Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(cli): require explicit --commit to file gap reports; never file in non-interactive mode by default (#2400)

Joey69f622e68144
diff --git a/packages/cli/src/commands/gap-report.mjs b/packages/cli/src/commands/gap-report.mjs
index 9bd6928a6c..7b25fbeb36 100644
--- a/packages/cli/src/commands/gap-report.mjs
+++ b/packages/cli/src/commands/gap-report.mjs
@@ -13,6 +13,7 @@ import * as fs from 'node:fs';
import * as path from 'node:path';
import * as p from '@clack/prompts';
import {
+ buildGapReportPreview,
checkGhCli,
createGapReport,
loadGapReportConfig,
@@ -21,6 +22,54 @@ import {
import {getRunPrefix} from '../utils/package-manager.mjs';
import {jsonOut, jsonError} from '../lib/json.mjs';
+/**
+ * Decide whether we're in a context safe to actually file a report.
+ *
+ * Returns true ONLY when the user has explicitly opted in via --commit, OR
+ * we're in an interactive TTY session AND --dry-run was not requested.
+ *
+ * Defaults are intentionally conservative: in CI, when piped, when --json is
+ * set, or when neither --commit nor a TTY is present, we dry-run.
+ */
+export function shouldActuallyFile({
+ commit = false,
+ dryRun = false,
+ json = false,
+ isTTY = process.stdout.isTTY,
+} = {}) {
+ if (dryRun) return false;
+ if (commit) return true;
+ if (json) return false;
+ if (!isTTY) return false;
+ // Interactive TTY without --commit: caller must show a confirmation prompt.
+ return true;
+}
+
+/**
+ * Render a human-readable preview of the gap report that would be filed.
+ */
+export function formatPreview(preview) {
+ const lines = [];
+ if (preview.mode === 'github') {
+ lines.push(`Would file GitHub issue on ${preview.repo}:`);
+ } else if (preview.mode === 'custom') {
+ lines.push(`Would invoke custom command: ${preview.command}`);
+ } else {
+ lines.push('Gap reporting is disabled (no action would be taken).');
+ return lines.join('\n');
+ }
+ lines.push('');
+ lines.push(` Title: ${preview.title}`);
+ lines.push('');
+ lines.push(' Body:');
+ for (const ln of preview.body.split('\n')) {
+ lines.push(` ${ln}`);
+ }
+ lines.push('');
+ lines.push(' Labels: gap-report');
+ return lines.join('\n');
+}
+
function isCancel(value) {
if (p.isCancel(value)) {
p.cancel('Gap report cancelled.');
@@ -174,6 +223,22 @@ export function registerGapReport(program) {
.option('--category <category>', 'Gap category')
.option('--reason <reason>', 'What capability was missing')
.option('--list-categories', 'List valid gap categories')
+ .option(
+ '--dry-run',
+ 'Print the issue that would be filed without contacting GitHub. Default in CI / non-TTY / --json mode.',
+ )
+ .option(
+ '--commit',
+ 'Actually file the issue. Required in non-interactive mode (CI, piped, --json).',
+ )
+ .addHelpText(
+ 'after',
+ '\nSafety:\n' +
+ ' Set XDS_GAP_REPORT=off to disable gap reporting entirely.\n' +
+ ' In non-interactive mode (CI, piped stdout, --json), gap-report is\n' +
+ ' dry-run by default. Pass --commit to actually file an issue.\n' +
+ ' In interactive mode, you will always be shown a confirmation prompt.\n',
+ )
.action(async options => {
const json = program.opts().json || false;
@@ -189,17 +254,27 @@ export function registerGapReport(program) {
if (!config.enabled) {
if (json) return jsonError('Gap reporting is disabled');
console.log(
- `Gap reporting is disabled. Run \`${getRunPrefix()} xds gap-report setup\` to configure.`,
+ `Gap reporting is disabled (XDS_GAP_REPORT=off or xds.config.mjs).\n` +
+ `Run \`${getRunPrefix()} xds gap-report setup\` to configure.`,
);
return;
}
- if (!config.command && !checkGhCli()) {
- console.error(
- 'Error: GitHub CLI (gh) is not installed or not authenticated.\n' +
- 'Install it from https://cli.github.com and run `gh auth login`.\n\n' +
- `Or run \`${getRunPrefix()} xds gap-report setup\` to configure a custom command.`,
- );
+ // We only need gh available when we'd actually file. For dry-run, skip
+ // the gh check so users can preview output in CI without `gh` installed.
+ const willFile = shouldActuallyFile({
+ commit: options.commit,
+ dryRun: options.dryRun,
+ json,
+ });
+
+ if (willFile && !config.command && !checkGhCli()) {
+ const msg =
+ 'GitHub CLI (gh) is not installed or not authenticated.\n' +
+ 'Install it from https://cli.github.com and run `gh auth login`.\n\n' +
+ `Or run \`${getRunPrefix()} xds gap-report setup\` to configure a custom command.`;
+ if (json) return jsonError(msg);
+ console.error(`Error: ${msg}`);
process.exit(1);
}
@@ -223,6 +298,36 @@ export function registerGapReport(program) {
process.exit(1);
}
+ const preview = buildGapReportPreview({
+ component: options.component,
+ category: options.category,
+ intention: options.reason,
+ source: 'cli',
+ });
+
+ if (!willFile) {
+ // DRY-RUN: print what would be filed and exit cleanly.
+ if (json) {
+ return jsonOut('gap-report.dryRun', {
+ dryRun: true,
+ wouldFile: preview.mode !== 'disabled',
+ mode: preview.mode,
+ title: preview.title,
+ body: preview.body,
+ repo: preview.repo,
+ command: preview.command || null,
+ hint:
+ 'Re-run with --commit to actually file. ' +
+ 'Default is dry-run in non-interactive contexts.',
+ });
+ }
+ console.log(formatPreview(preview));
+ console.log(
+ '\n[dry-run] Nothing was filed. Re-run with --commit to file this report.',
+ );
+ return;
+ }
+
try {
const url = createGapReport({
component: options.component,
@@ -286,17 +391,49 @@ export function registerGapReport(program) {
}),
);
+ const previewArgs = {
+ component: component.trim(),
+ category,
+ intention: intention.trim(),
+ detail: detail?.trim() || undefined,
+ source: 'interactive',
+ };
+
+ const preview = buildGapReportPreview(previewArgs);
+
+ // Always show the user exactly what would be filed before sending.
+ p.note(
+ `${preview.mode === 'github' ? `Repo: ${preview.repo}` : `Custom command: ${preview.command}`}\n\n` +
+ `Title:\n ${preview.title}\n\n` +
+ `Body:\n${preview.body
+ .split('\n')
+ .map(l => ` ${l}`)
+ .join('\n')}`,
+ 'Preview — this is exactly what will be filed',
+ );
+
+ if (options.dryRun) {
+ p.outro('[dry-run] Nothing filed.');
+ return;
+ }
+
+ const confirm = isCancel(
+ await p.confirm({
+ message: 'File this gap report now?',
+ initialValue: false,
+ }),
+ );
+
+ if (!confirm) {
+ p.outro('Cancelled — nothing was filed.');
+ return;
+ }
+
const s = p.spinner();
s.start('Filing gap report');
try {
- const url = createGapReport({
- component: component.trim(),
- category,
- intention: intention.trim(),
- detail: detail?.trim() || undefined,
- source: 'interactive',
- });
+ const url = createGapReport(previewArgs);
s.stop(url ? 'Gap report filed' : 'Gap reporting is disabled');
if (url) {
p.log.success(url);
diff --git a/packages/cli/src/commands/gap-report.test.mjs b/packages/cli/src/commands/gap-report.test.mjs
new file mode 100644
index 0000000000..cd91e20739
--- /dev/null
+++ b/packages/cli/src/commands/gap-report.test.mjs
@@ -0,0 +1,163 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * Tests for gap-report safety gates: dry-run-by-default in non-interactive
+ * mode, --commit required to actually file, --no-report suppression in swizzle,
+ * and XDS_GAP_REPORT=off honored everywhere.
+ *
+ * Regression cases for issues #2370 and #2371: real gap-report issues filed
+ * unintentionally in CI/non-TTY runs.
+ */
+
+import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
+import {shouldActuallyFile, formatPreview} from './gap-report.mjs';
+
+describe('shouldActuallyFile', () => {
+ it('returns false in non-TTY mode by default (dry-run by default in CI)', () => {
+ expect(shouldActuallyFile({isTTY: false})).toBe(false);
+ });
+
+ it('returns false when --json is set, even with TTY', () => {
+ expect(shouldActuallyFile({isTTY: true, json: true})).toBe(false);
+ });
+
+ it('returns false when --dry-run is explicitly set', () => {
+ expect(shouldActuallyFile({isTTY: true, dryRun: true})).toBe(false);
+ });
+
+ it('returns true in TTY mode without dry-run/json (interactive prompts will gate)', () => {
+ expect(shouldActuallyFile({isTTY: true})).toBe(true);
+ });
+
+ it('returns true with --commit even in non-TTY mode', () => {
+ expect(shouldActuallyFile({isTTY: false, commit: true})).toBe(true);
+ });
+
+ it('--commit overrides --json being set', () => {
+ expect(shouldActuallyFile({isTTY: false, commit: true, json: true})).toBe(
+ true,
+ );
+ });
+
+ it('--dry-run wins over --commit (safety)', () => {
+ expect(
+ shouldActuallyFile({isTTY: true, commit: true, dryRun: true}),
+ ).toBe(false);
+ });
+});
+
+describe('formatPreview', () => {
+ it('renders a github-mode preview with title, body, and repo', () => {
+ const out = formatPreview({
+ mode: 'github',
+ repo: 'facebookexperimental/xds',
+ title: '[gap] Button: missing compact variant',
+ body: '## User Intention\n\nNeed a compact variant',
+ });
+ expect(out).toContain('Would file GitHub issue on facebookexperimental/xds');
+ expect(out).toContain('[gap] Button');
+ expect(out).toContain('Need a compact variant');
+ expect(out).toContain('Labels: gap-report');
+ });
+
+ it('renders disabled mode without filing instructions', () => {
+ const out = formatPreview({mode: 'disabled'});
+ expect(out).toContain('Gap reporting is disabled');
+ expect(out).not.toContain('Would file');
+ });
+
+ it('renders custom-command mode', () => {
+ const out = formatPreview({
+ mode: 'custom',
+ command: './scripts/report.sh',
+ title: 't',
+ body: 'b',
+ });
+ expect(out).toContain('Would invoke custom command: ./scripts/report.sh');
+ });
+});
+
+describe('XDS_GAP_REPORT=off env var', () => {
+ let originalEnv;
+ beforeEach(() => {
+ originalEnv = process.env.XDS_GAP_REPORT;
+ });
+ afterEach(() => {
+ if (originalEnv === undefined) delete process.env.XDS_GAP_REPORT;
+ else process.env.XDS_GAP_REPORT = originalEnv;
+ vi.resetModules();
+ });
+
+ it('disables gap reporting when set to "off"', async () => {
+ process.env.XDS_GAP_REPORT = 'off';
+ vi.resetModules();
+ const {loadGapReportConfig, createGapReport} = await import(
+ '../utils/github.mjs'
+ );
+ expect(loadGapReportConfig().enabled).toBe(false);
+
+ // createGapReport must return null and never invoke gh.
+ const result = createGapReport({
+ component: 'Button',
+ category: 'other',
+ intention: 'test',
+ });
+ expect(result).toBeNull();
+ });
+
+ it('also accepts "false" and "0" as disable values', async () => {
+ process.env.XDS_GAP_REPORT = 'false';
+ vi.resetModules();
+ let mod = await import('../utils/github.mjs');
+ expect(mod.loadGapReportConfig().enabled).toBe(false);
+
+ process.env.XDS_GAP_REPORT = '0';
+ vi.resetModules();
+ mod = await import('../utils/github.mjs');
+ expect(mod.loadGapReportConfig().enabled).toBe(false);
+ });
+});
+
+describe('buildGapReportPreview', () => {
+ let originalEnv;
+ beforeEach(() => {
+ originalEnv = process.env.XDS_GAP_REPORT;
+ // Force github mode (default) for these tests.
+ delete process.env.XDS_GAP_REPORT;
+ });
+ afterEach(() => {
+ if (originalEnv === undefined) delete process.env.XDS_GAP_REPORT;
+ else process.env.XDS_GAP_REPORT = originalEnv;
+ });
+
+ it('renders title and body without invoking gh', async () => {
+ vi.resetModules();
+ const {buildGapReportPreview} = await import('../utils/github.mjs');
+ const preview = buildGapReportPreview({
+ component: 'Button',
+ category: 'missing_variant',
+ intention: 'Need compact variant for tables',
+ });
+ expect(preview.mode).toBe('github');
+ expect(preview.enabled).toBe(true);
+ expect(preview.title).toBe(
+ '[gap] Button: Need compact variant for tables',
+ );
+ expect(preview.body).toContain('| **Component** | Button |');
+ expect(preview.body).toContain('Need compact variant for tables');
+ expect(preview.repo).toBe('facebookexperimental/xds');
+ });
+
+ it('reports disabled mode when env var is off', async () => {
+ process.env.XDS_GAP_REPORT = 'off';
+ vi.resetModules();
+ const {buildGapReportPreview} = await import('../utils/github.mjs');
+ const preview = buildGapReportPreview({
+ component: 'Button',
+ category: 'other',
+ intention: 'x',
+ });
+ expect(preview.mode).toBe('disabled');
+ expect(preview.enabled).toBe(false);
+ });
+});
diff --git a/packages/cli/src/commands/swizzle-gap-safety.test.mjs b/packages/cli/src/commands/swizzle-gap-safety.test.mjs
new file mode 100644
index 0000000000..7bd44701c3
--- /dev/null
+++ b/packages/cli/src/commands/swizzle-gap-safety.test.mjs
@@ -0,0 +1,259 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * End-to-end safety tests for `xds swizzle --gap` and `xds gap-report`.
+ *
+ * Critical: these tests must NEVER actually invoke `gh issue create`. We
+ * defend in depth:
+ *
+ * 1. We spawn the CLI in a non-TTY pipe → triggers the dry-run gate.
+ * 2. We set XDS_GAP_REPORT=off as an extra belt-and-suspenders for tests
+ * that would otherwise risk filing.
+ * 3. We unset GH_TOKEN so that any unexpected `gh` invocation fails fast.
+ * 4. We put a sabotaged `gh` shim earlier on PATH that blocks real
+ * `gh issue create` calls and writes a marker file. Any successful
+ * "filing" path leaves a marker we can assert against — so a regression
+ * is detected even if the gate silently breaks.
+ *
+ * Regression cases for issues #2370 and #2371: real gap-report issues filed
+ * unintentionally during a verification run because the non-interactive path
+ * called `gh issue create` with no confirmation.
+ */
+
+import {describe, it, expect, beforeAll, afterAll} from 'vitest';
+import {spawnSync} from 'node:child_process';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import {fileURLToPath} from 'node:url';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const cliBin = path.resolve(__dirname, '../../bin/xds.mjs');
+const repoRoot = path.resolve(__dirname, '../../../..');
+
+let shimDir;
+let markerFile;
+let baseEnv;
+
+beforeAll(() => {
+ shimDir = fs.mkdtempSync(path.join(os.tmpdir(), 'xds-gh-shim-'));
+ markerFile = path.join(shimDir, 'gh-issue-create-was-called.marker');
+
+ // Sabotaged `gh` shim. Records ONLY `gh issue create` invocations to the
+ // marker file, since that's the only command we want to detect as a
+ // "would-have-filed" event. Other subcommands (auth status, label create)
+ // succeed silently so they don't break the gh availability check or the
+ // label-ensure path.
+ const shim = `#!/usr/bin/env node
+import * as fs from 'node:fs';
+const args = process.argv.slice(2);
+const isIssueCreate = args[0] === 'issue' && args[1] === 'create';
+if (isIssueCreate) {
+ fs.appendFileSync(${JSON.stringify(markerFile)}, JSON.stringify(args) + '\\n');
+ process.stderr.write('TEST GUARD: real gh issue create blocked\\n');
+ process.exit(1);
+}
+// Other commands (auth status, label create) succeed silently.
+process.exit(0);
+`;
+ fs.writeFileSync(path.join(shimDir, 'gh'), shim);
+ fs.chmodSync(path.join(shimDir, 'gh'), 0o755);
+
+ baseEnv = {
+ ...process.env,
+ PATH: `${shimDir}:${process.env.PATH}`,
+ // Belt-and-suspenders: even if a gate breaks, this disables the feature.
+ // For tests that need the feature on, individual cases override this.
+ GH_TOKEN: '',
+ };
+});
+
+afterAll(() => {
+ fs.rmSync(shimDir, {recursive: true, force: true});
+});
+
+function runXds(args, {env = {}, cwd = repoRoot} = {}) {
+ // Reset marker for each run.
+ if (fs.existsSync(markerFile)) fs.unlinkSync(markerFile);
+ const result = spawnSync('node', [cliBin, ...args], {
+ cwd,
+ env: {...baseEnv, ...env},
+ encoding: 'utf-8',
+ });
+ return {
+ ...result,
+ // True iff the CLI tried to call `gh issue create` — the actual filing
+ // operation. Other gh subcommands (auth status, label create) are
+ // ignored as benign.
+ ghWasCalled: fs.existsSync(markerFile),
+ ghCallArgs: fs.existsSync(markerFile)
+ ? fs.readFileSync(markerFile, 'utf-8')
+ : null,
+ };
+}
+
+describe('gap-report: dry-run by default in non-interactive mode', () => {
+ it('non-TTY pipe with all required flags → dry-run, exit 0, no gh call', () => {
+ const r = runXds([
+ 'gap-report',
+ '--component',
+ 'Button',
+ '--category',
+ 'missing_variant',
+ '--reason',
+ 'Test that we never file in non-interactive mode',
+ ]);
+ expect(r.status).toBe(0);
+ expect(r.ghWasCalled).toBe(false);
+ expect(r.stdout).toMatch(/dry-run/i);
+ expect(r.stdout).toMatch(/Re-run with --commit/i);
+ // Preview should include the title we'd file.
+ expect(r.stdout).toContain('Button');
+ });
+
+ it('--json mode in non-TTY → structured dry-run JSON, no gh call', () => {
+ const r = runXds([
+ '--json',
+ 'gap-report',
+ '--component',
+ 'Button',
+ '--category',
+ 'missing_variant',
+ '--reason',
+ 'JSON dry-run',
+ ]);
+ expect(r.status).toBe(0);
+ expect(r.ghWasCalled).toBe(false);
+ // jsonOut pretty-prints across multiple lines; parse the whole stdout
+ // as JSON (after stripping any trailing whitespace).
+ const parsed = JSON.parse(r.stdout.trim());
+ expect(parsed.type).toBe('gap-report.dryRun');
+ expect(parsed.data.dryRun).toBe(true);
+ expect(parsed.data.title).toContain('Button');
+ expect(parsed.data.wouldFile).toBe(true);
+ });
+
+ it('XDS_GAP_REPORT=off → no gh call, even with --commit flag', () => {
+ const r = runXds(
+ [
+ 'gap-report',
+ '--component',
+ 'Button',
+ '--category',
+ 'other',
+ '--reason',
+ 'should be disabled',
+ '--commit',
+ ],
+ {env: {XDS_GAP_REPORT: 'off'}},
+ );
+ // Should exit 0 with a "disabled" message; never calls gh.
+ expect(r.ghWasCalled).toBe(false);
+ expect(r.status).toBe(0);
+ expect(r.stdout + r.stderr).toMatch(/disabled/i);
+ });
+
+ it('--commit in non-TTY mode WOULD invoke gh (verified via shim)', () => {
+ // This proves --commit actually engages the file path. Our shim exits 1
+ // so the CLI will report failure, but the marker proves gh was invoked
+ // with the expected args.
+ const r = runXds(
+ [
+ 'gap-report',
+ '--component',
+ 'Button',
+ '--category',
+ 'other',
+ '--reason',
+ 'commit flag should engage filing',
+ '--commit',
+ ],
+ {env: {XDS_GAP_REPORT: ''}}, // re-enable feature; shim will block real call
+ );
+ expect(r.ghWasCalled).toBe(true);
+ expect(r.ghCallArgs).toContain('issue');
+ expect(r.ghCallArgs).toContain('create');
+ expect(r.ghCallArgs).toContain('facebookexperimental/xds');
+ });
+});
+
+describe('swizzle --gap respects safety gates', () => {
+ it('swizzle --gap in non-TTY → dry-run, no gh call', () => {
+ const r = runXds([
+ 'swizzle',
+ 'Button',
+ '--output',
+ path.join(os.tmpdir(), 'xds-swizzle-test-' + Date.now()),
+ '--gap',
+ 'Need a compact variant',
+ '--gap-category',
+ 'missing_variant',
+ ]);
+ expect(r.ghWasCalled).toBe(false);
+ expect(r.status).toBe(0);
+ expect(r.stdout).toMatch(/dry-run/i);
+ });
+
+ it('swizzle --gap --no-report → never engages gap reporting at all', () => {
+ const outDir = path.join(os.tmpdir(), 'xds-swizzle-noreport-' + Date.now());
+ const r = runXds([
+ 'swizzle',
+ 'Button',
+ '--output',
+ outDir,
+ '--gap',
+ 'Should be suppressed entirely',
+ '--gap-category',
+ 'missing_variant',
+ '--no-report',
+ ]);
+ expect(r.ghWasCalled).toBe(false);
+ expect(r.status).toBe(0);
+ // Should not even show a dry-run preview — reporting is suppressed.
+ expect(r.stdout).toMatch(/suppressed/i);
+ expect(r.stdout).not.toMatch(/Would file GitHub issue/i);
+ });
+
+ it('swizzle --gap --no-report --commit → STILL no gh call (no-report wins)', () => {
+ // Critical regression test: --no-report must beat --commit for the
+ // --gap auto-file path. Otherwise CI scripts could file issues.
+ const outDir = path.join(os.tmpdir(), 'xds-swizzle-norep2-' + Date.now());
+ const r = runXds(
+ [
+ 'swizzle',
+ 'Button',
+ '--output',
+ outDir,
+ '--gap',
+ 'should never file',
+ '--gap-category',
+ 'other',
+ '--no-report',
+ '--commit',
+ ],
+ {env: {XDS_GAP_REPORT: ''}},
+ );
+ expect(r.ghWasCalled).toBe(false);
+ expect(r.status).toBe(0);
+ });
+
+ it('swizzle --gap with XDS_GAP_REPORT=off → no gh call', () => {
+ const outDir = path.join(os.tmpdir(), 'xds-swizzle-envoff-' + Date.now());
+ const r = runXds(
+ [
+ 'swizzle',
+ 'Button',
+ '--output',
+ outDir,
+ '--gap',
+ 'should be disabled by env',
+ '--gap-category',
+ 'other',
+ '--commit',
+ ],
+ {env: {XDS_GAP_REPORT: 'off'}},
+ );
+ expect(r.ghWasCalled).toBe(false);
+ expect(r.status).toBe(0);
+ });
+});
diff --git a/packages/cli/src/commands/swizzle.mjs b/packages/cli/src/commands/swizzle.mjs
index 973e1f5efa..88bd401c36 100644
--- a/packages/cli/src/commands/swizzle.mjs
+++ b/packages/cli/src/commands/swizzle.mjs
@@ -17,11 +17,13 @@ import * as p from '@clack/prompts';
import {findCoreDir, listComponents} from '../utils/paths.mjs';
import {jsonOut, jsonError} from '../lib/json.mjs';
import {
+ buildGapReportPreview,
checkGhCli,
createGapReport,
loadGapReportConfig,
GAP_CATEGORIES,
} from '../utils/github.mjs';
+import {shouldActuallyFile, formatPreview} from './gap-report.mjs';
/**
* Rewrite relative imports that point outside the component directory
@@ -63,7 +65,18 @@ export function registerSwizzle(program) {
.option('--list', 'List available components')
.option('--gap <reason>', 'File a gap report explaining why you swizzled')
.option('--gap-category <category>', 'Gap category (for --gap mode)')
- .option('--no-report', 'Suppress the interactive gap report prompt')
+ .option(
+ '--no-report',
+ 'Suppress all gap reporting (interactive prompt AND --gap auto-filing)',
+ )
+ .option(
+ '--dry-run',
+ 'For --gap: print the issue that would be filed without contacting GitHub. Default in non-TTY / --json mode.',
+ )
+ .option(
+ '--commit',
+ 'For --gap: actually file the issue. Required in non-interactive mode.',
+ )
.action(async (component, options) => {
const coreDir = findCoreDir(process.cwd());
const json = program.opts().json || false;
@@ -134,29 +147,84 @@ export function registerSwizzle(program) {
const gapConfig = loadGapReportConfig();
let gapReportUrl = null;
+ let gapDryRunPreview = null;
- if (options.gap) {
- if (gapConfig.enabled && (gapConfig.command || checkGhCli())) {
- const category = options.gapCategory || 'other';
+ // CRITICAL: --no-report must suppress BOTH the interactive prompt AND
+ // the --gap auto-file path. Previously --gap bypassed --no-report.
+ // commander sets options.report to false for `--no-report`.
+ const reportingSuppressed = options.report === false;
+
+ if (options.gap && !reportingSuppressed && gapConfig.enabled) {
+ const category = options.gapCategory || 'other';
+ const previewArgs = {
+ component: dirName,
+ category,
+ intention: options.gap,
+ source: 'llm-auto',
+ };
+
+ const willFile = shouldActuallyFile({
+ commit: options.commit,
+ dryRun: options.dryRun,
+ json,
+ });
+
+ const preview = buildGapReportPreview(previewArgs);
+
+ if (!willFile) {
+ // Dry-run: do NOT call gh. Surface what would have been filed.
+ gapDryRunPreview = {
+ dryRun: true,
+ wouldFile: preview.mode !== 'disabled',
+ mode: preview.mode,
+ title: preview.title,
+ body: preview.body,
+ repo: preview.repo,
+ command: preview.command || null,
+ };
+ } else if (gapConfig.command || checkGhCli()) {
try {
- gapReportUrl = createGapReport({
- component: dirName,
- category,
- intention: options.gap,
- source: 'llm-auto',
- });
+ gapReportUrl = createGapReport(previewArgs);
} catch (err) {
- if (!json) console.error(`Warning: Could not file gap report: ${err.message}`);
+ if (!json)
+ console.error(`Warning: Could not file gap report: ${err.message}`);
}
}
+ }
- if (json) return jsonOut('swizzle.copy', {component: dirName, outputDir: relOutput, filesCopied: copied, files: copiedFiles.map(f => f), gapReport: gapReportUrl});
+ if (options.gap) {
+ if (json)
+ return jsonOut('swizzle.copy', {
+ component: dirName,
+ outputDir: relOutput,
+ filesCopied: copied,
+ files: copiedFiles.map(f => f),
+ gapReport: gapReportUrl,
+ gapReportDryRun: gapDryRunPreview,
+ gapReportSuppressed: reportingSuppressed || !gapConfig.enabled,
+ });
console.log(`\n✓ Copied ${copied} files to ${relOutput}/\n`);
console.log('Relative imports have been rewritten to use @xds/core.');
console.log('You can now customize the component source freely.\n');
- if (gapReportUrl) console.log(`✓ Gap report filed: ${gapReportUrl}\n`);
- else if (!gapConfig.enabled) console.log('Gap reporting is disabled via configuration.');
- else if (!gapConfig.command && !checkGhCli()) console.log('Skipping gap report: gh CLI not available.');
+ if (gapReportUrl) {
+ console.log(`✓ Gap report filed: ${gapReportUrl}\n`);
+ } else if (gapDryRunPreview) {
+ console.log(formatPreview(buildGapReportPreview({
+ component: dirName,
+ category: options.gapCategory || 'other',
+ intention: options.gap,
+ source: 'llm-auto',
+ })));
+ console.log(
+ '\n[dry-run] No gap report was filed. Re-run with --commit to file.',
+ );
+ } else if (reportingSuppressed) {
+ console.log('Gap reporting suppressed by --no-report.');
+ } else if (!gapConfig.enabled) {
+ console.log('Gap reporting is disabled via configuration.');
+ } else if (!gapConfig.command && !checkGhCli()) {
+ console.log('Skipping gap report: gh CLI not available.');
+ }
return;
}
@@ -166,7 +234,7 @@ export function registerSwizzle(program) {
console.log('Relative imports have been rewritten to use @xds/core.');
console.log('You can now customize the component source freely.\n');
- if (!options.report || !gapConfig.enabled) {
+ if (reportingSuppressed || !gapConfig.enabled) {
return;
}
@@ -210,17 +278,43 @@ export function registerSwizzle(program) {
}),
);
+ const previewArgs = {
+ component: dirName,
+ category,
+ intention: intention.trim(),
+ detail: detail?.trim() || undefined,
+ source: 'interactive',
+ };
+
+ const preview = buildGapReportPreview(previewArgs);
+
+ p.note(
+ `${preview.mode === 'github' ? `Repo: ${preview.repo}` : `Custom command: ${preview.command}`}\n\n` +
+ `Title:\n ${preview.title}\n\n` +
+ `Body:\n${preview.body
+ .split('\n')
+ .map(l => ` ${l}`)
+ .join('\n')}`,
+ 'Preview — this is exactly what will be filed',
+ );
+
+ const confirmFile = isCancel(
+ await p.confirm({
+ message: 'File this gap report now?',
+ initialValue: false,
+ }),
+ );
+
+ if (!confirmFile) {
+ console.log('Cancelled — nothing was filed.');
+ return;
+ }
+
const s = p.spinner();
s.start('Filing gap report');
try {
- const url = createGapReport({
- component: dirName,
- category,
- intention: intention.trim(),
- detail: detail?.trim() || undefined,
- source: 'interactive',
- });
+ const url = createGapReport(previewArgs);
s.stop('Gap report filed');
console.log(`✓ ${url}\n`);
} catch (err) {
diff --git a/packages/cli/src/utils/github.mjs b/packages/cli/src/utils/github.mjs
index e068f75ac3..0c810eee07 100644
--- a/packages/cli/src/utils/github.mjs
+++ b/packages/cli/src/utils/github.mjs
@@ -159,17 +159,20 @@ function runCustomCommand(command, report) {
}
/**
- * Create a gap report — either via GitHub issue or custom command.
+ * Build the report payload + rendered title/body for a gap report.
+ * Pure function — no side effects, never calls `gh` or external scripts.
*
- * @param {object} opts
- * @param {string} opts.component Component name (e.g. "Button")
- * @param {string} opts.category One of GAP_CATEGORIES values
- * @param {string} opts.intention What the user was trying to achieve
- * @param {string} [opts.detail] Additional context
- * @param {string} [opts.source] Who filed it: "interactive", "llm-auto", "cli"
- * @returns {string|null} URL of the created issue (or custom command output), null if disabled
+ * @returns {{
+ * enabled: boolean,
+ * mode: 'disabled' | 'custom' | 'github',
+ * command?: string,
+ * report: object,
+ * title: string,
+ * body: string,
+ * repo: string,
+ * }}
*/
-export function createGapReport({
+export function buildGapReportPreview({
component,
category,
intention,
@@ -177,11 +180,6 @@ export function createGapReport({
source = 'cli',
}) {
const config = loadGapReportConfig();
-
- if (!config.enabled) {
- return null;
- }
-
const categoryLabel =
GAP_CATEGORIES.find(c => c.value === category)?.label ?? category;
@@ -195,16 +193,7 @@ export function createGapReport({
timestamp: new Date().toISOString(),
};
- // Custom command mode — pipe JSON to the script
- if (config.command) {
- return runCustomCommand(config.command, report);
- }
-
- // Default mode — create GitHub issue
- ensureGapReportLabel();
-
const title = `[gap] ${component}: ${intention.slice(0, 70)}`;
-
const body = [
'| Field | Value |',
'|-------|-------|',
@@ -216,22 +205,65 @@ export function createGapReport({
'## User Intention',
'',
intention,
- ...(detail
- ? ['', '## Additional Context', '', detail]
- : []),
+ ...(detail ? ['', '## Additional Context', '', detail] : []),
].join('\n');
+ let mode = 'github';
+ if (!config.enabled) mode = 'disabled';
+ else if (config.command) mode = 'custom';
+
+ return {
+ enabled: config.enabled,
+ mode,
+ command: config.command,
+ report,
+ title,
+ body,
+ repo: DEFAULT_REPO,
+ };
+}
+
+/**
+ * Create a gap report — either via GitHub issue or custom command.
+ *
+ * SAFETY: This actually invokes `gh issue create` (or runs the custom command).
+ * Callers MUST gate this behind explicit user confirmation or a `--commit`-style
+ * flag in non-interactive contexts. Use `buildGapReportPreview` for dry-run.
+ *
+ * @param {object} opts
+ * @param {string} opts.component Component name (e.g. "Button")
+ * @param {string} opts.category One of GAP_CATEGORIES values
+ * @param {string} opts.intention What the user was trying to achieve
+ * @param {string} [opts.detail] Additional context
+ * @param {string} [opts.source] Who filed it: "interactive", "llm-auto", "cli"
+ * @returns {string|null} URL of the created issue (or custom command output), null if disabled
+ */
+export function createGapReport(opts) {
+ const preview = buildGapReportPreview(opts);
+
+ if (!preview.enabled) {
+ return null;
+ }
+
+ // Custom command mode — pipe JSON to the script
+ if (preview.mode === 'custom') {
+ return runCustomCommand(preview.command, preview.report);
+ }
+
+ // Default mode — create GitHub issue
+ ensureGapReportLabel();
+
const result = execFileSync(
'gh',
[
'issue',
'create',
'--repo',
- DEFAULT_REPO,
+ preview.repo,
'--title',
- title,
+ preview.title,
'--body',
- body,
+ preview.body,
'--label',
'gap-report',
],