vouchington-tooling 0.58.0 → 0.59.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 (74) hide show
  1. package/README.md +21 -0
  2. package/dist/agent-issue-labels/ensure-labels.d.mts +1 -1
  3. package/dist/agent-issue-labels/ensure-labels.mjs +1 -1
  4. package/dist/browser-session-runner/tail-queue.d.mts +1 -1
  5. package/dist/browser-session-runner/tail-queue.mjs +1 -1
  6. package/dist/cli/commands/gitleaks-directory-scan.d.mts +4 -0
  7. package/dist/cli/commands/gitleaks-directory-scan.mjs +9 -0
  8. package/dist/cli/commands/transient-retry.d.mts +13 -0
  9. package/dist/cli/commands/transient-retry.mjs +68 -0
  10. package/dist/cli/index.mjs +8 -53
  11. package/dist/cli/parse-forwarded-commands.d.mts +6 -0
  12. package/dist/cli/parse-forwarded-commands.mjs +4 -0
  13. package/dist/cli/parse.d.mts +6 -0
  14. package/dist/cli/script-paths.d.mts +5 -0
  15. package/dist/cli/script-paths.mjs +48 -0
  16. package/dist/cli/usage.d.mts +1 -1
  17. package/dist/cli/usage.mjs +7 -0
  18. package/dist/dead-code/baseline.d.mts +19 -0
  19. package/dist/dead-code/baseline.mjs +124 -0
  20. package/dist/dead-code/child-command.d.mts +6 -0
  21. package/dist/dead-code/child-command.mjs +107 -0
  22. package/dist/dead-code/cli.d.mts +5 -0
  23. package/dist/dead-code/cli.mjs +71 -0
  24. package/dist/dead-code/entry-roots.d.mts +7 -0
  25. package/dist/dead-code/entry-roots.mjs +43 -0
  26. package/dist/dead-code/fixture-deadline.test-helpers.d.mts +1 -0
  27. package/dist/dead-code/fixture-deadline.test-helpers.mjs +9 -0
  28. package/dist/dead-code/gate.d.mts +29 -0
  29. package/dist/dead-code/gate.mjs +33 -0
  30. package/dist/dead-code/gate.test-helpers.d.mts +14 -0
  31. package/dist/dead-code/gate.test-helpers.mjs +35 -0
  32. package/dist/dead-code/index.d.mts +9 -0
  33. package/dist/dead-code/index.mjs +7 -0
  34. package/dist/dead-code/scan.d.mts +11 -0
  35. package/dist/dead-code/scan.mjs +37 -0
  36. package/dist/dead-code/tracked-snapshot.d.mts +2 -0
  37. package/dist/dead-code/tracked-snapshot.mjs +72 -0
  38. package/dist/markdown/details-scope.d.mts +1 -1
  39. package/dist/markdown/details-scope.mjs +1 -1
  40. package/dist/transient-retry/attempts.d.mts +1 -1
  41. package/dist/transient-retry/attempts.mjs +1 -1
  42. package/dist/transient-retry/decision-evaluator.d.mts +3 -3
  43. package/dist/transient-retry/gh-api.d.mts +30 -0
  44. package/dist/transient-retry/gh-api.mjs +68 -0
  45. package/dist/transient-retry/github-actions-log.d.mts +7 -0
  46. package/dist/transient-retry/github-actions-log.mjs +33 -0
  47. package/dist/transient-retry/index.d.mts +15 -0
  48. package/dist/transient-retry/index.mjs +8 -0
  49. package/dist/transient-retry/log-stream.d.mts +12 -0
  50. package/dist/transient-retry/log-stream.mjs +39 -0
  51. package/dist/transient-retry/log-window.d.mts +18 -0
  52. package/dist/transient-retry/log-window.mjs +94 -0
  53. package/dist/transient-retry/rerun.d.mts +23 -0
  54. package/dist/transient-retry/rerun.mjs +68 -0
  55. package/dist/transient-retry/run-context-annotations.d.mts +7 -0
  56. package/dist/transient-retry/run-context-annotations.mjs +44 -0
  57. package/dist/transient-retry/run-context-jobs.d.mts +20 -0
  58. package/dist/transient-retry/run-context-jobs.mjs +54 -0
  59. package/dist/transient-retry/run-context-logs.d.mts +12 -0
  60. package/dist/transient-retry/run-context-logs.mjs +86 -0
  61. package/dist/transient-retry/run-context-rule-attempts.d.mts +14 -0
  62. package/dist/transient-retry/run-context-rule-attempts.mjs +65 -0
  63. package/dist/transient-retry/run-context-types.d.mts +49 -0
  64. package/dist/transient-retry/run-context-types.mjs +3 -0
  65. package/dist/transient-retry/run-context.d.mts +9 -0
  66. package/dist/transient-retry/run-context.mjs +25 -0
  67. package/dist/transient-retry/run-context.test-helpers.d.mts +16 -0
  68. package/dist/transient-retry/run-context.test-helpers.mjs +56 -0
  69. package/dist/transient-retry/types.d.mts +8 -7
  70. package/dist/vitest-diagnostics/vitest-worker-exit-diagnostics-reporter.mjs +1 -1
  71. package/dist/workflow-secrets-drift/gh.d.mts +1 -1
  72. package/dist/workflow-secrets-drift/gh.mjs +1 -1
  73. package/package.json +6 -1
  74. package/scripts/__pycache__/run_bounded_process.cpython-312.pyc +0 -0
