Skip to content

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

TypeScript

Add gap reporting to swizzle flow and standalone command (#122)

Cindy Zhangda877536b25f
diff --git a/.claude/commands/curate-gaps.md b/.claude/commands/curate-gaps.md
new file mode 100644
index 0000000000..46eab0266c
--- /dev/null
+++ b/.claude/commands/curate-gaps.md
@@ -0,0 +1,113 @@
+# Curate Gap Reports
+
+Analyze open gap reports and produce a curated gap analysis issue.
+
+## Arguments
+
+$ARGUMENTS
+
+Use `--close` to close raw gap reports after curating (links them to the analysis issue).
+
+## Instructions
+
+### 1. Fetch all open gap reports
+
+```bash
+gh issue list --repo facebookexperimental/xds --label gap-report --state open --json number,title,body,createdAt --limit 200
+```
+
+If there are zero open gap reports, tell the user and stop.
+
+### 2. Parse and analyze
+
+For each issue, extract:
+
+- **Component** (from the table in the body)
+- **Category** (from the table)
+- **Source** (interactive, llm-auto, cli)
+- **User Intention** (the section after "## User Intention")
+
+Focus on **user intention** — what builders were trying to achieve — not specific prop/API requests.
+
+### 3. Group by themes
+
+Identify high-level themes across the reports:
+
+- Common intentions (e.g. "need dense/compact variants", "missing responsive behavior")
+- Component hotspots (which components appear most often)
+- Category distribution
+
+### 4. Create curated analysis issue
+
+Create the label first, then the issue:
+
+```bash
+gh label create gap-analysis --repo facebookexperimental/xds --color 0E8A16 --description "Curated gap analysis summary" --force
+```
+
+Then create the issue. Use this format for the body:
+
+```
+## Gap Analysis: <Month> <Year>
+
+**<N> gap reports analyzed** | Period: <earliest date> — <latest date>
+
+### Top User Intentions
+
+1. **<Theme>** (<count> reports)
+ - <Summarized intention>
+ - Evidence: #<issue>, #<issue>
+
+2. **<Theme>** (<count> reports)
+ - <Summarized intention>
+ - Evidence: #<issue>, #<issue>
+
+(continue for all themes)
+
+### Component Hotspots
+
+| Component | Reports | Top Category |
+|-----------|---------|-------------|
+| <Name> | <N> | <category> |
+
+### Category Distribution
+
+| Category | Count |
+|----------|-------|
+| <cat> | <N> |
+
+### Recommendations
+
+1. <Actionable recommendation based on evidence>
+2. <Actionable recommendation based on evidence>
+
+<details>
+<summary>Raw Reports (<N> total)</summary>
+
+| # | Component | Category | Intention |
+|---|-----------|----------|-----------|
+| #<num> | <comp> | <cat> | <brief intention> |
+
+</details>
+```
+
+Create the issue:
+
+```bash
+gh issue create --repo facebookexperimental/xds --title "Gap Analysis: <Month> <Year> — <primary theme>" --label gap-analysis --body "<body>"
+```
+
+### 5. Optionally close raw reports
+
+Only if the user passed `--close` as an argument:
+
+For each raw gap report, add a comment and close it:
+
+```bash
+gh issue comment <number> --repo facebookexperimental/xds --body "Curated into gap analysis #<analysis-issue-number>"
+gh issue close <number> --repo facebookexperimental/xds
+```
+
+### 6. Report results
+
+Print the URL of the created gap analysis issue and a summary of what was processed.
diff --git a/packages/cli/src/commands/agent-docs.mjs b/packages/cli/src/commands/agent-docs.mjs
index bb2ae32b28..59117a1f36 100644
--- a/packages/cli/src/commands/agent-docs.mjs
+++ b/packages/cli/src/commands/agent-docs.mjs
@@ -29,6 +29,9 @@ export function generateCompressedIndex(version) {
|npx xds swizzle <Name> Copy component source for customization
|npx xds theme <preset> Apply theme (default, neutral)
|npx xds template <name> [path] Scaffold page (blank, table, login)
+|npx xds swizzle <Name> --gap "<reason>" Swizzle + file gap report
+|npx xds gap-report --component <Name> --category <cat> --reason "<why>" File gap without swizzle
+|RULE: When swizzling to unblock yourself, ALWAYS use --gap to explain what capability was missing.
${XDS_MARKER_END}`;
}
diff --git a/packages/cli/src/commands/gap-report.mjs b/packages/cli/src/commands/gap-report.mjs
new file mode 100644
index 0000000000..7db7e1157a
--- /dev/null
+++ b/packages/cli/src/commands/gap-report.mjs
@@ -0,0 +1,286 @@
+/**
+ * @file gap-report command — File a gap report for missing XDS capabilities
+ *
+ * Interactive and non-interactive modes for reporting gaps in the design system.
+ * Creates GitHub issues with the `gap-report` label.
+ *
+ * Includes `gap-report setup` subcommand for configuring gap report delivery.
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as p from '@clack/prompts';
+import {
+ checkGhCli,
+ createGapReport,
+ loadGapReportConfig,
+ GAP_CATEGORIES,
+} from '../utils/github.mjs';
+
+function isCancel(value) {
+ if (p.isCancel(value)) {
+ p.cancel('Gap report cancelled.');
+ process.exit(0);
+ }
+ return value;
+}
+
+/**
+ * Update or insert the gapReport key in xds.config.mjs.
+ * Preserves existing keys (e.g. theme).
+ */
+function writeGapReportConfig(targetDir, gapReportValue) {
+ const configPath = path.join(targetDir, 'xds.config.mjs');
+
+ if (fs.existsSync(configPath)) {
+ let content = fs.readFileSync(configPath, 'utf-8');
+
+ // Replace existing gapReport key (handles both `false` and `{ command: '...' }`)
+ if (/gapReport\s*:/.test(content)) {
+ content = content.replace(
+ /gapReport\s*:\s*(?:\{[^}]*\}|false|true)\s*,?/s,
+ `gapReport: ${gapReportValue},`,
+ );
+ } else {
+ // Insert before the closing `};`
+ content = content.replace(
+ /(\n};?\s*)$/,
+ `\n gapReport: ${gapReportValue},$1`,
+ );
+ }
+
+ fs.writeFileSync(configPath, content);
+ } else {
+ const content = `/**
+ * XDS Configuration
+ * Generated by \`xds gap-report setup\`
+ */
+export default {
+ gapReport: ${gapReportValue},
+};
+`;
+ fs.writeFileSync(configPath, content);
+ }
+
+ return configPath;
+}
+
+export function registerGapReport(program) {
+ const gapCmd = program
+ .command('gap-report')
+ .description('Report a gap in the XDS design system');
+
+ // --- setup subcommand ---
+ gapCmd
+ .command('setup')
+ .description('Configure where gap reports are sent')
+ .action(async () => {
+ p.intro('Gap report setup');
+
+ const config = loadGapReportConfig();
+ const currentMode = !config.enabled
+ ? 'disabled'
+ : config.command
+ ? 'custom'
+ : 'github';
+
+ const mode = isCancel(
+ await p.select({
+ message: `How should gap reports be delivered? (current: ${currentMode})`,
+ options: [
+ {
+ value: 'github',
+ label: 'GitHub Issues',
+ hint: 'Creates issues on facebookexperimental/xds (requires gh CLI)',
+ },
+ {
+ value: 'custom',
+ label: 'Custom command',
+ hint: 'Run a script that receives the report as JSON on stdin',
+ },
+ {
+ value: 'disabled',
+ label: 'Disabled',
+ hint: 'Turn off gap reporting entirely',
+ },
+ ],
+ }),
+ );
+
+ let configValue;
+ const targetDir = process.cwd();
+
+ if (mode === 'disabled') {
+ configValue = 'false';
+ writeGapReportConfig(targetDir, configValue);
+ p.log.success('Gap reporting disabled.');
+ } else if (mode === 'custom') {
+ const command = isCancel(
+ await p.text({
+ message: 'Path to script:',
+ placeholder: './scripts/report-gap.sh',
+ validate: val => {
+ if (!val.trim()) return 'Script path is required';
+ },
+ }),
+ );
+
+ configValue = `{ command: '${command.trim()}' }`;
+ writeGapReportConfig(targetDir, configValue);
+
+ p.log.success(`Gap reports will be sent to: ${command.trim()}`);
+ p.note(
+ 'Your script receives JSON on stdin with these fields:\n' +
+ ' component, category, categoryLabel, intention,\n' +
+ ' detail, source, timestamp\n\n' +
+ 'Anything printed to stdout is shown to the user.',
+ 'Script contract',
+ );
+ } else {
+ // GitHub mode — remove gapReport key or set to default
+ const configPath = path.join(targetDir, 'xds.config.mjs');
+ if (fs.existsSync(configPath)) {
+ let content = fs.readFileSync(configPath, 'utf-8');
+ // Remove the gapReport line entirely to use default
+ content = content.replace(
+ /\s*gapReport\s*:\s*(?:\{[^}]*\}|false|true)\s*,?/s,
+ '',
+ );
+ fs.writeFileSync(configPath, content);
+ }
+
+ if (!checkGhCli()) {
+ p.log.warning(
+ 'gh CLI is not installed or not authenticated.\n' +
+ 'Install from https://cli.github.com and run `gh auth login`.',
+ );
+ } else {
+ p.log.success(
+ 'Gap reports will create GitHub issues on facebookexperimental/xds.',
+ );
+ }
+ }
+
+ p.outro('Configuration saved to xds.config.mjs');
+ });
+
+ // --- main gap-report command ---
+ gapCmd
+ .option('--component <name>', 'Component name')
+ .option('--category <category>', 'Gap category')
+ .option('--reason <reason>', 'What capability was missing')
+ .action(async options => {
+ const config = loadGapReportConfig();
+ if (!config.enabled) {
+ console.log(
+ 'Gap reporting is disabled. Run `npx 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 `npx xds gap-report setup` to configure a custom command.',
+ );
+ process.exit(1);
+ }
+
+ const isNonInteractive =
+ options.component && options.category && options.reason;
+
+ if (isNonInteractive) {
+ // Non-interactive mode for LLM/script use
+ const validCategory = GAP_CATEGORIES.find(
+ c => c.value === options.category,
+ );
+ if (!validCategory) {
+ console.error(
+ `Error: Invalid category "${options.category}".\n` +
+ `Valid categories: ${GAP_CATEGORIES.map(c => c.value).join(', ')}`,
+ );
+ process.exit(1);
+ }
+
+ try {
+ const url = createGapReport({
+ component: options.component,
+ category: options.category,
+ intention: options.reason,
+ source: 'cli',
+ });
+ if (url) {
+ console.log(`\n✓ Gap report filed: ${url}\n`);
+ } else {
+ console.log('\nGap reporting is disabled via configuration.\n');
+ }
+ } catch (err) {
+ console.error(`Error filing gap report: ${err.message}`);
+ process.exit(1);
+ }
+ return;
+ }
+
+ // Interactive mode
+ p.intro('Report an XDS gap');
+
+ const component = isCancel(
+ await p.text({
+ message: 'Which component is this about?',
+ placeholder: 'e.g. Button, Table, or "general"',
+ validate: val => {
+ if (!val.trim()) return 'Component name is required';
+ },
+ }),
+ );
+
+ const category = isCancel(
+ await p.select({
+ message: 'What kind of gap is this?',
+ options: GAP_CATEGORIES,
+ }),
+ );
+
+ const intention = isCancel(
+ await p.text({
+ message: 'What were you trying to achieve?',
+ placeholder:
+ 'e.g. "Need a compact variant for use in dense data tables"',
+ validate: val => {
+ if (!val.trim()) return 'Please describe what you were trying to do';
+ },
+ }),
+ );
+
+ const detail = isCancel(
+ await p.text({
+ message: 'Any additional context? (optional)',
+ placeholder: 'Press Enter to skip',
+ }),
+ );
+
+ 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',
+ });
+ s.stop(url ? 'Gap report filed' : 'Gap reporting is disabled');
+ if (url) {
+ p.log.success(url);
+ }
+ } catch (err) {
+ s.stop('Failed to file gap report');
+ p.log.error(err.message);
+ process.exit(1);
+ }
+
+ p.outro('Thanks for the feedback!');
+ });
+}
diff --git a/packages/cli/src/commands/swizzle.mjs b/packages/cli/src/commands/swizzle.mjs
index ef61d94f05..64c40e01ad 100644
--- a/packages/cli/src/commands/swizzle.mjs
+++ b/packages/cli/src/commands/swizzle.mjs
@@ -4,18 +4,28 @@
* Resolves component source from packages/core/src/{Component}/,
* copies non-test files to the output directory, and rewrites
* relative imports to use '@xds/core' package paths.
+ *
+ * After swizzling, optionally prompts the user to file a gap report
+ * explaining why they needed to customize the component.
*/
import * as fs from 'node:fs';
import * as path from 'node:path';
+import * as p from '@clack/prompts';
import {findCoreDir, listComponents} from '../utils/paths.mjs';
+import {
+ checkGhCli,
+ createGapReport,
+ loadGapReportConfig,
+ GAP_CATEGORIES,
+} from '../utils/github.mjs';
/**
* Rewrite relative imports that point outside the component directory
* to use @xds/core package paths.
*
- * e.g. '../theme/tokens.stylex' → '@xds/core/theme'
- * '../utils/mergeProps' → '@xds/core/utils'
+ * e.g. '../theme/tokens.stylex' -> '@xds/core/theme'
+ * '../utils/mergeProps' -> '@xds/core/utils'
*/
export function rewriteImports(content) {
// Match import/export from statements with relative paths going up
@@ -23,8 +33,8 @@ export function rewriteImports(content) {
/(from\s+['"])(\.\.\/.+?)(['"])/g,
(match, prefix, importPath, suffix) => {
// Extract the top-level directory from the relative path
- // e.g. '../theme/tokens.stylex' → 'theme'
- // e.g. '../utils/mergeProps' → 'utils'
+ // e.g. '../theme/tokens.stylex' -> 'theme'
+ // e.g. '../utils/mergeProps' -> 'utils'
const parts = importPath.replace(/^\.\.\//, '').split('/');
const topDir = parts[0];
@@ -34,13 +44,24 @@ export function rewriteImports(content) {
);
}
+function isCancel(value) {
+ if (p.isCancel(value)) {
+ p.cancel('Cancelled.');
+ process.exit(0);
+ }
+ return value;
+}
+
export function registerSwizzle(program) {
program
.command('swizzle [component]')
.description('Copy component source for customization')
.option('--output <dir>', 'Output directory', './components/xds')
.option('--list', 'List available components')
- .action((component, options) => {
+ .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')
+ .action(async (component, options) => {
const coreDir = findCoreDir(process.cwd());
if (!coreDir) {
@@ -104,5 +125,102 @@ export function registerSwizzle(program) {
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');
+
+ // --- Gap reporting ---
+
+ const gapConfig = loadGapReportConfig();
+
+ // Programmatic gap mode (for LLMs using --gap flag)
+ if (options.gap) {
+ if (!gapConfig.enabled) {
+ console.log('Gap reporting is disabled via configuration.');
+ return;
+ }
+ if (!gapConfig.command && !checkGhCli()) {
+ console.log(
+ 'Skipping gap report: gh CLI not available. Install from https://cli.github.com',
+ );
+ return;
+ }
+
+ const category = options.gapCategory || 'other';
+ try {
+ const url = createGapReport({
+ component: dirName,
+ category,
+ intention: options.gap,
+ source: 'llm-auto',
+ });
+ if (url) {
+ console.log(`✓ Gap report filed: ${url}\n`);
+ }
+ } catch (err) {
+ console.error(`Warning: Could not file gap report: ${err.message}`);
+ }
+ return;
+ }
+
+ // Skip interactive prompt if --no-report or gap reporting disabled
+ if (!options.report || !gapConfig.enabled) {
+ return;
+ }
+
+ // Interactive gap report prompt
+ if (!gapConfig.command && !checkGhCli()) {
+ // Silently skip if gh isn't available and no custom command configured
+ return;
+ }
+
+ const shouldReport = isCancel(
+ await p.confirm({
+ message: 'Would you like to report why you swizzled this component?',
+ initialValue: false,
+ }),
+ );
+
+ if (!shouldReport) return;
+
+ const category = isCancel(
+ await p.select({
+ message: 'What kind of gap is this?',
+ options: GAP_CATEGORIES,
+ }),
+ );
+
+ const intention = isCancel(
+ await p.text({
+ message: 'What were you trying to achieve?',
+ placeholder:
+ 'e.g. "Need a compact variant for use in dense data tables"',
+ validate: val => {
+ if (!val.trim()) return 'Please describe what you were trying to do';
+ },
+ }),
+ );
+
+ const detail = isCancel(
+ await p.text({
+ message: 'Any additional context? (optional)',
+ placeholder: 'Press Enter to skip',
+ }),
+ );
+
+ 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',
+ });
+ s.stop('Gap report filed');
+ console.log(`✓ ${url}\n`);
+ } catch (err) {
+ s.stop('Failed to file gap report');
+ console.error(`Warning: Could not file gap report: ${err.message}`);
+ }
});
}
diff --git a/packages/cli/src/index.mjs b/packages/cli/src/index.mjs
index a46417185f..57242e5b4b 100644
--- a/packages/cli/src/index.mjs
+++ b/packages/cli/src/index.mjs
@@ -12,6 +12,7 @@ import {registerComponent} from './commands/component.mjs';
import {registerDocs} from './commands/docs.mjs';
import {registerTemplate} from './commands/template.mjs';
import {registerTheme} from './commands/theme.mjs';
+import {registerGapReport} from './commands/gap-report.mjs';
export const program = new Command();
@@ -28,6 +29,7 @@ registerSwizzle(program);
registerAgentDocs(program);
registerTemplate(program);
registerTheme(program);
+registerGapReport(program);
// Hidden command used by package.json postinstall scripts
program
diff --git a/packages/cli/src/utils/github.mjs b/packages/cli/src/utils/github.mjs
new file mode 100644
index 0000000000..3f5f984fc0
--- /dev/null
+++ b/packages/cli/src/utils/github.mjs
@@ -0,0 +1,240 @@
+/**
+ * @file GitHub utilities for XDS CLI
+ *
+ * Shared helpers for interacting with the GitHub CLI (`gh`).
+ * Used by gap-report and swizzle commands.
+ *
+ * Gap reporting can be configured via xds.config.mjs:
+ * gapReport: false — disable entirely
+ * gapReport: { command: './scripts/report-gap.sh' } — run custom script (receives JSON on stdin)
+ *
+ * Or via environment variable:
+ * XDS_GAP_REPORT=off — disable entirely
+ * XDS_GAP_REPORT=./scripts/report-gap.sh — run custom script
+ */
+
+import {execFileSync} from 'node:child_process';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+
+/** Default target repository for gap report issues. */
+const DEFAULT_REPO = 'facebookexperimental/xds';
+
+/** Gap report category options. */
+export const GAP_CATEGORIES = [
+ {value: 'missing_component', label: 'Missing component'},
+ {value: 'missing_variant', label: 'Missing variant or prop'},
+ {value: 'layout_gap', label: 'Layout gap'},
+ {value: 'styling_gap', label: 'Styling gap'},
+ {value: 'a11y_gap', label: 'Accessibility gap'},
+ {value: 'api_friction', label: 'API friction'},
+ {value: 'docs_gap', label: 'Documentation gap'},
+ {value: 'other', label: 'Other'},
+];
+
+/**
+ * Load gap report configuration.
+ *
+ * Priority: env var > xds.config.mjs > default (GitHub issue)
+ *
+ * Returns { enabled: boolean, command?: string }
+ * - enabled: false → gap reporting disabled
+ * - command: string → run this script instead of creating a GitHub issue
+ * - neither → default behavior (GitHub issue to facebookexperimental/xds)
+ */
+export function loadGapReportConfig() {
+ // 1. Check environment variable
+ const envVar = process.env.XDS_GAP_REPORT;
+ if (envVar) {
+ if (envVar === 'off' || envVar === 'false' || envVar === '0') {
+ return {enabled: false};
+ }
+ // Treat as custom command
+ return {enabled: true, command: envVar};
+ }
+
+ // 2. Check xds.config.mjs
+ const configPath = path.join(process.cwd(), 'xds.config.mjs');
+ if (fs.existsSync(configPath)) {
+ try {
+ const content = fs.readFileSync(configPath, 'utf-8');
+ const match = content.match(/gapReport\s*:\s*(.+?)[\s,}]/s);
+ if (match) {
+ const value = match[1].trim();
+ if (value === 'false') {
+ return {enabled: false};
+ }
+ // Look for command property in object literal
+ const cmdMatch = content.match(
+ /gapReport\s*:\s*\{[^}]*command\s*:\s*['"](.+?)['"]/s,
+ );
+ if (cmdMatch) {
+ return {enabled: true, command: cmdMatch[1]};
+ }
+ }
+ } catch {
+ // Config parse error — fall through to defaults
+ }
+ }
+
+ // 3. Default
+ return {enabled: true};
+}
+
+/**
+ * Check if `gh` CLI is installed and authenticated.
+ * Returns true if ready, false otherwise.
+ */
+export function checkGhCli() {
+ try {
+ execFileSync('gh', ['auth', 'status'], {stdio: 'ignore'});
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Idempotently create the `gap-report` and `gap-analysis` labels.
+ * Uses `--force` to avoid errors if labels already exist.
+ */
+function ensureGapReportLabel() {
+ try {
+ execFileSync(
+ 'gh',
+ [
+ 'label',
+ 'create',
+ 'gap-report',
+ '--repo',
+ DEFAULT_REPO,
+ '--color',
+ 'D4C5F9',
+ '--description',
+ 'Auto-filed gap report from swizzle/gap-report CLI',
+ '--force',
+ ],
+ {stdio: 'ignore'},
+ );
+ execFileSync(
+ 'gh',
+ [
+ 'label',
+ 'create',
+ 'gap-analysis',
+ '--repo',
+ DEFAULT_REPO,
+ '--color',
+ '0E8A16',
+ '--description',
+ 'Curated gap analysis summary',
+ '--force',
+ ],
+ {stdio: 'ignore'},
+ );
+ } catch {
+ // Best-effort — labels may already exist or user may lack permissions
+ }
+}
+
+/**
+ * Run a custom gap report command, piping report data as JSON to stdin.
+ *
+ * @param {string} command Script path to execute
+ * @param {object} report Report data (component, category, intention, detail, source)
+ * @returns {string} stdout from the command
+ */
+function runCustomCommand(command, report) {
+ const resolved = path.resolve(process.cwd(), command);
+ const json = JSON.stringify(report, null, 2);
+
+ const result = execFileSync(resolved, [], {
+ input: json,
+ encoding: 'utf-8',
+ });
+
+ return result.trim();
+}
+
+/**
+ * Create a gap report — either via GitHub issue or custom command.
+ *
+ * @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({
+ component,
+ category,
+ intention,
+ detail,
+ source = 'cli',
+}) {
+ const config = loadGapReportConfig();
+
+ if (!config.enabled) {
+ return null;
+ }
+
+ const categoryLabel =
+ GAP_CATEGORIES.find(c => c.value === category)?.label ?? category;
+
+ const report = {
+ component,
+ category,
+ categoryLabel,
+ intention,
+ detail: detail || null,
+ source,
+ 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 |',
+ '|-------|-------|',
+ `| **Component** | ${component} |`,
+ `| **Category** | ${categoryLabel} |`,
+ `| **Source** | ${source} |`,
+ `| **Timestamp** | ${report.timestamp} |`,
+ '',
+ '## User Intention',
+ '',
+ intention,
+ ...(detail
+ ? ['', '## Additional Context', '', detail]
+ : []),
+ ].join('\n');
+
+ const result = execFileSync(
+ 'gh',
+ [
+ 'issue',
+ 'create',
+ '--repo',
+ DEFAULT_REPO,
+ '--title',
+ title,
+ '--body',
+ body,
+ '--label',
+ 'gap-report',
+ ],
+ {encoding: 'utf-8'},
+ );
+
+ return result.trim();
+}