@@ -0,0 +1,107 @@
1
+ import { spawn } from 'node:child_process';
2
+ export class ChildCommandCleanupError extends AggregateError {
3
+ processGroupId;
4
+ completion;
5
+ constructor(processGroupId, completion, errors) {
6
+ super(errors, 'Child command cleanup failed; owned process group may still be live', {
7
+ cause: errors[0],
8
+ });
9
+ this.processGroupId = processGroupId;
10
+ this.completion = completion;
11
+ }
12
+ }
13
+ class ChildCommandFailure extends Error {
14
+ code;
15
+ constructor(file, code, signal, stderr) {
16
+ super(`Command failed: ${file} (${signal ?? code}): ${stderr}`);
17
+ this.code = code;
18
+ }
19
+ }
20
+ // Finite fixtures opt into a deadline; repository scans retain no local cap.
21
+ export async function runChildCommand(file, args, cwd, remaining) {
22
+ const timeout = remaining?.();
23
+ await new Promise((resolve, reject) => {
24
+ let settleCapture = () => undefined;
25
+ const capture = new Promise((done) => {
26
+ settleCapture = done;
27
+ });
28
+ let expired = false;
29
+ let settled = false;
30
+ let failure = null;
31
+ let exit;
32
+ let timer;
33
+ let bytes = 0;
34
+ let stderr = '';
35
+ const child = spawn(file, args, { cwd, detached: true, stdio: ['ignore', 'pipe', 'pipe'] });
36
+ function stopGroup() {
37
+ if (settled || child.pid === undefined)
38
+ return;
39
+ try {
40
+ // eslint-disable-next-line no-restricted-properties -- terminate only this command's detached group, never the application process
41
+ process.kill(-child.pid, 'SIGKILL');
42
+ }
43
+ catch (err) {
44
+ if (err instanceof Error && 'code' in err && err.code === 'ESRCH')
45
+ return;
46
+ settled = true;
47
+ clearTimeout(timer);
48
+ const errors = failure ? [failure, err] : [err];
49
+ child.stdout.destroy();
50
+ child.stderr.destroy();
51
+ reject(new ChildCommandCleanupError(child.pid, capture, errors));
52
+ }
53
+ }
54
+ function output(chunk, isError) {
55
+ bytes += chunk.length;
56
+ if (bytes > 8 * 1024 * 1024) {
57
+ // Signal once: a later signal can hit the already-exited group leader and fail with EPERM.
58
+ if (failure !== null)
59
+ return;
60
+ failure = new Error('Child command output exceeded maxBuffer');
61
+ stopGroup();
62
+ }
63
+ else if (isError)
64
+ stderr += chunk.toString('utf8');
65
+ }
66
+ child.stdout.on('data', (chunk) => output(chunk, false));
67
+ child.stderr.on('data', (chunk) => output(chunk, true));
68
+ child.once('error', (err) => {
69
+ failure ??= err;
70
+ });
71
+ child.once('spawn', () => {
72
+ if (expired)
73
+ stopGroup();
74
+ });
75
+ child.once('exit', (code, signal) => {
76
+ exit = { code, signal };
77
+ stopGroup();
78
+ });
79
+ child.once('close', (code, signal) => {
80
+ const outcome = exit ?? { code, signal };
81
+ const commandFailure = outcome.code === 0
82
+ ? null
83
+ : new ChildCommandFailure(file, outcome.code, outcome.signal, stderr);
84
+ if (commandFailure && failure && commandFailure !== failure) {
85
+ failure = new AggregateError([failure, commandFailure], failure.message, { cause: failure });
86
+ }
87
+ else
88
+ failure ??= commandFailure;
89
+ settleCapture(failure);
90
+ clearTimeout(timer);
91
+ if (settled)
92
+ return;
93
+ settled = true;
94
+ if (failure)
95
+ reject(failure);
96
+ else
97
+ resolve();
98
+ });
99
+ if (timeout !== undefined) {
100
+ timer = setTimeout(() => {
101
+ expired = true;
102
+ failure ??= new Error('Child command exceeded the fixture deadline');
103
+ stopGroup();
104
+ }, timeout);
105
+ }
106
+ });
107
+ }
@@ -0,0 +1,5 @@
1
+ export declare const USAGE: string;
2
+ type Output = Pick<Console, 'error' | 'log'>;
3
+ /** Runs `vouchington dead-code`. Returns 2 for usage errors and 1 for gate failures. */
4
+ export declare function runDeadCodeCli(argv: readonly string[], output?: Output): Promise<number>;
5
+ export {};
@@ -0,0 +1,71 @@
1
+ import { parseArgs } from 'node:util';
2
+ import { runDeadCodeGate } from "./gate.mjs";
3
+ export const USAGE = 'Usage: vouchington dead-code --baseline <path> [--seed|--update] [--config <path>] ' +
4
+ '[--binary <path>] [--repo-root <path>] [--entry <glob>]... [--snapshot-ignore <glob>]... ' +
5
+ '[--exclude <glob>]...';
6
+ function message(err) {
7
+ return err instanceof Error ? err.message : String(err);
8
+ }
9
+ function summary(result) {
10
+ const { identities, trackedFiles, removed } = result;
11
+ if (result.operation === 'seed') {
12
+ return `Seeded dead-code baseline with ${identities} identities from ${trackedFiles} tracked files`;
13
+ }
14
+ if (result.operation === 'update') {
15
+ return `Dead-code baseline removed ${removed} stale identities; ${identities} remain`;
16
+ }
17
+ return `Dead-code baseline matches ${identities} identities across ${trackedFiles} tracked files`;
18
+ }
19
+ /** Runs `vouchington dead-code`. Returns 2 for usage errors and 1 for gate failures. */
20
+ export async function runDeadCodeCli(argv, output = console) {
21
+ let values;
22
+ try {
23
+ ;
24
+ ({ values } = parseArgs({
25
+ args: [...argv],
26
+ options: {
27
+ baseline: { type: 'string' },
28
+ seed: { type: 'boolean' },
29
+ update: { type: 'boolean' },
30
+ config: { type: 'string' },
31
+ binary: { type: 'string' },
32
+ 'repo-root': { type: 'string' },
33
+ entry: { type: 'string', multiple: true },
34
+ 'snapshot-ignore': { type: 'string', multiple: true },
35
+ exclude: { type: 'string', multiple: true },
36
+ },
37
+ strict: true,
38
+ }));
39
+ }
40
+ catch (err) {
41
+ output.error(`${USAGE}\n${message(err)}`);
42
+ return 2;
43
+ }
44
+ if (!values.baseline) {
45
+ output.error(`${USAGE}\n--baseline is required`);
46
+ return 2;
47
+ }
48
+ if (values.seed && values.update) {
49
+ output.error(`${USAGE}\n--seed and --update are mutually exclusive`);
50
+ return 2;
51
+ }
52
+ const operation = values.seed ? 'seed' : values.update ? 'update' : 'check';
53
+ try {
54
+ const result = await runDeadCodeGate({
55
+ repoRoot: values['repo-root'] ?? process.cwd(),
56
+ baselinePath: values.baseline,
57
+ operation,
58
+ configPath: values.config,
59
+ binary: values.binary,
60
+ entryRoots: values.entry,
61
+ snapshotIgnore: values['snapshot-ignore'],
62
+ excludeFindings: values.exclude,
63
+ });
64
+ output.log(summary(result));
65
+ return 0;
66
+ }
67
+ catch (err) {
68
+ output.error(message(err));
69
+ return 1;
70
+ }
71
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Resolves the live entry roots for a snapshot. Roots come from `override` when given,
3
+ * otherwise from the snapshot config's `deadCode.entry`. Every root must be a relative
4
+ * snapshot-internal glob that matches at least one file. An override is written into the
5
+ * snapshot's copy of the config (never the working tree).
6
+ */
7
+ export declare function resolveEntryRoots(snapshotRoot: string, configPath: string, override?: readonly string[]): Promise<string[]>;
@@ -0,0 +1,43 @@
1
+ import { glob, readFile, writeFile } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ function invalid(entry) {
4
+ return (typeof entry !== 'string' ||
5
+ entry.length === 0 ||
6
+ entry.startsWith('/') ||
7
+ entry.includes('\\') ||
8
+ entry.split('/').includes('..'));
9
+ }
10
+ async function assertLive(snapshotRoot, entries) {
11
+ if (entries.length === 0)
12
+ throw new Error('jscpd deadCode.entry must contain at least one root');
13
+ for (const entry of entries) {
14
+ if (invalid(entry))
15
+ throw new Error(`Invalid dead-code entry root: ${String(entry)}`);
16
+ let matches = 0;
17
+ for await (const _ of glob(entry, { cwd: snapshotRoot }))
18
+ matches += 1;
19
+ if (matches === 0)
20
+ throw new Error(`Stale dead-code entry root: ${String(entry)}`);
21
+ }
22
+ return [...entries];
23
+ }
24
+ /**
25
+ * Resolves the live entry roots for a snapshot. Roots come from `override` when given,
26
+ * otherwise from the snapshot config's `deadCode.entry`. Every root must be a relative
27
+ * snapshot-internal glob that matches at least one file. An override is written into the
28
+ * snapshot's copy of the config (never the working tree).
29
+ */
30
+ export async function resolveEntryRoots(snapshotRoot, configPath, override) {
31
+ const file = join(snapshotRoot, configPath);
32
+ const config = JSON.parse(await readFile(file, 'utf8'));
33
+ const configured = config?.deadCode?.entry;
34
+ if (override === undefined && !Array.isArray(configured)) {
35
+ throw new Error('jscpd deadCode.entry must contain at least one root');
36
+ }
37
+ const entries = await assertLive(snapshotRoot, override ?? configured);
38
+ if (override !== undefined) {
39
+ config.deadCode = { ...config.deadCode, entry: entries };
40
+ await writeFile(file, `${JSON.stringify(config, null, 2)}\n`);
41
+ }
42
+ return entries;
43
+ }
@@ -0,0 +1 @@
1
+ export declare function createFixtureDeadline(): () => number;
@@ -0,0 +1,9 @@
1
+ export function createFixtureDeadline() {
2
+ const deadline = process.hrtime.bigint() + 4000000000n;
3
+ return () => {
4
+ const milliseconds = Number((deadline - process.hrtime.bigint()) / 1000000n);
5
+ if (milliseconds <= 0)
6
+ throw new Error('Analyzer fixture case deadline exhausted');
7
+ return milliseconds;
8
+ };
9
+ }
@@ -0,0 +1,29 @@
1
+ export type DeadCodeOperation = 'check' | 'seed' | 'update';
2
+ export type DeadCodeGateOptions = {
3
+ /** Git repository whose tracked working tree is scanned. */
4
+ repoRoot: string;
5
+ /** Baseline JSON file, absolute or relative to `repoRoot`. */
6
+ baselinePath: string;
7
+ operation?: DeadCodeOperation;
8
+ /** jscpd config, relative to `repoRoot` and tracked. Defaults to `.jscpd.json`. */
9
+ configPath?: string | undefined;
10
+ /** jscpd executable. Defaults to `<repoRoot>/node_modules/.bin/jscpd`. */
11
+ binary?: string | undefined;
12
+ /** Live entry roots (files or globs). Defaults to the config's `deadCode.entry`. */
13
+ entryRoots?: readonly string[] | undefined;
14
+ /** Tracked-file globs left out of the snapshot. */
15
+ snapshotIgnore?: readonly string[] | undefined;
16
+ /** Finding path globs that are not counted. */
17
+ excludeFindings?: readonly string[] | undefined;
18
+ /** Optional deadline source forwarded to child processes. */
19
+ remaining?: (() => number) | undefined;
20
+ };
21
+ export type DeadCodeGateResult = {
22
+ operation: DeadCodeOperation;
23
+ identities: number;
24
+ trackedFiles: number;
25
+ /** Stale identities removed by `update`; 0 for `seed` and `check`. */
26
+ removed: number;
27
+ };
28
+ /** Scans a tracked snapshot and checks, seeds, or shrinks the committed baseline. */
29
+ export declare function runDeadCodeGate(options: DeadCodeGateOptions): Promise<DeadCodeGateResult>;
@@ -0,0 +1,33 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { mkdtemp, rm } from 'node:fs/promises';
3
+ import { tmpdir } from 'node:os';
4
+ import { join, resolve } from 'node:path';
5
+ import { reconcileBaseline } from "./baseline.mjs";
6
+ import { resolveEntryRoots } from "./entry-roots.mjs";
7
+ import { scanDeadCode } from "./scan.mjs";
8
+ import { copyTrackedWorkingTree } from "./tracked-snapshot.mjs";
9
+ /** Scans a tracked snapshot and checks, seeds, or shrinks the committed baseline. */
10
+ export async function runDeadCodeGate(options) {
11
+ const operation = options.operation ?? 'check';
12
+ const repoRoot = resolve(options.repoRoot);
13
+ const baselinePath = resolve(repoRoot, options.baselinePath);
14
+ const configPath = options.configPath ?? '.jscpd.json';
15
+ if (operation === 'seed' && existsSync(baselinePath)) {
16
+ throw new Error('Initial baseline already exists; --seed cannot replace it');
17
+ }
18
+ if (operation !== 'seed' && !existsSync(baselinePath)) {
19
+ throw new Error('Dead-code baseline is missing; --seed is required for first adoption');
20
+ }
21
+ const temporaryRoot = await mkdtemp(join(tmpdir(), 'dead-code-gate-'));
22
+ try {
23
+ const snapshotRoot = join(temporaryRoot, 'snapshot');
24
+ const trackedFiles = await copyTrackedWorkingTree(repoRoot, snapshotRoot, options.remaining, options.snapshotIgnore);
25
+ await resolveEntryRoots(snapshotRoot, configPath, options.entryRoots);
26
+ const current = await scanDeadCode(snapshotRoot, join(temporaryRoot, 'report'), options.binary ?? join(repoRoot, 'node_modules/.bin/jscpd'), options.remaining, { configPath, excludeGlobs: options.excludeFindings });
27
+ const removed = await reconcileBaseline(baselinePath, current, operation);
28
+ return { operation, identities: current.length, trackedFiles, removed };
29
+ }
30
+ finally {
31
+ await rm(temporaryRoot, { recursive: true, force: true });
32
+ }
33
+ }
@@ -0,0 +1,14 @@
1
+ export type Fixture = {
2
+ repo: string;
3
+ binary: string;
4
+ baseline: string;
5
+ };
6
+ export declare const orphan: {
7
+ category: string;
8
+ path: string;
9
+ name: string;
10
+ };
11
+ /** Writes a stand-in analyzer that records its config and emits `findings`. */
12
+ export declare function analyzer(directory: string, findings: unknown[]): Promise<string>;
13
+ /** A git repository with a tracked config, an entry file, and a tracked orphan. */
14
+ export declare function fixture(findings?: unknown[]): Promise<Fixture>;
@@ -0,0 +1,35 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { chmod, mkdtemp, mkdir, writeFile } from 'node:fs/promises';
3
+ import { tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ export const orphan = { category: 'unused-file', path: 'orphan.mts', name: '' };
6
+ /** Writes a stand-in analyzer that records its config and emits `findings`. */
7
+ export async function analyzer(directory, findings) {
8
+ const binary = join(directory, 'analyzer.mjs');
9
+ const report = { statistics: { files: 3, unparsed: 0 }, findings };
10
+ await writeFile(binary, `#!/usr/bin/env node
11
+ import { copyFileSync, mkdirSync, writeFileSync } from 'node:fs'
12
+ const out = process.argv[process.argv.indexOf('--output') + 1]
13
+ mkdirSync(out, { recursive: true })
14
+ copyFileSync(process.argv[process.argv.indexOf('--config') + 1], out + '/seen-config.json')
15
+ writeFileSync(out + '/basta-report.json', ${JSON.stringify(JSON.stringify(report))})
16
+ `);
17
+ await chmod(binary, 0o755);
18
+ return binary;
19
+ }
20
+ /** A git repository with a tracked config, an entry file, and a tracked orphan. */
21
+ export async function fixture(findings = [orphan]) {
22
+ const directory = await mkdtemp(join(tmpdir(), 'dead-code-gate-test-'));
23
+ const repo = join(directory, 'repo');
24
+ await mkdir(repo);
25
+ execFileSync('git', ['init', '-q'], { cwd: repo });
26
+ await writeFile(join(repo, 'main.mts'), 'export const live = 1\n');
27
+ await writeFile(join(repo, 'orphan.mts'), 'export const orphan = 2\n');
28
+ await writeFile(join(repo, '.jscpd.json'), JSON.stringify({ deadCode: { entry: ['main.mts'] } }));
29
+ execFileSync('git', ['add', '.'], { cwd: repo });
30
+ return {
31
+ repo,
32
+ binary: await analyzer(directory, findings),
33
+ baseline: join(repo, 'baseline.json'),
34
+ };
35
+ }
@@ -0,0 +1,9 @@
1
+ export { runDeadCodeCli, USAGE } from './cli.mts';
2
+ export { runDeadCodeGate } from './gate.mts';
3
+ export type { DeadCodeGateOptions, DeadCodeGateResult, DeadCodeOperation } from './gate.mts';
4
+ export { compareRows, parseBaseline, readBaseline, reconcileBaseline, rowsFromReport, writeBaseline, } from './baseline.mts';
5
+ export type { BaselineRow, FindingIdentity } from './baseline.mts';
6
+ export { resolveEntryRoots } from './entry-roots.mts';
7
+ export { createFindingFilter, scanDeadCode } from './scan.mts';
8
+ export { copyTrackedWorkingTree, trackedPaths } from './tracked-snapshot.mts';
9
+ export { ChildCommandCleanupError, runChildCommand } from './child-command.mts';
@@ -0,0 +1,7 @@
1
+ export { runDeadCodeCli, USAGE } from "./cli.mjs";
2
+ export { runDeadCodeGate } from "./gate.mjs";
3
+ export { compareRows, parseBaseline, readBaseline, reconcileBaseline, rowsFromReport, writeBaseline, } from "./baseline.mjs";
4
+ export { resolveEntryRoots } from "./entry-roots.mjs";
5
+ export { createFindingFilter, scanDeadCode } from "./scan.mjs";
6
+ export { copyTrackedWorkingTree, trackedPaths } from "./tracked-snapshot.mjs";
7
+ export { ChildCommandCleanupError, runChildCommand } from "./child-command.mjs";
@@ -0,0 +1,11 @@
1
+ import { type BaselineRow, type FindingIdentity } from './baseline.mts';
2
+ /**
3
+ * Builds the finding filter. Findings in test and spec files, unused files that are only
4
+ * used by tests, and any path matching one of `excludeGlobs` are not counted.
5
+ */
6
+ export declare function createFindingFilter(excludeGlobs?: readonly string[]): (finding: FindingIdentity, raw: Record<string, unknown>) => boolean;
7
+ /** Runs `binary --dead-code` over a snapshot and returns its baseline rows. */
8
+ export declare function scanDeadCode(snapshotRoot: string, reportRoot: string, binary: string, remaining?: () => number, options?: {
9
+ configPath?: string | undefined;
10
+ excludeGlobs?: readonly string[] | undefined;
11
+ }): Promise<BaselineRow[]>;
@@ -0,0 +1,37 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { join, matchesGlob } from 'node:path';
3
+ import { rowsFromReport } from "./baseline.mjs";
4
+ import { runChildCommand } from "./child-command.mjs";
5
+ /**
6
+ * Builds the finding filter. Findings in test and spec files, unused files that are only
7
+ * used by tests, and any path matching one of `excludeGlobs` are not counted.
8
+ */
9
+ export function createFindingFilter(excludeGlobs = []) {
10
+ return (finding, raw) => {
11
+ if (finding.category === 'unused-file' &&
12
+ Array.isArray(raw['reasons']) &&
13
+ raw['reasons'].includes('used-only-by-tests'))
14
+ return false;
15
+ if (excludeGlobs.some((glob) => matchesGlob(finding.path, glob)))
16
+ return false;
17
+ return !/\.(test|spec)\.[^/]+$/.test(finding.path);
18
+ };
19
+ }
20
+ /** Runs `binary --dead-code` over a snapshot and returns its baseline rows. */
21
+ export async function scanDeadCode(snapshotRoot, reportRoot, binary, remaining, options = {}) {
22
+ await runChildCommand(binary, [
23
+ '--dead-code',
24
+ '--no-gitignore',
25
+ '--config',
26
+ options.configPath ?? '.jscpd.json',
27
+ '--reporters',
28
+ 'json',
29
+ '--output',
30
+ reportRoot,
31
+ '--exit-code',
32
+ '0',
33
+ '.',
34
+ ], snapshotRoot, remaining);
35
+ const report = JSON.parse(await readFile(join(reportRoot, 'basta-report.json'), 'utf8'));
36
+ return rowsFromReport(report, createFindingFilter(options.excludeGlobs));
37
+ }
@@ -0,0 +1,2 @@
1
+ export declare function trackedPaths(repoRoot: string, remaining?: () => number): string[];
2
+ export declare function copyTrackedWorkingTree(repoRoot: string, snapshotRoot: string, remaining?: () => number, ignore?: readonly string[]): Promise<number>;
@@ -0,0 +1,72 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { copyFile, lstat, mkdir, readlink, realpath, symlink } from 'node:fs/promises';
3
+ import { dirname, isAbsolute, join, matchesGlob, relative, sep } from 'node:path';
4
+ function within(root, path) {
5
+ const difference = relative(root, path);
6
+ return difference !== '..' && !difference.startsWith(`..${sep}`) && !isAbsolute(difference);
7
+ }
8
+ export function trackedPaths(repoRoot, remaining) {
9
+ const output = execFileSync('git', ['ls-files', '--cached', '-z'], {
10
+ cwd: repoRoot,
11
+ maxBuffer: 20 * 1024 * 1024,
12
+ timeout: remaining?.(),
13
+ killSignal: 'SIGKILL',
14
+ });
15
+ return [...new Set(output.toString('utf8').split('\0').filter(Boolean))];
16
+ }
17
+ export async function copyTrackedWorkingTree(repoRoot, snapshotRoot, remaining, ignore = []) {
18
+ const root = await realpath(repoRoot);
19
+ const paths = trackedPaths(root, remaining).filter((path) => !ignore.some((glob) => matchesGlob(path, glob)));
20
+ let copied = 0;
21
+ for (let index = 0; index < paths.length; index += 64) {
22
+ const batch = await Promise.all(paths.slice(index, index + 64).map(async (path) => {
23
+ const source = join(root, path);
24
+ const target = join(snapshotRoot, path);
25
+ if (!within(root, source) || !within(snapshotRoot, target)) {
26
+ throw new Error(`Tracked path escapes the repository: ${path}`);
27
+ }
28
+ let sourceParent;
29
+ try {
30
+ sourceParent = await realpath(dirname(source));
31
+ }
32
+ catch (err) {
33
+ if (err.code === 'ENOENT')
34
+ return false; // tracked deletion
35
+ throw err;
36
+ }
37
+ if (!within(root, sourceParent))
38
+ throw new Error(`Tracked path escapes the repository: ${path}`);
39
+ let info;
40
+ try {
41
+ info = await lstat(source);
42
+ }
43
+ catch (err) {
44
+ if (err.code === 'ENOENT')
45
+ return false; // tracked deletion
46
+ throw err;
47
+ }
48
+ await mkdir(dirname(target), { recursive: true });
49
+ const resolved = await realpath(source);
50
+ if (!within(root, resolved))
51
+ throw new Error(`Tracked path escapes the repository: ${path}`);
52
+ if (info.isSymbolicLink()) {
53
+ const link = await readlink(source);
54
+ const targetLink = isAbsolute(link)
55
+ ? relative(dirname(target), join(snapshotRoot, relative(root, resolved)))
56
+ : link;
57
+ await symlink(targetLink, target);
58
+ }
59
+ else if (info.isFile()) {
60
+ await copyFile(source, target);
61
+ }
62
+ else {
63
+ throw new Error(`Tracked path is neither a file nor an internal symlink: ${path}`);
64
+ }
65
+ return true;
66
+ }));
67
+ copied += batch.filter(Boolean).length;
68
+ }
69
+ if (copied === 0)
70
+ throw new Error('Tracked snapshot contains no files');
71
+ return copied;
72
+ }
@@ -1,9 +1,9 @@
1
1
  import type { MarkdownSectionsDiagnostic } from './document-types.mts';
2
2
  /** Tracks disclosure tags from HTML nodes, never from fenced code or Markdown comments. */
3
3
  export declare class DetailsScope {
4
- private readonly markdown;
5
4
  readonly diagnostics: MarkdownSectionsDiagnostic[];
6
5
  private readonly frames;
6
+ private readonly markdown;
7
7
  constructor(markdown: string);
8
8
  get visible(): boolean;
9
9
  acceptHtml(html: string, startOffset: number): void;
@@ -1,8 +1,8 @@
1
1
  /** Tracks disclosure tags from HTML nodes, never from fenced code or Markdown comments. */
2
2
  export class DetailsScope {
3
- markdown;
4
3
  diagnostics = [];
5
4
  frames = [];
5
+ markdown;
6
6
  constructor(markdown) {
7
7
  this.markdown = markdown;
8
8
  }
@@ -1,5 +1,5 @@
1
1
  /**
2
2
  * Normalizes a provider's attempt count when earlier attempts produced no targets.
3
- * Provider API fetching and parsing intentionally remain outside this package.
3
+ * Fetching a provider's run state lives in `run-context*.mts`.
4
4
  */
5
5
  export declare function deriveRetryAttempt(runAttempt: number, priorTargetCounts: readonly number[]): number;
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Normalizes a provider's attempt count when earlier attempts produced no targets.
3
- * Provider API fetching and parsing intentionally remain outside this package.
3
+ * Fetching a provider's run state lives in `run-context*.mts`.
4
4
  */
5
5
  export function deriveRetryAttempt(runAttempt, priorTargetCounts) {
6
6
  const emptyPriorAttempts = priorTargetCounts.filter((count) => count === 0).length;
@@ -12,9 +12,9 @@ export type DecisionResult = {
12
12
  matchedRule: string;
13
13
  reason: NoMatchReason;
14
14
  };
15
- export interface EvaluateRulesOptions {
16
- afterRuleEvaluated?: (context: RetryContext, rule: RetryRule) => Promise<void> | void;
15
+ export interface EvaluateRulesOptions<C extends RetryContext = RetryContext> {
16
+ afterRuleEvaluated?: (context: C, rule: RetryRule<C>) => Promise<void> | void;
17
17
  /** Defaults to `no-match`. Use `dispatch` when unmatched work should leave the retry engine. */
18
18
  unmatchedDecision?: 'no-match' | 'dispatch';
19
19
  }
20
- export declare function decide(context: RetryContext, rules: readonly RetryRule[], options?: EvaluateRulesOptions): Promise<DecisionResult>;
20
+ export declare function decide<C extends RetryContext = RetryContext>(context: C, rules: readonly RetryRule<C>[], options?: EvaluateRulesOptions<C>): Promise<DecisionResult>;
@@ -0,0 +1,30 @@
1
+ import { type RunTextCommand } from '../gh-cli/exec.mts';
2
+ /** Substrings of a failed `gh` call that mark a transport hiccup worth retrying. */
3
+ export declare const DEFAULT_RETRYABLE_MARKERS: readonly string[];
4
+ /** The largest stdout one buffered `gh api` call may return; job logs are streamed, not buffered. */
5
+ export declare const API_MAX_BUFFER_BYTES: number;
6
+ export interface GhApiOptions {
7
+ /** Runs `gh` with the given argv and returns stdout. Defaults to {@link createGhRunner}. */
8
+ run?: RunTextCommand;
9
+ attempts?: number;
10
+ retryableMarkers?: readonly string[];
11
+ sleep?: (ms: number) => Promise<void>;
12
+ warn?: (message: string) => void;
13
+ }
14
+ export interface GhApi {
15
+ /** `gh api <args>` with bounded retries on transport errors. Resolves to stdout. */
16
+ call: (args: string[]) => Promise<string>;
17
+ isRetryable: (error: unknown) => boolean;
18
+ sleep: (ms: number) => Promise<void>;
19
+ /** Runs an arbitrary `gh` argv once, without retries. */
20
+ run: RunTextCommand;
21
+ }
22
+ /**
23
+ * Builds the default `gh` runner. `tokenEnv` names the environment variable that holds the
24
+ * token; when set and present it is passed to `gh` as `GH_TOKEN`. Otherwise `gh` uses its own
25
+ * credentials.
26
+ */
27
+ export declare function createGhRunner(tokenEnv?: string): RunTextCommand;
28
+ /** The `gh` child environment: forced color removed, and `tokenEnv`'s value exposed as `GH_TOKEN`. */
29
+ export declare function ghEnvWithToken(tokenEnv?: string): (env: NodeJS.ProcessEnv) => NodeJS.ProcessEnv;
30
+ export declare function createGhApi({ run, attempts, retryableMarkers, sleep, warn, }?: GhApiOptions): GhApi;