An open source design system that's fully customizable and agent ready
TypeScript
feat(cli): fan out gap reports to project and integration handlers (#6200)
Joeydccba2f0e268
diff --git a/.changeset/calm-gap-routes.md b/.changeset/calm-gap-routes.mdnew file mode 100644index 0000000000..74c06d0a40--- /dev/null+++ b/.changeset/calm-gap-routes.md@@ -0,0 +1,18 @@+---+'@astryxdesign/cli': patch+---++[feat] Replace executable gap-report writers with composable handlers.++Gap reports now fan out to every configured handler — project config first,+then each loaded integration in config order — instead of selecting one+writer. Each handler gets its own report copy and an abort signal under a 30 s+budget. A failed handler cannot stop later handlers, and the aggregate receipt+shows every outcome.++Public types: `GapReportHandler` replaces `GapReportWriter`; the handler+receives a normalized `GapReport` event and returns a strict+`GapReportHandlerReceipt`. Project config gains a `gapReport` field; the+integration named export uses the same type.++@josephfarinadiff --git a/.github/scripts/api-cli-parity-test.mjs b/.github/scripts/api-cli-parity-test.mjsindex 9e1aa2d1ee..b83f5d47c2 100644--- a/.github/scripts/api-cli-parity-test.mjs+++ b/.github/scripts/api-cli-parity-test.mjs@@ -291,6 +291,11 @@ add('swizzle --list', ['swizzle', '--list'],add('swizzle (not found)', ['swizzle', 'NotARealComponent99'],() => apiCall(api.swizzle, 'NotARealComponent99', {cwd: ROOT}));+// Gap report categories are read-only and deterministic; filing paths are+// exercised with isolated package handlers in the focused suite.+add('gap-report --list-categories', ['gap-report', '--list-categories'],+ () => apiCall(api.gapReport, undefined, {listCategories: true, cwd: ROOT}));+// Upgrade — list + the two argument-validation errors are read-only: they// return/throw before any codemod or agent-docs side effect, so the api matches// the CLI envelope exactly. The full run/status pipeline is covered by thediff --git a/.github/scripts/cli-api-types-verify.mjs b/.github/scripts/cli-api-types-verify.mjsindex 2f95741c69..2a5a8e4790 100644--- a/.github/scripts/cli-api-types-verify.mjs+++ b/.github/scripts/cli-api-types-verify.mjs@@ -97,7 +97,7 @@ fs.symlinkSync(CORE_DIR, path.join(nm, 'core'), 'dir');const scenario = `import {component, docs, blog, discover, template, hook, search, build, swizzle,- upgrade, init, doctor, layoutExpand, layoutCheck, layoutGrammar,+ gapReport, upgrade, init, doctor, layoutExpand, layoutCheck, layoutGrammar,themeBuild, themeAdd, themeList, listThemes,integrationAdd, integrationAddComponent, integrationAddDoc,integrationAddTemplate, integrationAddCodemod, integrationAddAgentDoc,@@ -105,8 +105,9 @@ import {validateIntegration, summarizeIssues, logger, AstryxError,} from '@astryxdesign/cli/api';import type {- ComponentOptions, SearchOptions, UpgradeOptions,- ComponentDetailResponse, SearchResponse, UpgradeRunResponse, Logger,+ ComponentOptions, SearchOptions, UpgradeOptions, GapReportOptions,+ ComponentDetailResponse, SearchResponse, UpgradeRunResponse,+ GapReportReceiptResponse, GapReportCategoriesResponse, Logger,IntegrationAddComponentOptions, IntegrationAddDocOptions,IntegrationAddTemplateOptions, IntegrationAddCodemodOptions,IntegrationAddAgentDocOptions, IntegrationAddThemeOptions,@@ -119,9 +120,10 @@ async function main() {if (r.type === 'component.detail') { const n: string = r.data.name; void n; }const s: SearchOptions = { limit: 5, type: 'component' };const l: Logger = logger; l.setSilent(false); l.log('x');- void ({} as ComponentOptions); void ({} as UpgradeOptions);+ void ({} as ComponentOptions); void ({} as UpgradeOptions); void ({} as GapReportOptions);void ({} as ComponentDetailResponse); void ({} as SearchResponse); void ({} as UpgradeRunResponse);- void [docs, blog, discover, template, hook, search, build, swizzle, upgrade, init,+ void ({} as GapReportReceiptResponse); void ({} as GapReportCategoriesResponse);+ void [docs, blog, discover, template, hook, search, build, swizzle, gapReport, upgrade, init,doctor, layoutExpand, layoutCheck, layoutGrammar, themeBuild, themeAdd, themeList,listThemes, validateIntegration, summarizeIssues, AstryxError, s];}@@ -158,7 +160,9 @@ import {parseDoc, parseComponent, parseHook, parseFunction, parseReference,parseTemplate, parseSchema, parseCommand, parseEnum,} from '@astryxdesign/cli/authoring';-import type {SchemaDoc, CommandDoc, EnumDoc, FunctionDoc} from '@astryxdesign/cli/authoring';+import type {+ SchemaDoc, CommandDoc, EnumDoc, FunctionDoc, GapReportHandler,+} from '@astryxdesign/cli/authoring';function authoringSurface(raw: unknown) {const doc = parseDoc(raw);@@ -170,7 +174,14 @@ function authoringSurface(raw: unknown) {const command: CommandDoc = parseCommand(raw);const enumDoc: EnumDoc = parseEnum(raw);const fn: FunctionDoc = parseFunction(raw);- void [schema, command, enumDoc, fn];+ const gapHandler: GapReportHandler = {+ audience: 'public',+ async handle(_report, {signal}) {+ void signal;+ return {status: 'skipped'};+ },+ };+ void [schema, command, enumDoc, fn, gapHandler];void [parseComponent, parseHook, parseReference, parseTemplate];}void authoringSurface;diff --git a/.github/scripts/cli-json-smoke-test.mjs b/.github/scripts/cli-json-smoke-test.mjsindex d454b30ba6..904a6b2aec 100644--- a/.github/scripts/cli-json-smoke-test.mjs+++ b/.github/scripts/cli-json-smoke-test.mjs@@ -234,6 +234,12 @@ console.log('\nswizzle --json');checkJson('swizzle --list', ['swizzle', '--list'], {expectType: 'swizzle.list'});checkJson('swizzle (not found)', ['swizzle', 'NonexistentComponent99'], {expectError: true});+// ── Gap reports ─────────────────────────────────────────────────────+console.log('\ngap-report --json');+checkJson('gap-report --list-categories', ['gap-report', '--list-categories'], {+ expectType: 'gap-report.categories',+});+// ── Build ────────────────────────────────────────────────────────────console.log('\nbuild --json');checkJson('build (playbook)', ['build'], {expectType: 'build.help'});diff --git a/docs/specs/AST-031/spec.md b/docs/specs/AST-031/spec.mdnew file mode 100644index 0000000000..fc6adbd8e9--- /dev/null+++ b/docs/specs/AST-031/spec.md@@ -0,0 +1,292 @@+---+schema_version: 1+template_version: 1+kind: system-spec+id: spec:AST-031+authority: draft+archive_reason: null+superseded_by: null+approved_by: null+approved_at: null+phase: proposed+owners: [joeyfarina, cixzhang]+affects_architecture: [architecture:cli-surface]+affects_families: []+affects_contributing: []+affects_consumer_docs: [cli-integrations]+---++# Runtime integration feature composition system spec++## Intent++Define reusable composition rules for runtime integration features — CLI+capabilities that an integration can contribute alongside its default manifest.+Each feature is a named export from the integration module and an optional+matching field in `astryx.config`. Multiple handlers compose additively: every+configured eligible handler runs in isolation, failures are reported per handler, and+the feature defines one aggregate command outcome without letting one handler+silence the others.++This spec captures the general composition contract first, then records the+requirements specific to `gapReport`, the first feature built on it.++## Non-goals++- Replace the default-export manifest or its contribution model (components,+ templates, codemods, docs). Those are loaded by the `Project` seam and are+ outside this scope.+- Define transport protocols, network destinations, or persistence formats for+ any handler.+- Provide a plugin system with lifecycle hooks, dependency ordering, or+ inter-handler communication.++---++## Requirements++### General composition rules++The following rules apply to every runtime integration feature that follows+this spec. A feature is identified by a named export from+`astryx.integration.{ts,mjs,js}` and optionally a matching field in+`astryx.config`.++#### Named export + matching project config field++A feature is declared as a **named export** from the integration module.+The same feature may also appear as a field in the consumer's+`astryx.config` for project-level handlers. Older CLI versions that do not+recognize the named export ignore it and continue loading the default manifest.++#### Additive composition++Every handler in the effective set receives an ordered delivery outcome. The+project handler comes first, then each integration handler in the order the+integrations appear in `astryx.config`. An eligible handler runs; a public+handler without consent records `consent_required` without being called. No+handler overrides or displaces another.++#### Identity dedupe by handle function++When the same `handle` function reference appears more than once in the+effective set (e.g. a project config re-exports an integration's handler), it+runs exactly once, at the position of its first occurrence.++#### Per-handler structuredClone copy++Each handler receives its own `structuredClone` copy of the event. A handler+that mutates its input cannot affect any other handler.++#### Failure isolation + aggregate response++A handler that throws, times out, or misbehaves produces a failed delivery for+that handler. Later handlers still run. The command's aggregate response+collects a per-handler delivery record so the caller can see exactly which+handlers succeeded, which failed, and why.++#### Lifecycle / async++- **Timeout:** each handler has a 30-second wall-clock timeout and receives an+ `AbortSignal` that fires when that budget expires.+- **Async:** handlers may be async; the CLI awaits each one.+- **Execution order:** handlers run sequentially in effective-set order. A+ handler's failure does not skip subsequent handlers.++#### Per-handler consent metadata++Each handler declares an `audience` of `'internal'` or `'public'`. The CLI+enforces consent per handler: a `public`-audience handler is not invoked+unless the caller has explicitly confirmed the public write. An `internal`+handler requires no additional confirmation.++#### Inspectable consent (consent_required delivery)++When the caller has not confirmed consent and a handler requires it, the CLI+records a `consent_required` delivery for that handler without calling it. The+caller can inspect which handlers would need consent before re-running with+confirmation.++#### Fallback behavior++A built-in fallback (e.g. opening a GitHub issue via `issuesUrl`) activates+**only** when the effective handler set is empty after deduplication. The+presence of any configured handler — project or integration — suppresses the+fallback entirely.++#### issuesUrl is target metadata++`issuesUrl` on an integration manifest or project config describes the+destination for human-readable issue links. It is metadata about the target+package, not a handler implementation. Handlers use it as context; the CLI+uses it for fallback routing.++#### Mutation-sensitive tests++Tests for a feature built on this composition model MUST cover the fan-out+order, isolation, deduplication, timeout, consent gating, consent-required+inspection, fallback suppression, and aggregate response shape. Removing a+fail-closed guard MUST break a test.++---++### Gap-report-specific requirements++`gapReport` is the first feature built on the general composition rules above.++- **FR1 — Handler type.** A gap-report handler is a plain object conforming to+ `GapReportHandler`: `{ audience: 'internal' | 'public', handle: (event: GapReport, context: { signal: AbortSignal }) => GapReportHandlerReceipt | Promise<GapReportHandlerReceipt> }`.+ `GapReportHandler` replaces `GapReportWriter`.++- **FR2 — Event shape.** The `GapReport` event carries `schemaVersion: 1`,+ plain camelCase field names, normalized values, and a `target` object with+ `{ package, version, issuesUrl }`. No snake_case, no abbreviations, no+ nested debug context.++- **FR3 — Receipt contract.** A handler MUST return a `GapReportHandlerReceipt`:+ `{ status: 'filed' | 'routed_only' | 'skipped', url?: string, message?: string }`.+ No other status values are accepted. `url` and `message` are optional and+ carry human-readable context.++- **FR4 — Handler isolation.** Each handler runs in isolation:+ - Each handler runs in its own worker. `stdout` is redirected to `stderr`, and+ `process.exit`, `process.exitCode`, and late promise continuations are+ contained in that worker.+ - A throw or timeout (30 s) produces a failed delivery for that handler. The+ CLI aborts the handler's signal, then terminates its worker before starting+ the next handler.+ - A failed handler does not affect the command's own exit code or other+ handlers.++- **FR5 — No inherited-handler opt-out.** There is no opt-out mechanism for+ gap-report handlers analogous to `inheritDebug`. Every internal handler in the+ effective set runs, and every public handler receives an outcome subject only+ to the explicit consent gate.+ The `inheritDebug` field in `package.json` is a compatibility exception specific+ to the `debug` feature (see Decision log DEC-2); it does not set a precedent+ for other features.++- **FR6 — Effective set.** The effective handler set is: project config's+ `gapReport` handler first (if present), then each integration's `gapReport`+ named export in `astryx.config` integration order. Deduplication is by+ `handle` function identity.++- **FR7 — Target selection.** The target package for the gap report is selected+ by: explicit `--package` flag → the unique component owner when only one+ package owns the component → Core as the default. Target selection is not+ based on handler count or handler source.++- **FR8 — Built-in GitHub fallback.** When the effective handler set is empty+ (zero handlers after deduplication), and the target has a GitHub `issuesUrl`,+ the CLI offers to file via `gh issue create`. This fallback is consent-gated+ (`public` audience). Any other `issuesUrl` scheme produces a `routed_only`+ receipt. The fallback is suppressed entirely when at least one handler exists.++- **FR9 — Project config field.** `astryx.config` gains a `gapReport` field+ accepting a `GapReportHandler`. This is the project-level handler and runs+ first in the effective set.++- **FR10 — Integration named export.** An integration declares its handler as+ `export const gapReport: GapReportHandler` from its integration module. The+ named export is deliberately not a default-manifest field, consistent with the+ `debug` feature's export convention.++- **FR11 — Per-handler consent.** Each handler's `audience` is evaluated+ independently. A fan-out with mixed audiences invokes `internal` handlers+ unconditionally and gates `public` handlers on caller consent. Ungated+ handlers still run even when a gated sibling is blocked.++- **FR12 — Aggregate response.** The command's response includes a `deliveries`+ array with one entry per effective handler or fallback. Each delivery records+ `handlerType`, `handler`, `audience`, `status`, `url`, and `message`. The+ response shape is the same in `--json` and human output modes.++#### Platform support++- Supported: Node >= 22.13, any OS the CLI supports.+- Unsupported: handlers that depend on network access, native binaries, or+ platform-specific APIs are the handler author's responsibility; the CLI+ provides isolation but not capability detection.++---++## Current-state impact++`debug` already composes one project function with every integration named export,+in project-first/config-order delivery, with identity dedupe and per-handler copies.+Its synchronous process-exit lifecycle and existing `inheritDebug` compatibility+switch remain unchanged.++PR #6200 initially selected one executable gap writer. This specification replaces+that model before release: `gapReport` becomes one project handler plus every loaded+integration handler, and each handler returns its own receipt. Existing consumers+without handlers keep the consent-gated `issuesUrl` fallback. No released config or+integration API requires migration because the single-writer shape has not shipped.++---++## Verification++| Contract | Verification | Representative states | Mutation or failure expectation |+| -------- | ------------------------------------------------------ | --------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |+| FR1–FR3 | gap-report handler type and receipt contract tests | valid handler; missing audience; wrong status value; non-object return | an invalid handler shape or receipt is accepted silently |+| FR4 | handler isolation tests | handler writes stdout; handler calls process.exit; handler throws; handler exceeds 30 s | stdout corruption reaches the JSON envelope, or exit/throw stops later handlers |+| FR5 | no-opt-out assertion test | project sets `inheritDebug: false` in package.json; gap-report handlers still run | an opt-out mechanism suppresses a gap-report handler |+| FR6 | effective-set ordering and deduplication tests | project + two integrations; duplicate handle ref; project only; integrations only | wrong order, duplicate execution, or missing handler |+| FR7 | target selection tests | explicit package; unique owner; ambiguous owner requiring `--package`; no component match | handler count influences target, ambiguity is guessed, or an unknown component fails to default to Core |+| FR8 | fallback activation and suppression tests | zero handlers + GitHub issuesUrl; zero handlers + non-GitHub issuesUrl; one handler present | fallback fires with a handler present, or non-GitHub issuesUrl claims it filed |+| FR9–FR10 | config field and named-export loading tests | project config with gapReport; integration with named export; both present; neither present | config field ignored, named export ignored, or old CLI breaks on named export |+| FR11 | mixed-audience consent tests | all internal; all public with consent; all public without consent; mixed with partial consent | a public handler runs without consent, or an internal handler is blocked by consent |+| FR12 | aggregate response shape tests | all succeed; one fails; one times out; consent_required entries; empty set (fallback) | missing delivery entry, wrong source attribution, or response shape differs between --json and human |+| General | mutation-sensitive composition tests (structuredClone) | handler mutates event fields; handler adds properties to event | mutation leaks to a subsequent handler |++---++## Decision log++### DEC-1 — Handlers compose additively; no single-writer selection++**Reference:** `spec:AST-031/DEC-1`+**Decider:** `joeyfarina`, `2026-09-10`++Every configured handler runs. The previous model selected one writer based on+target ownership, which meant an integration could not observe reports about+components it did not own. Additive composition lets every interested party+receive every report while isolating failures to individual deliveries.++Rejected: single-writer selection by target ownership; priority-based override+where a project handler silences integration handlers; "first match wins"+routing.++### DEC-2 — No general opt-out mechanism for runtime features++**Reference:** `spec:AST-031/DEC-2`+**Decider:** `joeyfarina`, `2026-09-10`++The `debug` feature's existing `inheritDebug` switch remains a compatibility+exception owned by that feature. It does not establish a general+`inherit<Feature>` convention. Gap reporting is an explicit command whose purpose+is to notify every configured handler, so loading an integration opts into its+handler. Any future opt-out requires a separate owner decision.++Rejected: automatically cloning `inheritDebug` into a general package.json+pattern; adding a gap-report opt-out that silently prevents a loaded integration+from receiving an explicit report.++### DEC-3 — Target selection uses component ownership, not handler count++**Reference:** `spec:AST-031/DEC-3`+**Decider:** `joeyfarina`, `2026-09-10`++The target package for a gap report is the package that owns the component. When+multiple packages claim the same component name, the CLI requires an explicit+`--package` instead of guessing. A name with no exact owner defaults to Core.+Handler count and handler order never change target attribution.++Rejected: selecting the target by handler count or integration order; silently+choosing one ambiguous owner; distributing target ownership to every package that+ships a handler.++## Open questions++None.diff --git a/packages/cli/README.md b/packages/cli/README.mdindex 149c633bc3..6f8dac5252 100644--- a/packages/cli/README.md+++ b/packages/cli/README.md@@ -66,6 +66,7 @@ Options:| `discover` | Discover external packages and components || `docs` | Print reference docs || `doctor` | Diagnose Astryx projects and integration packages |+| `gap-report` | Route a design-system gap to its owning package || `hook` | List hooks or print hook docs || `init` | Initialize the design system in your project || `integration` | Author and verify an Astryx integration package |@@ -414,6 +415,8 @@ Every response has a `type` discriminant. The full set is below (generated from| `build.kit` | The grouped composition kit: echoed query, hasResults/matchCount/directMatch fields (matchCount is the total matched, never a cap read back), the closest page templates, drop-in block patterns, idea-specific components/hooks, and the always-on frame + foundation component-name arrays. || `swizzle.list` | The names of swizzlable components discoverable from cwd's @astryxdesign/core. || `swizzle.copy` | An eject receipt: component name, owning package, output directory, files-copied count, the written file names, whether any file uses StyleX, and an optional maintainer note. |+| `gap-report.categories` | The fixed gap category values and human-readable labels. |+| `gap-report.file` | An aggregate receipt with overall status, the selected package and issues URL, ordered per-handler deliveries, and filedCount/routedOnlyCount totals. || `template.list` | Every discovered template (page + block); each entry carries id, name, description, kind, owning package, optional category and componentsUsed, and readiness flags. || `template.show` | The resolved template's raw source plus its description, kind, and the component names it composes. || `template.skeleton` | A layout skeleton (structural tags with spatial annotations) plus the template's description and the components it composes. |diff --git a/packages/cli/api/gap-report/gap-report-worker.mjs b/packages/cli/api/gap-report/gap-report-worker.mjsnew file mode 100644index 0000000000..2b63f3494e--- /dev/null+++ b/packages/cli/api/gap-report/gap-report-worker.mjs@@ -0,0 +1,73 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Isolated worker for one project or integration gap-report handler.+ *+ * A handler runs in its own JavaScript isolate so process.exit, process.exitCode,+ * late promise continuations, and stdout cannot affect the CLI process. The+ * parent sends an abort message at the timeout boundary, then terminates this+ * worker after a short grace period.+ */++import {parentPort, workerData} from 'node:worker_threads';+import {importUserModule} from '../../foundation/fs/module-loader.mjs';++if (parentPort == null) {+ throw new Error('Gap report handler worker requires a parent port.');+}+const port = /** @type {NonNullable<typeof parentPort>} */ (parentPort);++const controller = new AbortController();+port.once('message', message => {+ if (message?.type === 'abort') controller.abort();+});++/** @param {unknown} error @returns {string} */+function errorMessage(error) {+ return error instanceof Error ? error.message : String(error);+}++/** @param {unknown} message */+function send(message) {+ try {+ port.postMessage(message);+ } catch (error) {+ port.postMessage({kind: 'error', message: errorMessage(error)});+ }+}++async function run() {+ try {+ const mod = await importUserModule(workerData.modulePath);+ const handler =+ workerData.handlerSource === 'project'+ ? /** @type {any} */ (mod?.default)?.gapReport+ : mod?.gapReport;+ if (+ handler == null ||+ typeof handler !== 'object' ||+ typeof handler.handle !== 'function'+ ) {+ throw new Error(+ 'Gap report handler could not be reloaded in its worker.',+ );+ }++ const exitCodeBefore = process.exitCode;+ send({kind: 'ready'});+ const value = await handler.handle(workerData.report, {+ signal: controller.signal,+ });+ if (process.exitCode !== exitCodeBefore) {+ send({kind: 'exit-code'});+ } else {+ send({kind: 'result', value});+ }+ } catch (error) {+ send({kind: 'error', message: errorMessage(error)});+ } finally {+ port.close();+ }+}++void run();diff --git a/packages/cli/api/gap-report/gap-report.doc.mjs b/packages/cli/api/gap-report/gap-report.doc.mjsnew file mode 100644index 0000000000..7b2bf26ebd--- /dev/null+++ b/packages/cli/api/gap-report/gap-report.doc.mjs@@ -0,0 +1,127 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file FunctionDoc for `gapReport()` / `astryx gap-report`.+ * @position packages/cli/api/gap-report — function documentation+ */++/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */+export const doc = {+ type: 'function',+ kind: 'api',+ name: 'gapReport',+ displayName: 'gapReport()',+ summary: 'Route a design-system gap through the fan-out handler composition.',+ description:+ 'Creates a normalized gap report and fans it out to every effective handler: the project config handler first, then each loaded integration handler in config order, deduplicated by handle function identity. Each handler receives a structuredClone of the report and an AbortSignal, then runs in its own worker with a 30 s timeout and stdout redirected to stderr. A timed-out worker is terminated before the next handler starts, so process.exit, process.exitCode, and late continuations cannot affect the CLI process. A public handler requires confirmPublic per handler; internal handlers always run. When no handlers exist, a built-in GitHub/routed-only fallback runs. The aggregate response carries ordered deliveries with per-handler outcomes.',+ importPath: '@astryxdesign/cli/api',+ signature:+ 'gapReport(component?: string, options?: GapReportOptions): Promise<GapReportCategoriesResponse | GapReportReceiptResponse>',+ keywords: [+ 'gap',+ 'report',+ 'feedback',+ 'issue',+ 'integration',+ 'routing',+ 'handler',+ 'fan-out',+ ],+ params: [+ {+ name: 'component',+ type: 'string',+ description:+ 'Component or general design-system area. Required unless listCategories is true.',+ },+ {+ name: 'options.category',+ type: 'GapReportCategory',+ description: 'Fixed category from the reported category vocabulary.',+ },+ {+ name: 'options.reason',+ type: 'string',+ description: 'What capability was missing or difficult.',+ },+ {+ name: 'options.detail',+ type: 'string',+ description: 'Optional additional context (up to 8000 characters).',+ },+ {+ name: 'options.package',+ type: 'string',+ description:+ 'Explicit owning package when automatic routing is ambiguous.',+ },+ {+ name: 'options.confirmPublic',+ type: 'boolean',+ description:+ 'Explicitly consent to invoking public handlers or creating a GitHub issue.',+ default: 'false',+ },+ {+ name: 'options.listCategories',+ type: 'boolean',+ description: 'Return categories without resolving a route or writing.',+ default: 'false',+ },+ {+ name: 'options.cwd',+ type: 'string',+ description:+ 'Directory used to load project config and component ownership.',+ },+ ],+ returns: [+ {+ type: 'gap-report.categories',+ description: 'The fixed category values and labels.',+ },+ {+ type: 'gap-report.file',+ description:+ 'An aggregate receipt with per-handler deliveries, filedCount/routedOnlyCount totals, and overall status.',+ },+ ],+ throws: [+ {+ code: 'ERR_UNKNOWN_CATEGORY',+ when: 'category is not one of the fixed gap-report values',+ },+ {+ code: 'ERR_INVALID_ARGUMENT',+ when: 'a field value is invalid',+ },+ {+ code: 'ERR_AMBIGUOUS_COMPONENT',+ when: 'more than one package owns the named component',+ },+ {+ code: 'ERR_UNKNOWN_PACKAGE',+ when: 'the explicitly selected package is not loaded',+ },+ {+ code: 'ERR_NOT_FOUND',+ when: 'no handler and no issues URL available',+ },+ ],+ examples: [+ {+ label: 'List categories',+ code: 'const categories = await gapReport(undefined, {listCategories: true});',+ },+ {+ label: 'Route without public mutation',+ code: "const receipt = await gapReport('Button', {category: 'missing_variant', reason: 'Need a compact size'});",+ },+ {+ label: 'Confirm public filing',+ code: "await gapReport('Button', {category: 'docs_gap', reason: 'Missing keyboard example', confirmPublic: true});",+ },+ ],+ command: 'gap-report',+ related: ['component', 'discover', 'swizzle'],+};diff --git a/packages/cli/api/gap-report/gap-report.mjs b/packages/cli/api/gap-report/gap-report.mjsnew file mode 100644index 0000000000..9f2253a55f--- /dev/null+++ b/packages/cli/api/gap-report/gap-report.mjs@@ -0,0 +1,707 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Automatic gap-report routing and delivery — fan-out composition.+ *+ * Resolves the report target from the configured project, then fans the+ * normalized report out to every effective handler: project config first,+ * then each loaded integration in astryx.config order. Each handler is+ * isolated in a worker: stdout→stderr, process exit contained, 30 s timeout,+ * one throw/timeout/exit = that handler's failed delivery; later handlers still+ * run. A public handler is skipped (consent_required) unless confirmPublic.+ *+ * When the effective handler set is empty, a built-in GitHub/routed-only+ * fallback runs. Any handlers present suppress the built-in fallback.+ */++import {Worker} from 'node:worker_threads';+import {AstryxError} from '../error.mjs';+import {Project} from '../../foundation/config/project.mjs';+import {CORE_PACKAGE} from '../../foundation/discovery/component-discovery.mjs';+import {captureEnv} from '../../foundation/debug/event.mjs';+import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';+import {parseGapReportReceipt} from '../../authoring/gap-report/parse.mjs';++/** @typedef {import('../../authoring/gap-report/type').GapReportHandler} GapReportHandler */+/** @typedef {import('../../authoring/gap-report/type').GapReport} GapReport */++const HANDLER_TIMEOUT_MS = 30_000;+const HANDLER_ABORT_GRACE_MS = 25;+const HANDLER_WORKER = new URL('./gap-report-worker.mjs', import.meta.url);++/** Fixed category vocabulary retained from the original CLI surface. */+export const GAP_REPORT_CATEGORIES = Object.freeze([+ Object.freeze({value: 'missing_component', label: 'Missing component'}),+ Object.freeze({value: 'missing_variant', label: 'Missing variant or prop'}),+ Object.freeze({value: 'layout_gap', label: 'Layout gap'}),+ Object.freeze({value: 'styling_gap', label: 'Styling gap'}),+ Object.freeze({value: 'a11y_gap', label: 'Accessibility gap'}),+ Object.freeze({value: 'api_friction', label: 'API friction'}),+ Object.freeze({value: 'docs_gap', label: 'Documentation gap'}),+ Object.freeze({value: 'other', label: 'Other'}),+]);++export const PUBLIC_CONFIRMATION_MESSAGE =+ 'Rerun with --confirm-public to file this report.';++/**+ * @typedef {object} ReportTarget+ * @property {string} package+ * @property {string|null} version+ * @property {string|null} issuesUrl+ */++/**+ * @typedef {(+ * | {kind: 'handler', handlerType: 'project'|'integration', handlerName: string, handler: GapReportHandler, modulePath: string, handlerSource: 'project'|'integration'}+ * | {kind: 'malformed', handlerType: 'integration', handlerName: string, error: string}+ * )} HandlerEntry+ */++/** @param {string} value @returns {number} */+function characterCount(value) {+ return Array.from(value).length;+}++/**+ * @param {unknown} value+ * @param {string} label+ * @param {number} max+ * @returns {string}+ */+function requiredText(value, label, max) {+ if (typeof value !== 'string' || value.trim() === '') {+ throw new AstryxError(+ `${label} is required.`,+ undefined,+ ERROR_CODES.ERR_MISSING_ARGUMENT,+ );+ }+ const normalized = value.trim();+ if (characterCount(normalized) > max) {+ throw new AstryxError(+ `${label} must be ${max} characters or fewer.`,+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ return normalized;+}++/**+ * @param {unknown} value+ * @returns {string|undefined}+ */+function optionalDetail(value) {+ if (value == null || value === '') return undefined;+ if (typeof value !== 'string') {+ throw new AstryxError(+ 'detail must be a string.',+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ const normalized = value.trim();+ if (normalized === '') return undefined;+ if (characterCount(normalized) > 8000) {+ throw new AstryxError(+ 'detail must be 8000 characters or fewer.',+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ return normalized;+}++/**+ * @param {Project} project+ * @param {string} packageName+ * @returns {ReportTarget}+ */+function targetForPackage(project, packageName) {+ if (packageName === CORE_PACKAGE) {+ return {+ package: CORE_PACKAGE,+ version: null,+ issuesUrl: project.issuesUrl({package: CORE_PACKAGE}) ?? null,+ };+ }++ const integration = project.loadedIntegrations.find(+ item => item.name === packageName || item.__spec === packageName,+ );+ if (!integration) {+ throw new AstryxError(+ `No loaded integration package named "${packageName}".`,+ project.loadedIntegrations.map(item => ({+ name: item.name,+ reason: 'loaded integration',+ })),+ ERROR_CODES.ERR_UNKNOWN_PACKAGE,+ );+ }++ return {+ package: integration.name,+ version: integration.version ?? null,+ issuesUrl: project.issuesUrl({package: integration.name}) ?? null,+ };+}++/**+ * Select the report TARGET: the package the report describes.+ * Explicit package first, then unique exact component owner, else Core.+ * Target selection does not depend on handler count.+ *+ * @param {Project} project+ * @param {string} component+ * @param {string|undefined} packageName+ * @returns {Promise<ReportTarget>}+ */+async function selectTarget(project, component, packageName) {+ if (packageName) return targetForPackage(project, packageName);++ const bareComponent = component.startsWith('XDS')+ ? component.slice(3)+ : component;+ const owners = [+ ...new Set(+ (await project.components())+ .filter(+ record => record.name.toLowerCase() === bareComponent.toLowerCase(),+ )+ .map(record => record.package),+ ),+ ];++ if (owners.length > 1) {+ throw new AstryxError(+ `Component "${component}" is provided by multiple packages. Re-run with --package <pkg> to choose one.`,+ owners.map(owner => ({name: owner, reason: 'provides this component'})),+ ERROR_CODES.ERR_AMBIGUOUS_COMPONENT,+ );+ }+ if (owners.length === 1) return targetForPackage(project, owners[0]);++ return targetForPackage(project, CORE_PACKAGE);+}++/**+ * Collect the effective handler set in delivery order: project config first,+ * then integrations in config order. Valid handlers dedupe by handle identity;+ * malformed integration exports retain their position as failed deliveries.+ *+ * @param {Project} project+ * @returns {HandlerEntry[]}+ */+export function collectGapReportHandlers(project) {+ /** @type {HandlerEntry[]} */+ const entries = [];+ /** @type {Set<Function>} */+ const seen = new Set();++ const projectHandler = project.config.gapReport;+ if (projectHandler != null) {+ seen.add(projectHandler.handle);+ entries.push({+ kind: 'handler',+ handlerType: 'project',+ handlerName: 'project',+ handler: projectHandler,+ modulePath: project.configPath ?? '',+ handlerSource: 'project',+ });+ }++ for (const integration of project.loadedIntegrations) {+ if (integration.__loadError) continue;+ if (integration.__gapReportError) {+ entries.push({+ kind: 'malformed',+ handlerType: 'integration',+ handlerName: integration.name,+ error: integration.__gapReportError,+ });+ continue;+ }+ const handler = integration.__gapReport;+ if (handler == null || seen.has(handler.handle)) continue;+ seen.add(handler.handle);+ entries.push({+ kind: 'handler',+ handlerType: 'integration',+ handlerName: integration.name,+ handler,+ modulePath: integration.__manifestFile,+ handlerSource: 'integration',+ });+ }++ return entries;+}++/** @param {string} message */+function failedHandler(message) {+ return {status: /** @type {const} */ ('failed'), url: null, message};+}++/**+ * Call one handler in its own worker. The worker owns process.exit,+ * process.exitCode, stdout, and every continuation the handler creates. A+ * timeout aborts the supplied signal, gives the handler one short turn to+ * observe it, then terminates the isolate before the next handler starts.+ *+ * @param {Extract<HandlerEntry, {kind: 'handler'}>} entry+ * @param {GapReport} report cloned before this call+ * @param {number} [timeoutMs]+ * @returns {Promise<Pick<import('./gap-report.type.mjs').GapReportDelivery, 'status'|'url'|'message'>>}+ */+async function callHandler(entry, report, timeoutMs = HANDLER_TIMEOUT_MS) {+ const worker = new Worker(HANDLER_WORKER, {+ workerData: {+ modulePath: entry.modulePath,+ handlerSource: entry.handlerSource,+ report,+ },+ stdout: true,+ stderr: true,+ execArgv: process.execArgv.filter(arg => !arg.startsWith('--input-type')),+ });++ for (const stream of [worker.stdout, worker.stderr]) {+ stream?.on('data', chunk => {+ try {+ process.stderr.write(chunk);+ } catch {+ // Handler diagnostics are best effort.+ }+ });+ }++ return await new Promise(resolve => {+ let settled = false;+ let timedOut = false;+ /** @type {ReturnType<typeof setTimeout> | undefined} */+ let timeout;+ /** @type {ReturnType<typeof setTimeout> | undefined} */+ let abortGrace;+ const timeoutOutcome = failedHandler('Gap report handler timed out.');++ /** @param {Pick<import('./gap-report.type.mjs').GapReportDelivery, 'status'|'url'|'message'>} outcome */+ const finish = outcome => {+ if (settled) return;+ settled = true;+ if (timeout !== undefined) clearTimeout(timeout);+ if (abortGrace !== undefined) clearTimeout(abortGrace);+ Promise.resolve(worker.terminate())+ .catch(() => {})+ .finally(() => resolve(outcome));+ };++ const beginTimeout = () => {+ if (timeout !== undefined) clearTimeout(timeout);+ timeout = setTimeout(() => {+ if (settled) return;+ timedOut = true;+ try {+ worker.postMessage({type: 'abort'});+ } catch {+ // The worker may have exited at the timeout boundary.+ }+ abortGrace = setTimeout(+ () => finish(timeoutOutcome),+ HANDLER_ABORT_GRACE_MS,+ );+ }, timeoutMs);+ };++ worker.on('message', message => {+ if (settled || timedOut) return;+ if (message?.kind === 'ready') {+ beginTimeout();+ return;+ }+ if (message?.kind === 'exit-code') {+ finish(failedHandler('Handler changed process.exitCode.'));+ return;+ }+ if (message?.kind === 'error') {+ finish(failedHandler(String(message.message)));+ return;+ }+ if (message?.kind !== 'result') {+ finish(failedHandler('Handler worker returned an invalid message.'));+ return;+ }++ const receipt = parseGapReportReceipt(message.value);+ if (!receipt) {+ finish(failedHandler('Handler returned an invalid receipt.'));+ return;+ }+ finish({+ status: receipt.status,+ url: receipt.url ?? null,+ message: receipt.message ?? null,+ });+ });++ worker.on('error', error => {+ if (!timedOut) {+ finish(+ failedHandler(error instanceof Error ? error.message : String(error)),+ );+ }+ });++ worker.on('exit', code => {+ if (settled) return;+ if (timedOut) {+ finish(timeoutOutcome);+ return;+ }+ finish(failedHandler(`Handler called process.exit(${String(code)}).`));+ });++ beginTimeout();+ });+}++/**+ * Deliver one report to the ordered effective handler set. This helper is+ * exported only for focused contract tests; it is not part of the package API.+ *+ * @param {HandlerEntry[]} entries+ * @param {GapReport} report+ * @param {{confirmPublic?: boolean, timeoutMs?: number}} [options]+ * @returns {Promise<import('./gap-report.type.mjs').GapReportDelivery[]>}+ */+export async function deliverGapReportHandlers(+ entries,+ report,+ {confirmPublic = false, timeoutMs = HANDLER_TIMEOUT_MS} = {},+) {+ /** @type {import('./gap-report.type.mjs').GapReportDelivery[]} */+ const deliveries = [];++ for (const entry of entries) {+ if (entry.kind === 'malformed') {+ deliveries.push({+ handlerType: entry.handlerType,+ handler: entry.handlerName,+ audience: null,+ status: 'failed',+ url: null,+ message: entry.error,+ });+ continue;+ }++ const {handler} = entry;+ if (handler.audience === 'public' && !confirmPublic) {+ deliveries.push({+ handlerType: entry.handlerType,+ handler: entry.handlerName,+ audience: handler.audience,+ status: 'consent_required',+ url: null,+ message: PUBLIC_CONFIRMATION_MESSAGE,+ });+ continue;+ }++ const outcome = await callHandler(+ entry,+ structuredClone(report),+ timeoutMs,+ );+ deliveries.push({+ handlerType: entry.handlerType,+ handler: entry.handlerName,+ audience: handler.audience,+ ...outcome,+ });+ }++ return deliveries;+}++/**+ * @param {string} issuesUrl+ * @returns {{repo: string}|null}+ */+function githubRoute(issuesUrl) {+ try {+ const url = new URL(issuesUrl);+ if (url.protocol !== 'https:' || url.hostname !== 'github.com') return null;+ const parts = url.pathname.split('/').filter(Boolean);+ if (+ parts.length < 3 ||+ parts.length > 4 ||+ parts[2] !== 'issues' ||+ (parts.length === 4 && parts[3] !== 'new')+ ) {+ return null;+ }+ return {repo: `${parts[0]}/${parts[1]}`};+ } catch {+ return null;+ }+}++/**+ * Built-in GitHub fallback — runs only when the effective handler set is empty.+ * Requires confirmPublic.+ *+ * @param {ReportTarget} target+ * @param {{component: string, categoryLabel: string, intention: string, detail?: string, source: string, timestamp: string}} report+ * @param {{repo: string}} github+ * @returns {Promise<Pick<import('./gap-report.type.mjs').GapReportDelivery, 'status'|'url'|'message'>>}+ */+async function runGithubFallback(target, report, github) {+ const {execFile} = await import('node:child_process');+ const title = `[gap] ${report.component}: ${report.intention.slice(0, 70)}`;+ const body = [+ `Component: ${report.component}`,+ `Category: ${report.categoryLabel}`,+ `Source: ${report.source}`,+ `Reported: ${report.timestamp}`,+ '',+ '## Intention',+ '',+ report.intention,+ ...(report.detail ? ['', '## Additional context', '', report.detail] : []),+ ].join('\n');++ try {+ const output = await new Promise((resolve, reject) => {+ execFile(+ 'gh',+ [+ 'issue',+ 'create',+ '--repo',+ github.repo,+ '--title',+ title,+ '--body',+ body,+ ],+ {encoding: 'utf8', timeout: HANDLER_TIMEOUT_MS, windowsHide: true},+ (error, stdout) => {+ if (error) reject(error);+ else resolve(stdout);+ },+ );+ });++ const value = /** @type {string} */ (output).trim();+ let url = null;+ try {+ const parsedUrl = new URL(value);+ if (parsedUrl.protocol === 'https:' || parsedUrl.protocol === 'http:') {+ url = value;+ }+ } catch {+ // non-URL output from gh+ }+ return {+ status: /** @type {const} */ ('filed'),+ url,+ message: url ? 'Gap report filed.' : value || 'Gap report filed.',+ };+ } catch {+ return {+ status: /** @type {const} */ ('failed'),+ url: null,+ message:+ 'GitHub CLI could not create the routed issue. Install and authenticate gh, then retry.',+ };+ }+}++/**+ * Compute the aggregate status from the deliveries.+ * @param {import('./gap-report.type.mjs').GapReportDelivery[]} deliveries+ * @returns {import('./gap-report.type.mjs').GapReportAggregateStatus}+ */+function aggregateStatus(deliveries) {+ if (deliveries.length === 0) return 'skipped';++ const statuses = new Set(deliveries.map(d => d.status));++ // All consent_required+ if (statuses.size === 1 && statuses.has('consent_required'))+ return 'consent_required';+ // All skipped+ if (statuses.size === 1 && statuses.has('skipped')) return 'skipped';+ // All failed+ if (statuses.size === 1 && statuses.has('failed')) return 'failed';+ // All routed_only (no filed)+ if (+ !statuses.has('filed') &&+ statuses.has('routed_only') &&+ !statuses.has('failed')+ )+ return 'routed_only';++ const hasFiled = statuses.has('filed');+ const hasFailed = statuses.has('failed');+ const hasHandledWithoutFiling =+ statuses.has('routed_only') ||+ statuses.has('skipped') ||+ statuses.has('consent_required');++ if (hasFailed && (hasFiled || hasHandledWithoutFiling)) return 'partial';+ if (hasFailed) return 'failed';+ if (hasFiled) return 'filed';++ // Mixed non-failure (e.g. routed_only + consent_required + skipped)+ if (statuses.has('routed_only')) return 'routed_only';+ if (statuses.has('consent_required')) return 'consent_required';+ return 'skipped';+}++/**+ * List categories or route and file one gap report through the fan-out.+ *+ * @param {string|undefined} component+ * @param {import('./gap-report.type.mjs').GapReportOptions} [options]+ * @returns {Promise<import('./gap-report.type.mjs').GapReportCategoriesResponse | import('./gap-report.type.mjs').GapReportReceiptResponse>}+ */+export async function gapReport(component, options = {}) {+ if (options.listCategories) {+ return {+ type: 'gap-report.categories',+ data: GAP_REPORT_CATEGORIES.map(category => ({...category})),+ };+ }++ const resolvedComponent = requiredText(component, 'component', 120);+ const category = requiredText(options.category, 'category', 80);+ const categoryEntry = GAP_REPORT_CATEGORIES.find(+ entry => entry.value === category,+ );+ if (!categoryEntry) {+ throw new AstryxError(+ `Unknown gap category "${category}".`,+ GAP_REPORT_CATEGORIES.map(entry => ({+ name: entry.value,+ reason: entry.label,+ })),+ ERROR_CODES.ERR_UNKNOWN_CATEGORY,+ );+ }+ const intention = requiredText(options.reason, 'reason', 2000);+ const detail = optionalDetail(options.detail);+ const cwd = (await import('node:path')).resolve(options.cwd ?? process.cwd());+ const project = await Project.load(cwd);+ const target = await selectTarget(+ project,+ resolvedComponent,+ options.package,+ );++ const entries = collectGapReportHandlers(project);++ const timestamp = new Date().toISOString();+ const source = captureEnv().invocationSource;++ /** @type {GapReport} */+ const report = {+ schemaVersion: 1,+ component: resolvedComponent,+ category:+ /** @type {import('../../authoring/gap-report/type').GapReportCategory} */ (+ categoryEntry.value+ ),+ categoryLabel: categoryEntry.label,+ intention,+ ...(detail ? {detail} : {}),+ source,+ timestamp,+ target: {+ package: target.package,+ version: target.version,+ issuesUrl: target.issuesUrl,+ },+ };++ /** @type {import('./gap-report.type.mjs').GapReportDelivery[]} */+ const deliveries = [];++ if (entries.length > 0) {+ deliveries.push(+ ...(await deliverGapReportHandlers(entries, report, {+ confirmPublic: options.confirmPublic === true,+ })),+ );+ } else {+ if (!target.issuesUrl) {+ throw new AstryxError(+ `Package "${target.package}" provides neither a report handler nor an issues URL.`,+ undefined,+ ERROR_CODES.ERR_NOT_FOUND,+ );+ }++ const github = githubRoute(target.issuesUrl);+ if (github != null && options.confirmPublic !== true) {+ deliveries.push({+ handlerType: 'fallback',+ handler: 'github',+ audience: 'public',+ status: 'consent_required',+ url: null,+ message: PUBLIC_CONFIRMATION_MESSAGE,+ });+ } else if (github) {+ const outcome = await runGithubFallback(+ target,+ {+ component: resolvedComponent,+ categoryLabel: categoryEntry.label,+ intention,+ detail,+ source,+ timestamp,+ },+ github,+ );+ deliveries.push({+ handlerType: 'fallback',+ handler: 'github',+ audience: 'public',+ ...outcome,+ });+ } else {+ deliveries.push({+ handlerType: 'fallback',+ handler: 'issuesUrl',+ audience: null,+ status: 'routed_only',+ url: target.issuesUrl,+ message:+ 'No automatic handler is available; open the routed URL to file this report.',+ });+ }+ }++ const filedCount = deliveries.filter(d => d.status === 'filed').length;+ const routedOnlyCount = deliveries.filter(+ d => d.status === 'routed_only',+ ).length;+ const status = aggregateStatus(deliveries);++ return {+ type: 'gap-report.file',+ data: {+ status,+ package: target.package,+ issuesUrl: target.issuesUrl,+ deliveries,+ filedCount,+ routedOnlyCount,+ },+ };+}diff --git a/packages/cli/api/gap-report/gap-report.test.mjs b/packages/cli/api/gap-report/gap-report.test.mjsnew file mode 100644index 0000000000..43789c0985--- /dev/null+++ b/packages/cli/api/gap-report/gap-report.test.mjs@@ -0,0 +1,1210 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++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 {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import {Project} from '../../foundation/config/project.mjs';+import {+ GAP_REPORT_CATEGORIES,+ PUBLIC_CONFIRMATION_MESSAGE,+ collectGapReportHandlers,+ deliverGapReportHandlers,+ gapReport,+} from './gap-report.mjs';++let projectDir;++function configure(integrations = [], opts = {}) {+ const config = {integrations, ...opts};+ fs.writeFileSync(+ path.join(projectDir, 'astryx.config.mjs'),+ `export default ${JSON.stringify(config)};\n`,+ );+}++function packageDir(packageName) {+ return path.join(projectDir, 'node_modules', ...packageName.split('/'));+}++function addCoreComponent(component = 'Button') {+ const coreDir = packageDir('@astryxdesign/core');+ const componentDir = path.join(coreDir, 'src', component);+ fs.mkdirSync(componentDir, {recursive: true});+ fs.writeFileSync(+ path.join(coreDir, 'package.json'),+ JSON.stringify({name: '@astryxdesign/core', version: '0.5.4'}),+ );+ fs.writeFileSync(+ path.join(componentDir, `${component}.doc.mjs`),+ `export default {name: ${JSON.stringify(component)}, usage: {description: 'Core fixture'}, props: []};\n`,+ );+ fs.writeFileSync(+ path.join(componentDir, `${component}.tsx`),+ `export const ${component} = null;\n`,+ );+}++/**+ * Add an integration with a handler (function-based, not executable).+ * @param {object} opts+ * @param {string} opts.name+ * @param {'internal'|'public'} [opts.audience]+ * @param {string} [opts.issuesUrl]+ * @param {string} [opts.component]+ * @param {boolean} [opts.handler] whether to export a gapReport handler+ * @param {string} [opts.handleBody] JS code for the handle function body+ * @param {string} [opts.malformedExport] raw JS to export instead of a proper handler+ */+function addIntegration({+ name,+ audience = 'public',+ issuesUrl,+ component,+ handler = true,+ handleBody = "return {status: 'filed', message: 'Handled by ' + " ++ JSON.stringify(name) ++ '};',+ malformedExport,+}) {+ const dir = packageDir(name);+ fs.mkdirSync(dir, {recursive: true});+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ JSON.stringify({name, version: '1.2.3'}),+ );++ const manifest = {};+ if (issuesUrl) manifest.issuesUrl = issuesUrl;+ if (component) {+ manifest.components = './components';+ const components = path.join(dir, 'components');+ fs.mkdirSync(components, {recursive: true});+ fs.writeFileSync(+ path.join(components, `${component}.doc.mjs`),+ `export default {name: ${JSON.stringify(component)}, usage: {description: 'Fixture'}, props: []};\n`,+ );+ fs.writeFileSync(+ path.join(components, `${component}.tsx`),+ `export const ${component} = null;\n`,+ );+ }++ let namedExport = '';+ if (malformedExport != null) {+ namedExport = malformedExport;+ } else if (handler) {+ namedExport = `export const gapReport = {\n audience: ${JSON.stringify(audience)},\n handle: async (report, {signal}) => { ${handleBody} },\n};\n`;+ }++ fs.writeFileSync(+ path.join(dir, 'astryx.integration.mjs'),+ `${namedExport}export default ${JSON.stringify(manifest)};\n`,+ );+ return {dir};+}++const reportOptions = {+ category: 'missing_variant',+ reason: 'Need a compact size',+ detail: 'The current size does not fit the toolbar.',+};++beforeEach(() => {+ projectDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-gap-report-'));+ fs.writeFileSync(+ path.join(projectDir, 'package.json'),+ JSON.stringify({name: 'fixture-app'}),+ );+ configure();+});++afterEach(() => {+ vi.unstubAllEnvs();+ fs.rmSync(projectDir, {recursive: true, force: true});+});++describe('gapReport categories and validation', () => {+ it('preserves the legacy category vocabulary', async () => {+ const result = await gapReport(undefined, {listCategories: true});+ expect(result).toEqual({+ type: 'gap-report.categories',+ data: GAP_REPORT_CATEGORIES,+ });+ expect(result.data.map(item => item.value)).toEqual([+ 'missing_component',+ 'missing_variant',+ 'layout_gap',+ 'styling_gap',+ 'a11y_gap',+ 'api_friction',+ 'docs_gap',+ 'other',+ ]);+ });++ it('rejects missing, unknown, and oversized report fields', async () => {+ await expect(+ gapReport(undefined, {...reportOptions, cwd: projectDir}),+ ).rejects.toMatchObject({code: 'ERR_MISSING_ARGUMENT'});+ await expect(+ gapReport('Button', {+ ...reportOptions,+ category: 'not_real',+ cwd: projectDir,+ }),+ ).rejects.toMatchObject({code: 'ERR_UNKNOWN_CATEGORY'});+ await expect(+ gapReport('Button', {+ ...reportOptions,+ detail: 'x'.repeat(8001),+ cwd: projectDir,+ }),+ ).rejects.toMatchObject({code: 'ERR_INVALID_ARGUMENT'});+ });+});++describe('gapReport fan-out composition', () => {+ it('project handler and integration handler both run in order', async () => {+ const name = '@test/integration-one';+ addIntegration({+ name,+ audience: 'internal',+ handleBody: "return {status: 'filed', message: 'from integration'};",+ });++ // Write config with project handler + integration+ fs.writeFileSync(+ path.join(projectDir, 'astryx.config.mjs'),+ `+export default {+ integrations: [${JSON.stringify(name)}],+ gapReport: {+ audience: 'internal',+ handle: (report) => ({status: 'filed', message: 'from project'}),+ },+};+`,+ );++ const result = await gapReport('General', {+ ...reportOptions,+ cwd: projectDir,+ });++ expect(result.data.status).toBe('filed');+ expect(result.data.deliveries).toHaveLength(2);+ expect(+ result.data.deliveries.map(({handlerType, handler, audience}) => ({+ handlerType,+ handler,+ audience,+ })),+ ).toEqual([+ {handlerType: 'project', handler: 'project', audience: 'internal'},+ {+ handlerType: 'integration',+ handler: name,+ audience: 'internal',+ },+ ]);+ expect(result.data.deliveries[0].message).toBe('from project');+ expect(result.data.deliveries[1].message).toBe('from integration');+ expect(result.data.filedCount).toBe(2);+ });++ it('runs the self-resolved local package handler', async () => {+ fs.writeFileSync(+ path.join(projectDir, 'package.json'),+ JSON.stringify({name: '@test/local', version: '1.0.0'}),+ );+ fs.writeFileSync(+ path.join(projectDir, 'astryx.integration.mjs'),+ `export const gapReport = {+ audience: 'internal',+ handle(report) { return {status: 'filed', message: report.component}; },+};+export default {};+`,+ );++ const result = await gapReport('General', {+ ...reportOptions,+ cwd: projectDir,+ });++ expect(result.data.deliveries).toEqual([+ expect.objectContaining({+ handlerType: 'integration',+ handler: '@test/local',+ audience: 'internal',+ status: 'filed',+ message: 'General',+ }),+ ]);+ });++ it('all integration handlers run in config order', async () => {+ addIntegration({+ name: '@test/first',+ audience: 'internal',+ handleBody: "return {status: 'filed', message: 'first'};",+ });+ addIntegration({+ name: '@test/second',+ audience: 'internal',+ handleBody: "return {status: 'filed', message: 'second'};",+ });+ addIntegration({+ name: '@test/third',+ audience: 'internal',+ handleBody: "return {status: 'filed', message: 'third'};",+ });+ configure(['@test/first', '@test/second', '@test/third']);++ const result = await gapReport('General', {+ ...reportOptions,+ cwd: projectDir,+ });++ expect(result.data.deliveries).toHaveLength(3);+ expect(result.data.deliveries.map(d => d.handler)).toEqual([+ '@test/first',+ '@test/second',+ '@test/third',+ ]);+ expect(result.data.deliveries.map(d => d.message)).toEqual([+ 'first',+ 'second',+ 'third',+ ]);+ expect(result.data.filedCount).toBe(3);+ expect(result.data.status).toBe('filed');+ });++ it('deduplicates handlers by handle function identity', async () => {+ // Create two integrations that share the same handle function+ const sharedDir = path.join(projectDir, 'shared-handler');+ fs.mkdirSync(sharedDir, {recursive: true});+ fs.writeFileSync(+ path.join(sharedDir, 'handler.mjs'),+ "export const handle = async (report) => ({status: 'filed', message: 'shared'});\n",+ );++ const dir1 = packageDir('@test/first');+ fs.mkdirSync(dir1, {recursive: true});+ fs.writeFileSync(+ path.join(dir1, 'package.json'),+ JSON.stringify({name: '@test/first', version: '1.0.0'}),+ );+ fs.writeFileSync(+ path.join(dir1, 'astryx.integration.mjs'),+ `import {handle} from ${JSON.stringify(path.join(sharedDir, 'handler.mjs'))};\nexport const gapReport = {audience: 'internal', handle};\nexport default {};\n`,+ );++ const dir2 = packageDir('@test/second');+ fs.mkdirSync(dir2, {recursive: true});+ fs.writeFileSync(+ path.join(dir2, 'package.json'),+ JSON.stringify({name: '@test/second', version: '1.0.0'}),+ );+ fs.writeFileSync(+ path.join(dir2, 'astryx.integration.mjs'),+ `import {handle} from ${JSON.stringify(path.join(sharedDir, 'handler.mjs'))};\nexport const gapReport = {audience: 'internal', handle};\nexport default {};\n`,+ );++ configure(['@test/first', '@test/second']);++ const result = await gapReport('General', {+ ...reportOptions,+ cwd: projectDir,+ });++ expect(result.data.deliveries).toHaveLength(1);+ expect(result.data.deliveries[0].message).toBe('shared');+ });++ it('deduplicates the same handle across project and integration', () => {+ const handle = async () => ({status: 'filed', message: 'shared'});+ const entries = collectGapReportHandlers(+ /** @type {any} */ ({+ config: {gapReport: {audience: 'internal', handle}},+ configPath: '/tmp/astryx.config.mjs',+ loadedIntegrations: [+ {+ name: '@test/shared',+ __manifestFile: '/tmp/astryx.integration.mjs',+ __gapReport: {audience: 'internal', handle},+ },+ ],+ }),+ );++ expect(entries).toHaveLength(1);+ expect(entries[0]).toMatchObject({+ kind: 'handler',+ handlerType: 'project',+ handlerName: 'project',+ });+ });++ it('each handler receives a fresh structuredClone', async () => {+ addIntegration({+ name: '@test/mutator',+ audience: 'internal',+ handleBody:+ "report.component = 'MUTATED'; return {status: 'filed', message: report.component};",+ });+ addIntegration({+ name: '@test/reader',+ audience: 'internal',+ handleBody: "return {status: 'filed', message: report.component};",+ });+ configure(['@test/mutator', '@test/reader']);++ const result = await gapReport('General', {+ ...reportOptions,+ cwd: projectDir,+ });++ expect(result.data.deliveries).toHaveLength(2);+ expect(result.data.deliveries[0].message).toBe('MUTATED');+ expect(result.data.deliveries[1].message).toBe('General');+ });++ it('repeated Project.load does not duplicate handlers', async () => {+ addIntegration({+ name: '@test/only',+ audience: 'internal',+ handleBody: "return {status: 'filed', message: 'once'};",+ });+ configure(['@test/only']);++ // Call twice — second load should not add duplicates+ const result1 = await gapReport('General', {+ ...reportOptions,+ cwd: projectDir,+ });+ const result2 = await gapReport('General', {+ ...reportOptions,+ cwd: projectDir,+ });++ expect(result1.data.deliveries).toHaveLength(1);+ expect(result2.data.deliveries).toHaveLength(1);+ });++ it('does not treat inheritDebug as a gap-report opt-out', async () => {+ fs.writeFileSync(+ path.join(projectDir, 'package.json'),+ JSON.stringify({name: 'fixture-app', astryx: {inheritDebug: false}}),+ );+ addIntegration({+ name: '@test/always',+ audience: 'internal',+ handleBody: "return {status: 'filed', message: 'still ran'};",+ });+ configure(['@test/always']);++ const result = await gapReport('General', {+ ...reportOptions,+ cwd: projectDir,+ });++ expect(result.data.deliveries).toHaveLength(1);+ expect(result.data.deliveries[0]).toMatchObject({+ handler: '@test/always',+ status: 'filed',+ });+ });+});++describe('gapReport handler isolation', () => {+ it('terminates one timed-out handler and then runs the next handler', async () => {+ addIntegration({+ name: '@test/slow',+ audience: 'internal',+ handleBody: 'return new Promise(() => {});',+ });+ addIntegration({+ name: '@test/after',+ audience: 'internal',+ handleBody: "return {status: 'filed', message: 'after'};",+ });+ configure(['@test/slow', '@test/after']);+ const project = await Project.load(projectDir);++ const deliveries = await deliverGapReportHandlers(+ collectGapReportHandlers(project),+ /** @type {any} */ ({component: 'Button'}),+ {timeoutMs: 200},+ );++ expect(deliveries).toEqual([+ {+ handlerType: 'integration',+ handler: '@test/slow',+ audience: 'internal',+ status: 'failed',+ url: null,+ message: 'Gap report handler timed out.',+ },+ {+ handlerType: 'integration',+ handler: '@test/after',+ audience: 'internal',+ status: 'filed',+ url: null,+ message: 'after',+ },+ ]);+ });++ it('a timed-out late process.exit cannot terminate the caller', () => {+ addIntegration({+ name: '@test/late-exit',+ audience: 'internal',+ handleBody:+ 'await new Promise(resolve => setTimeout(resolve, 210)); process.exit(42);',+ });+ addIntegration({+ name: '@test/after-late-exit',+ audience: 'internal',+ handleBody: "return {status: 'filed', message: 'survived'};",+ });+ configure(['@test/late-exit', '@test/after-late-exit']);++ const projectModule = path.resolve(+ import.meta.dirname,+ '../../foundation/config/project.mjs',+ );+ const gapModule = path.resolve(import.meta.dirname, 'gap-report.mjs');+ const source = `+ const {Project} = await import(${JSON.stringify(projectModule)});+ const {collectGapReportHandlers, deliverGapReportHandlers} = await import(${JSON.stringify(gapModule)});+ const project = await Project.load(${JSON.stringify(projectDir)});+ const deliveries = await deliverGapReportHandlers(+ collectGapReportHandlers(project),+ {component: 'Button'},+ {timeoutMs: 200},+ );+ await new Promise(resolve => setTimeout(resolve, 300));+ process.stdout.write(JSON.stringify(deliveries));+ `;+ const child = spawnSync(+ process.execPath,+ ['--input-type=module', '-e', source],+ {encoding: 'utf8', timeout: 5000},+ );++ expect(child.status, child.stderr).toBe(0);+ expect(JSON.parse(child.stdout)).toMatchObject([+ {handler: '@test/late-exit', status: 'failed'},+ {handler: '@test/after-late-exit', status: 'filed'},+ ]);+ });++ it('redirects handler stdout and restores the parent stream method', async () => {+ fs.writeFileSync(+ path.join(projectDir, 'astryx.config.mjs'),+ `export default {+ gapReport: {+ audience: 'internal',+ handle() {+ process.stdout.write('handler-noise');+ return {status: 'skipped'};+ },+ },+};\n`,+ );+ const project = await Project.load(projectDir);+ const stderrWrite = vi+ .spyOn(process.stderr, 'write')+ .mockImplementation(() => true);+ const stdoutBefore = process.stdout.write;+ try {+ const deliveries = await deliverGapReportHandlers(+ collectGapReportHandlers(project),+ /** @type {any} */ ({component: 'Button'}),+ );++ expect(deliveries[0].status).toBe('skipped');+ expect(+ stderrWrite.mock.calls.map(call => String(call[0])).join(''),+ ).toContain('handler-noise');+ expect(process.stdout.write).toBe(stdoutBefore);+ } finally {+ stderrWrite.mockRestore();+ }+ });++ it('later handlers run after one throws', async () => {+ addIntegration({+ name: '@test/thrower',+ audience: 'internal',+ handleBody: "throw new Error('handler exploded');",+ });+ addIntegration({+ name: '@test/survivor',+ audience: 'internal',+ handleBody: "return {status: 'filed', message: 'survived'};",+ });+ configure(['@test/thrower', '@test/survivor']);++ const result = await gapReport('General', {+ ...reportOptions,+ cwd: projectDir,+ });++ expect(result.data.deliveries).toHaveLength(2);+ expect(result.data.deliveries[0].status).toBe('failed');+ expect(result.data.deliveries[0].message).toContain('handler exploded');+ expect(result.data.deliveries[1].status).toBe('filed');+ expect(result.data.deliveries[1].message).toBe('survived');+ expect(result.data.status).toBe('partial');+ });++ it('later handlers run after one tries process.exit', async () => {+ addIntegration({+ name: '@test/exiter',+ audience: 'internal',+ handleBody: 'process.exit(42);',+ });+ addIntegration({+ name: '@test/survivor',+ audience: 'internal',+ handleBody: "return {status: 'filed', message: 'still here'};",+ });+ configure(['@test/exiter', '@test/survivor']);++ const result = await gapReport('General', {+ ...reportOptions,+ cwd: projectDir,+ });++ expect(result.data.deliveries).toHaveLength(2);+ expect(result.data.deliveries[0].status).toBe('failed');+ expect(result.data.deliveries[0].message).toContain('process.exit');+ expect(result.data.deliveries[1].status).toBe('filed');+ expect(result.data.filedCount).toBe(1);+ });++ it('later handlers run after one changes process.exitCode', async () => {+ addIntegration({+ name: '@test/exit-code',+ audience: 'internal',+ handleBody:+ "process.exitCode = 42; return {status: 'filed', message: 'wrong'};",+ });+ addIntegration({+ name: '@test/survivor',+ audience: 'internal',+ handleBody: "return {status: 'filed', message: 'still here'};",+ });+ configure(['@test/exit-code', '@test/survivor']);+ const before = process.exitCode;++ const result = await gapReport('General', {+ ...reportOptions,+ cwd: projectDir,+ });++ expect(process.exitCode).toBe(before);+ expect(result.data.deliveries[0]).toMatchObject({+ handler: '@test/exit-code',+ status: 'failed',+ message: 'Handler changed process.exitCode.',+ });+ expect(result.data.deliveries[1]).toMatchObject({+ handler: '@test/survivor',+ status: 'filed',+ });+ });++ it('handler that returns non-receipt is a failed delivery', async () => {+ addIntegration({+ name: '@test/non-receipt',+ audience: 'internal',+ handleBody: "return 'not an object';",+ });+ addIntegration({+ name: '@test/after',+ audience: 'internal',+ handleBody: "return {status: 'filed', message: 'still ok'};",+ });+ configure(['@test/non-receipt', '@test/after']);++ const result = await gapReport('General', {+ ...reportOptions,+ cwd: projectDir,+ });++ expect(result.data.deliveries).toHaveLength(2);+ expect(result.data.deliveries[0].status).toBe('failed');+ expect(result.data.deliveries[1].status).toBe('filed');+ });++ it('malformed integration handler is isolated as a failed delivery', async () => {+ const dir = packageDir('@test/malformed');+ fs.mkdirSync(dir, {recursive: true});+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ JSON.stringify({name: '@test/malformed', version: '1.0.0'}),+ );+ fs.writeFileSync(+ path.join(dir, 'astryx.integration.mjs'),+ "export const gapReport = {audience: 'internal', command: './writer.mjs'};\nexport default {};\n",+ );++ addIntegration({+ name: '@test/valid',+ audience: 'internal',+ handleBody: "return {status: 'filed', message: 'ok'};",+ });+ configure(['@test/malformed', '@test/valid']);++ const result = await gapReport('General', {+ ...reportOptions,+ cwd: projectDir,+ });++ expect(result.data.deliveries).toHaveLength(2);+ expect(result.data.deliveries.map(d => d.handler)).toEqual([+ '@test/malformed',+ '@test/valid',+ ]);+ expect(result.data.deliveries[0].status).toBe('failed');+ expect(result.data.deliveries[1]).toMatchObject({+ status: 'filed',+ message: 'ok',+ });+ });++ it('invalid handler receipt is recorded as failed delivery', async () => {+ addIntegration({+ name: '@test/bad-receipt',+ audience: 'internal',+ handleBody: "return {status: 'invalid_status'};",+ });+ addIntegration({+ name: '@test/good',+ audience: 'internal',+ handleBody: "return {status: 'filed', message: 'good'};",+ });+ configure(['@test/bad-receipt', '@test/good']);++ const result = await gapReport('General', {+ ...reportOptions,+ cwd: projectDir,+ });++ expect(result.data.deliveries).toHaveLength(2);+ expect(result.data.deliveries[0].status).toBe('failed');+ expect(result.data.deliveries[0].message).toContain('invalid receipt');+ expect(result.data.deliveries[1].status).toBe('filed');+ });+});++describe('gapReport per-handler consent', () => {+ it('gates a public project handler until consent is explicit', async () => {+ const marker = path.join(projectDir, 'project-handler-ran');+ fs.writeFileSync(+ path.join(projectDir, 'astryx.config.mjs'),+ `import * as fs from 'node:fs';+export default {+ gapReport: {+ audience: 'public',+ handle() {+ fs.writeFileSync(${JSON.stringify(marker)}, 'yes');+ return {status: 'filed', message: 'project filed'};+ },+ },+};\n`,+ );++ const pending = await gapReport('General', {+ ...reportOptions,+ cwd: projectDir,+ });+ expect(pending.data.deliveries[0]).toMatchObject({+ handlerType: 'project',+ handler: 'project',+ audience: 'public',+ status: 'consent_required',+ });+ expect(fs.existsSync(marker)).toBe(false);++ const filed = await gapReport('General', {+ ...reportOptions,+ confirmPublic: true,+ cwd: projectDir,+ });+ expect(filed.data.deliveries[0]).toMatchObject({+ handlerType: 'project',+ handler: 'project',+ audience: 'public',+ status: 'filed',+ });+ expect(fs.readFileSync(marker, 'utf8')).toBe('yes');+ });++ it('public handler is skipped while internal handler runs', async () => {+ addIntegration({+ name: '@test/public-one',+ audience: 'public',+ handleBody: "return {status: 'filed', message: 'public filed'};",+ });+ addIntegration({+ name: '@test/internal-one',+ audience: 'internal',+ handleBody: "return {status: 'filed', message: 'internal filed'};",+ });+ configure(['@test/public-one', '@test/internal-one']);++ const result = await gapReport('General', {+ ...reportOptions,+ cwd: projectDir,+ });++ expect(result.data.deliveries).toHaveLength(2);+ expect(result.data.deliveries[0].status).toBe('consent_required');+ expect(result.data.deliveries[0].message).toBe(PUBLIC_CONFIRMATION_MESSAGE);+ expect(result.data.deliveries[1].status).toBe('filed');+ expect(result.data.deliveries[1].message).toBe('internal filed');+ expect(result.data.filedCount).toBe(1);+ });++ it('multiple internal handlers all run without consent', async () => {+ addIntegration({+ name: '@test/internal-a',+ audience: 'internal',+ handleBody: "return {status: 'filed', message: 'a'};",+ });+ addIntegration({+ name: '@test/internal-b',+ audience: 'internal',+ handleBody: "return {status: 'filed', message: 'b'};",+ });+ configure(['@test/internal-a', '@test/internal-b']);++ const result = await gapReport('General', {+ ...reportOptions,+ cwd: projectDir,+ });++ expect(result.data.deliveries).toHaveLength(2);+ expect(result.data.deliveries.every(d => d.status === 'filed')).toBe(true);+ expect(result.data.filedCount).toBe(2);+ expect(result.data.status).toBe('filed');+ });++ it('public handler runs when confirmPublic is true', async () => {+ addIntegration({+ name: '@test/public-ok',+ audience: 'public',+ handleBody: "return {status: 'filed', message: 'public worked'};",+ });+ configure(['@test/public-ok']);++ const result = await gapReport('General', {+ ...reportOptions,+ confirmPublic: true,+ cwd: projectDir,+ });++ expect(result.data.deliveries).toHaveLength(1);+ expect(result.data.deliveries[0].status).toBe('filed');+ expect(result.data.deliveries[0].message).toBe('public worked');+ });+});++describe('gapReport fallback behavior', () => {+ it('handlers suppress the built-in fallback', async () => {+ addIntegration({+ name: '@test/has-handler',+ audience: 'internal',+ issuesUrl: 'https://github.com/acme/widgets/issues',+ handleBody: "return {status: 'filed', message: 'handler took it'};",+ });+ configure(['@test/has-handler'], {+ issuesUrl: 'https://github.com/acme/core/issues',+ });++ const result = await gapReport('General', {+ ...reportOptions,+ cwd: projectDir,+ });++ // Should use handler, not GitHub fallback+ expect(result.data.deliveries).toHaveLength(1);+ expect(result.data.deliveries[0].message).toBe('handler took it');+ });++ it('no-handler GitHub consent-gated fallback works', async () => {+ configure([], {issuesUrl: 'https://github.com/acme/widgets/issues/new'});+ const binDir = path.join(projectDir, 'bin');+ const argsFile = path.join(projectDir, 'gh-args.json');+ fs.mkdirSync(binDir, {recursive: true});+ fs.writeFileSync(+ path.join(binDir, 'gh'),+ `#!/usr/bin/env node+import fs from 'node:fs';+fs.writeFileSync(${JSON.stringify(argsFile)}, JSON.stringify(process.argv.slice(2)));+console.log('https://github.com/acme/widgets/issues/42');+`,+ {mode: 0o755},+ );+ fs.chmodSync(path.join(binDir, 'gh'), 0o755);+ vi.stubEnv('PATH', `${binDir}${path.delimiter}${process.env.PATH ?? ''}`);++ // Without consent+ const pending = await gapReport('Button', {+ ...reportOptions,+ cwd: projectDir,+ });+ expect(pending.data.deliveries[0].status).toBe('consent_required');+ expect(fs.existsSync(argsFile)).toBe(false);++ // With consent+ const filed = await gapReport('Button', {+ ...reportOptions,+ confirmPublic: true,+ cwd: projectDir,+ });+ expect(filed.data.deliveries[0].status).toBe('filed');+ expect(filed.data.status).toBe('filed');+ });++ it('no-handler non-GitHub route returns routed_only', async () => {+ configure([], {issuesUrl: 'https://tracker.example/new'});++ const result = await gapReport('Button', {+ ...reportOptions,+ confirmPublic: true,+ cwd: projectDir,+ });++ expect(result.data.deliveries[0].status).toBe('routed_only');+ expect(result.data.deliveries[0].url).toBe('https://tracker.example/new');+ expect(result.data.status).toBe('routed_only');+ });++ it('no handler and no issues URL throws ERR_NOT_FOUND', async () => {+ // Create a project with an integration that has no handler, no issuesUrl,+ // and target an unknown package explicitly+ const name = '@test/bare';+ const dir = packageDir(name);+ fs.mkdirSync(dir, {recursive: true});+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ JSON.stringify({name, version: '1.0.0'}),+ );+ fs.writeFileSync(+ path.join(dir, 'astryx.integration.mjs'),+ 'export default {};\n',+ );+ configure([name]);++ await expect(+ gapReport('Button', {+ ...reportOptions,+ package: name,+ cwd: projectDir,+ }),+ ).rejects.toMatchObject({code: 'ERR_NOT_FOUND'});+ });+});++describe('gapReport target selection', () => {+ it('routes to the unique component owner', async () => {+ addIntegration({+ name: '@test/owner',+ audience: 'internal',+ component: 'TargetWidget',+ handleBody: "return {status: 'filed', message: report.target.package};",+ });+ configure(['@test/owner']);++ const result = await gapReport('XDSTargetWidget', {+ ...reportOptions,+ cwd: projectDir,+ });++ expect(result.data.package).toBe('@test/owner');+ expect(result.data.deliveries[0].message).toBe('@test/owner');+ });++ it('uses explicit package', async () => {+ addIntegration({+ name: '@test/first',+ audience: 'internal',+ handleBody: "return {status: 'filed', message: 'first'};",+ });+ addIntegration({+ name: '@test/second',+ audience: 'internal',+ handleBody: "return {status: 'filed', message: 'second'};",+ });+ configure(['@test/first', '@test/second']);++ const result = await gapReport('General', {+ ...reportOptions,+ package: '@test/second',+ cwd: projectDir,+ });++ expect(result.data.package).toBe('@test/second');+ // Both handlers still run (fan-out)+ expect(result.data.deliveries).toHaveLength(2);+ });++ it('falls back to Core when no component owner found', async () => {+ addIntegration({+ name: '@test/no-match',+ audience: 'internal',+ handleBody: "return {status: 'filed', message: report.target.package};",+ });+ configure(['@test/no-match']);++ const result = await gapReport('General', {+ ...reportOptions,+ cwd: projectDir,+ });++ expect(result.data.package).toBe('@astryxdesign/core');+ });++ it('requires --package when multiple packages own the component', async () => {+ addIntegration({+ name: '@test/first',+ component: 'SharedWidget',+ audience: 'internal',+ });+ addIntegration({+ name: '@test/second',+ component: 'SharedWidget',+ audience: 'internal',+ });+ configure(['@test/first', '@test/second']);++ await expect(+ gapReport('SharedWidget', {...reportOptions, cwd: projectDir}),+ ).rejects.toMatchObject({code: 'ERR_AMBIGUOUS_COMPONENT'});+ });+});++describe('gapReport aggregate status and CLI exit', () => {+ it('all filed → status filed', async () => {+ addIntegration({+ name: '@test/a',+ audience: 'internal',+ handleBody: "return {status: 'filed', message: 'a'};",+ });+ configure(['@test/a']);++ const result = await gapReport('General', {+ ...reportOptions,+ cwd: projectDir,+ });+ expect(result.data.status).toBe('filed');+ });++ it('mix of filed and failed → status partial', async () => {+ addIntegration({+ name: '@test/fail',+ audience: 'internal',+ handleBody: "throw new Error('boom');",+ });+ addIntegration({+ name: '@test/ok',+ audience: 'internal',+ handleBody: "return {status: 'filed', message: 'ok'};",+ });+ configure(['@test/fail', '@test/ok']);++ const result = await gapReport('General', {+ ...reportOptions,+ cwd: projectDir,+ });+ expect(result.data.status).toBe('partial');+ });++ it('mix of failed and consent-required → status partial', async () => {+ addIntegration({+ name: '@test/fail',+ audience: 'internal',+ handleBody: "throw new Error('boom');",+ });+ addIntegration({+ name: '@test/public',+ audience: 'public',+ handleBody: "return {status: 'filed', message: 'public'};",+ });+ configure(['@test/fail', '@test/public']);++ const result = await gapReport('General', {+ ...reportOptions,+ cwd: projectDir,+ });++ expect(result.data.status).toBe('partial');+ expect(result.data.deliveries.map(d => d.status)).toEqual([+ 'failed',+ 'consent_required',+ ]);+ });++ it('all failed → status failed', async () => {+ addIntegration({+ name: '@test/fail1',+ audience: 'internal',+ handleBody: "throw new Error('boom');",+ });+ configure(['@test/fail1']);++ const result = await gapReport('General', {+ ...reportOptions,+ cwd: projectDir,+ });+ expect(result.data.status).toBe('failed');+ });++ it('report event shape is plain camelCase with no internal context', async () => {+ addIntegration({+ name: '@test/inspector',+ audience: 'internal',+ handleBody: `+ const keys = Object.keys(report).sort();+ const targetKeys = Object.keys(report.target).sort();+ return {+ status: 'filed',+ message: JSON.stringify({+ keys,+ targetKeys,+ source: report.source,+ sv: report.schemaVersion,+ }),+ };+ `,+ });+ configure(['@test/inspector']);+ vi.stubEnv('ASTRYX_AGENT_ID', 'secret-agent');++ const result = await gapReport('Button', {+ ...reportOptions,+ cwd: projectDir,+ });++ const info = JSON.parse(result.data.deliveries[0].message);+ expect(info.sv).toBe(1);+ expect(info.source).toBe('ai');+ expect(info.keys).toEqual([+ 'category',+ 'categoryLabel',+ 'component',+ 'detail',+ 'intention',+ 'schemaVersion',+ 'source',+ 'target',+ 'timestamp',+ ]);+ expect(info.targetKeys).toEqual(['issuesUrl', 'package', 'version']);+ // No handler-private context fields or raw agent identifiers+ expect(result.data.deliveries[0].message).not.toContain('debug');+ expect(result.data.deliveries[0].message).not.toContain('context');+ expect(result.data.deliveries[0].message).not.toContain('secret-agent');+ });++ it('receipt type is gap-report.file for the aggregate response', async () => {+ addIntegration({+ name: '@test/basic',+ audience: 'internal',+ handleBody: "return {status: 'filed', message: 'ok'};",+ });+ configure(['@test/basic']);++ const result = await gapReport('General', {+ ...reportOptions,+ cwd: projectDir,+ });++ expect(result.type).toBe('gap-report.file');+ expect(result.data).toHaveProperty('deliveries');+ expect(result.data).toHaveProperty('filedCount');+ expect(result.data).toHaveProperty('routedOnlyCount');+ expect(result.data).toHaveProperty('status');+ expect(result.data).toHaveProperty('package');+ expect(result.data).toHaveProperty('issuesUrl');+ });+});++describe('gapReport strict receipt validation', () => {+ it('rejects receipt with unknown fields', async () => {+ addIntegration({+ name: '@test/extra-fields',+ audience: 'internal',+ handleBody: "return {status: 'filed', message: 'ok', extra: true};",+ });+ configure(['@test/extra-fields']);++ const result = await gapReport('General', {+ ...reportOptions,+ cwd: projectDir,+ });++ expect(result.data.deliveries[0].status).toBe('failed');+ });++ it('rejects routed_only without url', async () => {+ addIntegration({+ name: '@test/no-url',+ audience: 'internal',+ handleBody: "return {status: 'routed_only', message: 'but no url'};",+ });+ configure(['@test/no-url']);++ const result = await gapReport('General', {+ ...reportOptions,+ cwd: projectDir,+ });++ expect(result.data.deliveries[0].status).toBe('failed');+ });++ it('accepts valid routed_only with url', async () => {+ addIntegration({+ name: '@test/routed',+ audience: 'internal',+ handleBody:+ "return {status: 'routed_only', url: 'https://example.com/issue/1'};",+ });+ configure(['@test/routed']);++ const result = await gapReport('General', {+ ...reportOptions,+ cwd: projectDir,+ });++ expect(result.data.deliveries[0].status).toBe('routed_only');+ expect(result.data.routedOnlyCount).toBe(1);+ });++ it('accepts skipped without url or message', async () => {+ addIntegration({+ name: '@test/skipper',+ audience: 'internal',+ handleBody: "return {status: 'skipped'};",+ });+ configure(['@test/skipper']);++ const result = await gapReport('General', {+ ...reportOptions,+ cwd: projectDir,+ });++ expect(result.data.deliveries[0].status).toBe('skipped');+ expect(result.data.status).toBe('skipped');+ });+});diff --git a/packages/cli/api/gap-report/gap-report.type.mjs b/packages/cli/api/gap-report/gap-report.type.mjsnew file mode 100644index 0000000000..abca0b980c--- /dev/null+++ b/packages/cli/api/gap-report/gap-report.type.mjs@@ -0,0 +1,69 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * Colocated public types for `gapReport()` and `astryx gap-report`.+ */++/**+ * @typedef {'missing_component'|'missing_variant'|'layout_gap'|'styling_gap'|'a11y_gap'|'api_friction'|'docs_gap'|'other'} GapReportCategory+ */++/**+ * @typedef {object} GapReportCategoryEntry+ * @property {GapReportCategory} value+ * @property {string} label+ */++/**+ * @typedef {object} GapReportOptions+ * @property {string} [cwd] Project directory used for config and owner routing.+ * @property {GapReportCategory} [category] Fixed report category.+ * @property {string} [reason] What capability was missing or difficult.+ * @property {string} [detail] Optional additional context.+ * @property {string} [package] Explicit owner package for ambiguous routes.+ * @property {boolean} [confirmPublic] Explicit consent for public handlers or GitHub issue creation.+ * @property {boolean} [listCategories] Return the category vocabulary without routing or writing.+ */++/**+ * @typedef {object} GapReportCategoriesResponse+ * @property {'gap-report.categories'} type+ * @property {GapReportCategoryEntry[]} data+ */++/**+ * @typedef {'filed'|'partial'|'failed'|'routed_only'|'consent_required'|'skipped'} GapReportAggregateStatus+ */++/**+ * @typedef {'filed'|'routed_only'|'skipped'|'failed'|'consent_required'} GapReportDeliveryStatus+ */++/**+ * One handler's outcome in the fan-out.+ * @typedef {object} GapReportDelivery+ * @property {'project'|'integration'|'fallback'} handlerType+ * @property {string} handler Project, integration package, or fallback name.+ * @property {'internal'|'public'|null} audience+ * @property {GapReportDeliveryStatus} status+ * @property {string|null} url+ * @property {string|null} message+ */++/**+ * @typedef {object} GapReportReceipt+ * @property {GapReportAggregateStatus} status Overall outcome.+ * @property {string} package Selected owner package.+ * @property {string|null} issuesUrl Selected issue destination, when configured.+ * @property {GapReportDelivery[]} deliveries Ordered handler outcomes.+ * @property {number} filedCount Count of handlers that filed the report.+ * @property {number} routedOnlyCount Count of handlers that routed only.+ */++/**+ * @typedef {object} GapReportReceiptResponse+ * @property {'gap-report.file'} type+ * @property {GapReportReceipt} data+ */++export {};diff --git a/packages/cli/api/index.mjs b/packages/cli/api/index.mjsindex 89f9cd17a9..5034f1f7f6 100644--- a/packages/cli/api/index.mjs+++ b/packages/cli/api/index.mjs@@ -39,6 +39,7 @@ export {hook} from './hook/hook.mjs';export {search} from './search/search.mjs';export {build} from './build/build.mjs';export {swizzle} from './swizzle/swizzle.mjs';+export {gapReport} from './gap-report/gap-report.mjs';export {upgrade} from './upgrade/upgrade.mjs';export {init} from './init/init.mjs';export {doctor} from './doctor/doctor.mjs';@@ -85,6 +86,7 @@ export * from './hook/hook.type.mjs';export * from './search/search.type.mjs';export * from './build/build.type.mjs';export * from './swizzle/swizzle.type.mjs';+export * from './gap-report/gap-report.type.mjs';export * from './upgrade/upgrade.type.mjs';export * from './init/init.type.mjs';export * from './doctor/doctor.type.mjs';diff --git a/packages/cli/api/json/index.ts b/packages/cli/api/json/index.tsindex 1bdb7e173d..f3d8534383 100644--- a/packages/cli/api/json/index.ts+++ b/packages/cli/api/json/index.ts@@ -22,6 +22,7 @@ export type * from '../hook/hook.type.mjs';export type * from '../search/search.type.mjs';export type * from '../build/build.type.mjs';export type * from '../swizzle/swizzle.type.mjs';+export type * from '../gap-report/gap-report.type.mjs';export type * from '../upgrade/upgrade.type.mjs';export type * from '../init/init.type.mjs';export type * from '../doctor/doctor.type.mjs';diff --git a/packages/cli/assets/docs/cli-integrations.doc.mjs b/packages/cli/assets/docs/cli-integrations.doc.mjsindex 6071bb2d5d..4a7b550ab7 100644--- a/packages/cli/assets/docs/cli-integrations.doc.mjs+++ b/packages/cli/assets/docs/cli-integrations.doc.mjs@@ -301,6 +301,46 @@ export const docs = {},],},+ {+ title: 'Gap report handler',+ category: 'guide',+ content: [+ {+ type: 'prose',+ text: 'An integration can handle `astryx gap-report` events by exporting a `gapReport` handler from its integration module. The handler is a plain object with an `audience` and a `handle` function — not an executable command. Export it as a named export; do not put it in the default manifest. Older CLI versions ignore the named export and continue loading every manifest contribution they understand.',+ },+ {+ type: 'code',+ lang: 'typescript',+ code: "// astryx.integration.ts\nimport type {GapReportHandler} from '@astryxdesign/cli/authoring';\n\nexport const gapReport: GapReportHandler = {\n audience: 'public',\n async handle(event, {signal}) {\n // event is a normalized GapReport with camelCase fields\n // and event.target.{package, version, issuesUrl}\n const url = await createIssue(event, {signal});\n return { status: 'filed', url };\n },\n};\n\nexport default {\n components: './components',\n issuesUrl: 'https://github.com/acme/widgets/issues',\n};",+ },+ {+ type: 'prose',+ text: 'The same handler type is available as a `gapReport` field in `astryx.config` for project-level handling. When both exist, the project handler runs first, then each integration handler in config order. Every handler runs — none overrides another.',+ },+ {+ type: 'code',+ lang: 'typescript',+ code: "// astryx.config.ts\nimport type {AstryxConfig, GapReportHandler} from '@astryxdesign/cli/authoring';\n\nconst projectHandler: GapReportHandler = {\n audience: 'internal',\n async handle(event) {\n await postToTracker(event);\n return { status: 'filed', message: 'Posted to internal tracker' };\n },\n};\n\nexport default {\n integrations: ['@acme/astryx-widgets'],\n gapReport: projectHandler,\n} satisfies AstryxConfig;",+ },+ {+ type: 'prose',+ text: "Each handler receives its own deep copy of the `GapReport` event (via `structuredClone`) plus an `AbortSignal` that fires at the 30-second timeout. Each handler runs in its own worker. A throw, timeout, `stdout` write, `process.exit`, or `process.exitCode` change is contained there and produces a failed delivery for that handler only. On timeout the CLI aborts the signal, terminates the worker before starting the next handler, and preserves its own output and exit code. Handler `stdout` is forwarded to the CLI's `stderr` so it cannot corrupt a JSON envelope.",+ },+ {+ type: 'prose',+ text: "A handler MUST return a `GapReportHandlerReceipt` with a `status` of `'filed'`, `'routed_only'`, or `'skipped'`, plus optional `url` and `message` strings. The aggregate response includes an ordered `deliveries` array. Each entry names its project, integration package, or fallback and includes the declared audience, final status, URL, and message.",+ },+ {+ type: 'prose',+ text: "Use `audience: 'public'` for any public or third-party destination. The CLI will not invoke a public handler unless the caller explicitly confirms the public write. `audience: 'internal'` requires no additional confirmation. In a fan-out with mixed audiences, internal handlers run unconditionally while public handlers are consent-gated independently.",+ },+ {+ type: 'prose',+ text: 'When the effective handler set is empty (no project handler, no integration handlers), and the target has a GitHub `issuesUrl`, the CLI falls back to `gh issue create` after explicit confirmation. Any other `issuesUrl` scheme produces a `routed_only` receipt. The fallback is suppressed entirely when at least one handler is configured.',+ },+ ],+ },{title: 'How It Works',category: 'guide',@@ -309,6 +349,10 @@ export const docs = {type: 'prose',text: "Every CLI command loads the consumer's `astryx.config`, resolves each listed integration's manifest from `node_modules`, and discovers its contributions. Each file is parsed at the load boundary through `@astryxdesign/cli/authoring` — when the CLI loads it, not when you author it. A field of the wrong type fails there. A field this CLI does not know is ignored with a warning naming it, so a manifest written against a newer CLI still contributes everything this one understands. There are no factories; you write a plain object and stamp its `type`.",},+ {+ type: 'prose',+ text: 'Runtime integration features — `debug` and `gapReport` — use named exports from the integration module rather than fields in the default manifest. The CLI discovers them alongside the manifest but loads them through the composition rules in `spec:AST-031`: every configured handler runs additively, each in isolation with its own copy of the event.',+ },{type: 'prose',text: 'Discovery is resilient. A broken or misconfigured integration is skipped with a single non-blocking warning on stderr instead of crashing the CLI, and it never corrupts a `--json` stdout envelope. Everyday commands keep working with the remaining valid contributions.',diff --git a/packages/cli/authoring/config/config.doc.mjs b/packages/cli/authoring/config/config.doc.mjsindex b8b2ef5422..a8b9742552 100644--- a/packages/cli/authoring/config/config.doc.mjs+++ b/packages/cli/authoring/config/config.doc.mjs@@ -15,7 +15,7 @@ export const doc = {description:'The optional astryx.config.* file at your project root. Declares which ' +'integrations to load, where to route issue links, post-codemod hooks, local ' +- 'debug-log settings, and experimental layout components. All fields are ' ++ 'debug-log and gap-report handlers, and experimental layout components. All ' +'optional; {} is valid.',appliesTo: 'astryx.config.{ts,mjs,js}',fields: [@@ -52,6 +52,14 @@ export const doc = {example:"event => appendFileSync('runs.ndjson', JSON.stringify(event) + '\\n')",},+ {+ name: 'gapReport',+ type: 'GapReportHandler',+ description:+ 'Handle explicit gap reports in addition to every loaded integration handler. The project handler runs first. Public handlers require caller consent; internal handlers always run.',+ example:+ "{ audience: 'internal', async handle(report, {signal}) { return sendGap(report, {signal}); } }",+ },{name: 'experimental',type: '{ xle?: { components?: Record<string, XleComponent> } }',diff --git a/packages/cli/authoring/config/parse.mjs b/packages/cli/authoring/config/parse.mjsindex b0a9495dc6..e871968ade 100644--- a/packages/cli/authoring/config/parse.mjs+++ b/packages/cli/authoring/config/parse.mjs@@ -11,16 +11,20 @@import {z} from 'zod';import {formatZodError} from '../_shared/errors.mjs';+import {parseGapReportHandler} from '../gap-report/parse.mjs';/** @typedef {import('./type').AstryxConfig} AstryxConfig *//** @typedef {import('./type').PostCodemodHook} PostCodemodHook *//** @typedef {import('./type').XleComponent} XleComponent *//** @typedef {import('./type').DebugConfig} DebugConfig *//** @typedef {import('../debug/type').DebugEventHandler} DebugEventHandler */+/** @typedef {import('../gap-report/type').GapReportHandler} GapReportHandler */// Typed `z.custom` so `z.infer` reproduces the real function type (not `unknown`).const buildCommand = /** @type {z.ZodType<PostCodemodHook['buildCommand']>} */ (- z.custom(value => typeof value === 'function', {message: 'Expected a function'})+ z.custom(value => typeof value === 'function', {+ message: 'Expected a function',+ }));const postCodemodHookSchema = z@@ -41,7 +45,25 @@ const xleComponentSchema = z// Typed `z.custom` so `z.infer` reproduces the real handler type (not// `unknown`), the same way the post-codemod hook above keeps its signature.const debugSchema = /** @type {z.ZodType<DebugEventHandler>} */ (- z.custom(value => typeof value === 'function', {message: 'Expected a function'})+ z.custom(value => typeof value === 'function', {+ message: 'Expected a function',+ })+);++// Reuse the shared load-boundary parser so project and integration handlers+// accept exactly one shape. Typed z.custom preserves the public function type.+const gapReportHandlerSchema = /** @type {z.ZodType<GapReportHandler>} */ (+ z.custom(+ value => {+ try {+ parseGapReportHandler(value);+ return true;+ } catch {+ return false;+ }+ },+ {message: 'Expected a GapReportHandler {audience, handle}'},+ ));const configSchema = z@@ -53,10 +75,13 @@ const configSchema = z.strict().optional(),debug: debugSchema.optional(),+ gapReport: gapReportHandlerSchema.optional(),experimental: z.object({xle: z- .object({components: z.record(z.string(), xleComponentSchema).optional()})+ .object({+ components: z.record(z.string(), xleComponentSchema).optional(),+ }).strict().optional(),})diff --git a/packages/cli/authoring/config/parse.test.mjs b/packages/cli/authoring/config/parse.test.mjsindex 45726a3294..54f6969d91 100644--- a/packages/cli/authoring/config/parse.test.mjs+++ b/packages/cli/authoring/config/parse.test.mjs@@ -56,6 +56,28 @@ describe('parseConfig (load boundary)', () => {expect(msg).toContain('packages');});+ it('accepts the project gap-report handler shape', () => {+ const handle = () => ({status: 'filed', message: 'ok'});+ expect(+ parseConfig({gapReport: {audience: 'internal', handle}}).gapReport,+ ).toEqual({audience: 'internal', handle});+ });++ it('rejects obsolete or extended gap-report handler shapes', () => {+ expect(reason({gapReport: {command: './report.mjs'}})).toContain(+ 'gapReport',+ );+ expect(+ reason({+ gapReport: {+ audience: 'internal',+ handle: () => ({status: 'skipped'}),+ extra: true,+ },+ }),+ ).toContain('gapReport');+ });+it('rejects a non-array integrations field', () => {expect(reason({integrations: '@acme/widgets'})).toContain('expected array');expect(reason({integrations: [1]})).toContain('integrations.0');@@ -72,9 +94,9 @@ describe('parseConfig (load boundary)', () => {});it('rejects a non-function postCodemod.buildCommand', () => {- expect(reason({hooks: {postCodemod: [{buildCommand: 'notAFn'}]}})).toContain(- 'buildCommand',- );+ expect(+ reason({hooks: {postCodemod: [{buildCommand: 'notAFn'}]}}),+ ).toContain('buildCommand');});it('rejects unknown nested keys inside experimental.xle.components', () => {diff --git a/packages/cli/authoring/config/type.ts b/packages/cli/authoring/config/type.tsindex ba3076f716..934b66c635 100644--- a/packages/cli/authoring/config/type.ts+++ b/packages/cli/authoring/config/type.ts@@ -10,6 +10,7 @@*/import type {DebugEventHandler} from '../debug/type';+import type {GapReportHandler} from '../gap-report/type';/*** A command to run as part of a post-codemod hook. Returned by a hook's@@ -81,6 +82,8 @@ export interface AstryxConfig {};/** Record every astryx command run in this project. See {@link DebugConfig}. */debug?: DebugConfig;+ /** Route gap reports through a project-owned handler. See {@link GapReportHandler}. */+ gapReport?: GapReportHandler;/*** EXPERIMENTAL — shape may change and is not part of the stable config* contract. Provisional home for features still being proven out.diff --git a/packages/cli/authoring/gap-report/parse.mjs b/packages/cli/authoring/gap-report/parse.mjsnew file mode 100644index 0000000000..a29863782c--- /dev/null+++ b/packages/cli/authoring/gap-report/parse.mjs@@ -0,0 +1,121 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Gap-report handler parser — the load-boundary validator for the+ * `gapReport` named export in integration manifests and the `gapReport` field+ * in `astryx.config`.+ *+ * Zod is sealed in here: the schema is module-private, never exported, and+ * never appears in a public type. A compile-time drift-lock asserts it still+ * infers exactly the published interface.+ */++import {z} from 'zod';+import {formatZodError} from '../_shared/errors.mjs';++/** @typedef {import('./type').GapReportHandler} GapReportHandler */+/** @typedef {import('./type').GapReportHandlerReceipt} GapReportHandlerReceipt */++// Typed z.custom so z.infer reproduces the real function type, matching the+// pattern used by the debug handler and post-codemod hook parsers.+const handleFn = /** @type {z.ZodType<GapReportHandler['handle']>} */ (+ z.custom(value => typeof value === 'function', {+ message: 'Expected a function',+ })+);++const handlerSchema = z+ .object({+ audience: z.enum(['internal', 'public']),+ handle: handleFn,+ })+ .strict();++/**+ * Compile-time drift-lock: the sealed schema must infer EXACTLY the public+ * {@link GapReportHandler} type. If they drift, `MutuallyAssignable` becomes+ * `false` and `Expect<false>` fails `tsconfig.authoring-contract.json`.+ *+ * @typedef {import('../_shared/contract').Expect<+ * import('../_shared/contract').MutuallyAssignable<z.infer<typeof handlerSchema>, GapReportHandler>+ * >} _GapReportHandlerDriftLock+ */++const receiptSchema = z+ .object({+ status: z.enum(['filed', 'routed_only', 'skipped']),+ url: z.string().optional(),+ message: z.string().optional(),+ })+ .strict();++/**+ * @typedef {import('../_shared/contract').Expect<+ * import('../_shared/contract').MutuallyAssignable<z.infer<typeof receiptSchema>, GapReportHandlerReceipt>+ * >} _GapReportReceiptDriftLock+ */++/**+ * Validate an unknown value as a `GapReportHandler`, or throw a readable error.+ *+ * @param {unknown} input+ * @param {string} [label]+ * @returns {GapReportHandler}+ */+export function parseGapReportHandler(input, label = 'gapReport handler') {+ const result = handlerSchema.safeParse(input);+ if (!result.success) {+ throw new Error(formatZodError(label, result.error));+ }+ return result.data;+}++/**+ * Validate a handler's return value as a strict `GapReportHandlerReceipt`.+ * Returns the validated receipt, or null when invalid.+ *+ * This runs on the HOT path (called per handler per invocation), so it returns+ * null on failure rather than throwing — the caller records a failed delivery.+ *+ * @param {unknown} input+ * @returns {GapReportHandlerReceipt | null}+ */+export function parseGapReportReceipt(input) {+ const result = receiptSchema.safeParse(input);+ if (!result.success) return null;++ const receipt = result.data;+ const url = receipt.url?.trim() || undefined;+ const message = receipt.message?.trim() || undefined;++ // routed_only requires a URL+ if (receipt.status === 'routed_only' && !url) return null;++ // URL must be http(s)+ if (url != null) {+ try {+ const parsed = new URL(url);+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {+ return null;+ }+ } catch {+ return null;+ }+ }++ // message length cap+ if (message != null && Array.from(message).length > 2000) {+ return null;+ }++ // At least url or message where applicable (filed/routed_only)+ if (receipt.status !== 'skipped' && url == null && message == null) {+ return null;+ }++ return {+ status: receipt.status,+ ...(url == null ? {} : {url}),+ ...(message == null ? {} : {message}),+ };+}diff --git a/packages/cli/authoring/gap-report/parse.test.mjs b/packages/cli/authoring/gap-report/parse.test.mjsnew file mode 100644index 0000000000..7bd75687a9--- /dev/null+++ b/packages/cli/authoring/gap-report/parse.test.mjs@@ -0,0 +1,172 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, expect, it} from 'vitest';+import {parseGapReportHandler, parseGapReportReceipt} from './parse.mjs';++describe('parseGapReportHandler', () => {+ it('accepts a valid handler with audience and handle', () => {+ const handler = parseGapReportHandler({+ audience: 'internal',+ handle: () => ({status: 'filed', message: 'ok'}),+ });+ expect(handler.audience).toBe('internal');+ expect(typeof handler.handle).toBe('function');+ });++ it('accepts public audience', () => {+ const handler = parseGapReportHandler({+ audience: 'public',+ handle: () => ({status: 'skipped'}),+ });+ expect(handler.audience).toBe('public');+ });++ it('rejects missing audience', () => {+ expect(() => parseGapReportHandler({handle: () => ({})})).toThrow();+ });++ it('rejects invalid audience value', () => {+ expect(() =>+ parseGapReportHandler({audience: 'secret', handle: () => ({})}),+ ).toThrow();+ });++ it('rejects missing handle function', () => {+ expect(() => parseGapReportHandler({audience: 'internal'})).toThrow();+ });++ it('rejects handle that is not a function', () => {+ expect(() =>+ parseGapReportHandler({audience: 'internal', handle: './writer.mjs'}),+ ).toThrow();+ });++ it('rejects unknown fields (strict)', () => {+ expect(() =>+ parseGapReportHandler({+ audience: 'internal',+ handle: () => ({}),+ command: './writer.mjs',+ }),+ ).toThrow();+ });++ it('rejects null input', () => {+ expect(() => parseGapReportHandler(null)).toThrow();+ });++ it('rejects array input', () => {+ expect(() => parseGapReportHandler([])).toThrow();+ });++ it('rejects bare function (not a plain object)', () => {+ const fn = () => ({status: 'filed'});+ fn.audience = 'internal';+ fn.handle = fn;+ expect(() => parseGapReportHandler(fn)).toThrow();+ });+});++describe('parseGapReportReceipt', () => {+ it('accepts valid filed receipt with message', () => {+ const receipt = parseGapReportReceipt({+ status: 'filed',+ message: 'Report created',+ });+ expect(receipt).toEqual({status: 'filed', message: 'Report created'});+ });++ it('accepts valid filed receipt with url', () => {+ const receipt = parseGapReportReceipt({+ status: 'filed',+ url: 'https://example.com/issue/1',+ });+ expect(receipt).toEqual({+ status: 'filed',+ url: 'https://example.com/issue/1',+ });+ });++ it('accepts valid filed receipt with both url and message', () => {+ const receipt = parseGapReportReceipt({+ status: 'filed',+ url: 'https://example.com/issue/1',+ message: 'Created issue #1',+ });+ expect(receipt).not.toBeNull();+ expect(receipt.status).toBe('filed');+ });++ it('accepts valid routed_only with url', () => {+ const receipt = parseGapReportReceipt({+ status: 'routed_only',+ url: 'https://example.com/issues',+ });+ expect(receipt).toEqual({+ status: 'routed_only',+ url: 'https://example.com/issues',+ });+ });++ it('rejects routed_only without url', () => {+ expect(+ parseGapReportReceipt({status: 'routed_only', message: 'no url'}),+ ).toBeNull();+ });++ it('accepts valid skipped without url or message', () => {+ const receipt = parseGapReportReceipt({status: 'skipped'});+ expect(receipt).toEqual({status: 'skipped'});+ });++ it('rejects filed without url or message', () => {+ expect(parseGapReportReceipt({status: 'filed'})).toBeNull();+ });++ it('rejects filed with empty message', () => {+ expect(parseGapReportReceipt({status: 'filed', message: ' '})).toBeNull();+ });++ it('rejects unknown status', () => {+ expect(+ parseGapReportReceipt({status: 'pending', message: 'ok'}),+ ).toBeNull();+ });++ it('rejects unknown fields', () => {+ expect(+ parseGapReportReceipt({status: 'filed', message: 'ok', extra: true}),+ ).toBeNull();+ });++ it('rejects non-http url', () => {+ expect(+ parseGapReportReceipt({status: 'filed', url: 'ftp://example.com'}),+ ).toBeNull();+ });++ it('rejects message over 2000 characters', () => {+ expect(+ parseGapReportReceipt({+ status: 'filed',+ message: 'x'.repeat(2001),+ }),+ ).toBeNull();+ });++ it('accepts message of exactly 2000 characters', () => {+ const receipt = parseGapReportReceipt({+ status: 'filed',+ message: 'x'.repeat(2000),+ });+ expect(receipt).not.toBeNull();+ });++ it('rejects null input', () => {+ expect(parseGapReportReceipt(null)).toBeNull();+ });++ it('rejects string input', () => {+ expect(parseGapReportReceipt('filed')).toBeNull();+ });+});diff --git a/packages/cli/authoring/gap-report/type.ts b/packages/cli/authoring/gap-report/type.tsnew file mode 100644index 0000000000..cfd23c538f--- /dev/null+++ b/packages/cli/authoring/gap-report/type.ts@@ -0,0 +1,107 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * Public type surface for gap-report handlers.+ *+ * A handler receives a normalized gap report and routes it to a destination.+ * Project config may define one (`gapReport` in `astryx.config`); every loaded+ * integration may export one as a `gapReport` NAMED export. The CLI composes+ * them additively: project handler first, then each integration handler in+ * config order. Every handler receives a `structuredClone` of the same+ * normalized report.+ *+ * This module is the shared authoring surface for both config and integration+ * gap-report handlers.+ */++import type {DebugInvocationSource} from '../debug/type';++/** Supported gap-report categories. */+export type GapReportCategory =+ | 'missing_component'+ | 'missing_variant'+ | 'layout_gap'+ | 'styling_gap'+ | 'a11y_gap'+ | 'api_friction'+ | 'docs_gap'+ | 'other';++/**+ * The normalized report event handed to each handler. Plain camelCase,+ * with no handler-private context.+ */+export interface GapReport {+ schemaVersion: 1;+ component: string;+ category: GapReportCategory;+ categoryLabel: string;+ intention: string;+ detail?: string;+ source: DebugInvocationSource;+ timestamp: string;+ target: GapReportTarget;+}++/** The package a gap report describes. */+export interface GapReportTarget {+ package: string;+ version: string | null;+ issuesUrl: string | null;+}++/**+ * What a handler returns. Strict: unknown fields are invalid, and an invalid+ * return is recorded as a failed delivery.+ *+ * - `filed` — the handler created or queued the report.+ * - `routed_only` — the handler pointed at a destination but did not create+ * the report itself; `url` is REQUIRED.+ * - `skipped` — the handler chose not to act (e.g. deduplication).+ *+ * At least `url` or `message` must be present where applicable (filed or+ * routed_only).+ */+export interface GapReportHandlerReceipt {+ status: 'filed' | 'routed_only' | 'skipped';+ /** HTTP(S) URL. Required when status is `routed_only`. */+ url?: string;+ /** Human-readable message, at most 2000 characters. */+ message?: string;+}++/** Context for one handler invocation. */+export interface GapReportHandlerContext {+ /** Aborted when the handler exceeds its 30-second budget. */+ readonly signal: AbortSignal;+}++/**+ * A handler that receives a normalized gap report. Use a plain object, not a+ * bare function or callable-with-properties.+ *+ * ```+ * export const gapReport = {+ * audience: 'public',+ * handle: async (report) => ({status: 'filed', url: '...'}),+ * };+ * ```+ *+ * The handler is called with `structuredClone(report)`, so mutations are+ * harmless. It may be sync or async; async handlers are awaited with a 30 s+ * timeout. A throw, timeout, or `process.exit` attempt becomes a failed+ * delivery — later handlers still run. Handler stdout is redirected to stderr+ * so JSON stdout remains one envelope.+ */+export interface GapReportHandler {+ /** Whether the handler's destination is organization-internal or public. */+ audience: 'internal' | 'public';+ /**+ * Called with a normalized, cloned report and an abort signal. Return a strict+ * receipt. Async handlers are awaited with a 30 s timeout.+ */+ handle: (+ report: GapReport,+ context: GapReportHandlerContext,+ ) => GapReportHandlerReceipt | Promise<GapReportHandlerReceipt>;+}diff --git a/packages/cli/authoring/index.d.ts b/packages/cli/authoring/index.d.tsindex 1f9a5c90c7..23de59b6f0 100644--- a/packages/cli/authoring/index.d.ts+++ b/packages/cli/authoring/index.d.ts@@ -34,6 +34,14 @@ export type {EnumDoc} from './doctypes/types'; // error-codes.doc.mjs (vexport type {AstryxConfig} from './config/type'; // astryx.config.{ts,mjs}export type {DebugEvent} from './debug/type'; // one recorded CLI runexport type {AstryxIntegration} from './integration/type'; // astryx.integration.{ts,mjs}+export type {+ GapReportHandler,+ GapReportHandlerContext,+ GapReport,+ GapReportCategory,+ GapReportTarget,+ GapReportHandlerReceipt,+} from './gap-report/type'; // gap-report handler contractexport type {AstryxCodemod, AstryxConfigCodemod} from './codemod/type'; // codemods/*// ═══════════════════════════════════════════════════════════════════════@@ -51,6 +59,10 @@ export {parseEnum} from './doctypes/enum/parse.mjs';export {parseLegacyDoc} from './doctypes/legacy.mjs';export {parseConfig} from './config/parse.mjs';export {parseIntegration} from './integration/parse.mjs';+export {+ parseGapReportHandler,+ parseGapReportReceipt,+} from './gap-report/parse.mjs';export {parseCodemod} from './codemod/parse.mjs';export {parseDebugEvent} from './debug/parse.mjs';diff --git a/packages/cli/authoring/index.mjs b/packages/cli/authoring/index.mjsindex 5de0107d59..2471979145 100644--- a/packages/cli/authoring/index.mjs+++ b/packages/cli/authoring/index.mjs@@ -16,6 +16,10 @@export {parseConfig} from './config/parse.mjs';export {parseIntegration} from './integration/parse.mjs';+export {+ parseGapReportHandler,+ parseGapReportReceipt,+} from './gap-report/parse.mjs';export {parseCodemod} from './codemod/parse.mjs';export {parseDebugEvent} from './debug/parse.mjs';export {parseDoc} from './doctypes/parse.mjs';diff --git a/packages/cli/authoring/integration/type.ts b/packages/cli/authoring/integration/type.tsindex 6802600a74..35d724a64f 100644--- a/packages/cli/authoring/integration/type.ts+++ b/packages/cli/authoring/integration/type.ts@@ -7,12 +7,10 @@* manifest. Authors write a plain object against {@link AstryxIntegration};* the CLI validates it via `parseIntegration` at the load boundary.*- * The manifest module may also carry a `debug` NAMED export — a- * `DebugEventHandler` that receives every command run in the apps that install- * the integration. It is not a field here on purpose: a CLI released before a- * given field existed rejects it, and a rejected manifest contributes nothing- * at all, while a named export is simply not read. See the `cli-integrations`- * doc topic.+ * The manifest module may also carry `debug` and `gapReport` NAMED exports.+ * They are not fields here on purpose: a CLI released before a given manifest+ * field existed could reject it and lose every contribution, while an unknown+ * named export is simply not read. See the `cli-integrations` doc topic.*/export interface AstryxIntegration {/** Relative path to the components/docs root (resolved to absolute). */@@ -36,3 +34,19 @@ export interface AstryxIntegration {/** Where to file issues/feedback for this integration. */issuesUrl?: string;}++/**+ * A handler that receives a normalized gap report. Used as a named export+ * from integration manifests and as a config field.+ *+ * Re-exported from `@astryxdesign/cli/authoring`; see+ * `authoring/gap-report/type.ts` for the full contract.+ */+export type {+ GapReportHandler,+ GapReportHandlerContext,+ GapReport,+ GapReportCategory,+ GapReportTarget,+ GapReportHandlerReceipt,+} from '../gap-report/type';diff --git a/packages/cli/clients/cli/commands/gap-report.doc.mjs b/packages/cli/clients/cli/commands/gap-report.doc.mjsnew file mode 100644index 0000000000..2cb9ce86ff--- /dev/null+++ b/packages/cli/clients/cli/commands/gap-report.doc.mjs@@ -0,0 +1,73 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file CommandDoc for `astryx gap-report`.+ * @position packages/cli/clients/cli/commands — command documentation+ */++/** @type {import('@astryxdesign/cli/authoring').CommandDoc} */+export const doc = {+ type: 'command',+ name: 'gap-report',+ displayName: 'astryx gap-report',+ namespace: 'cli',+ summary: 'Route a design-system gap to its owning package',+ description:+ 'Reports a missing component, variant, layout, styling, accessibility, API, or documentation capability. The command selects an explicit package first, then a unique component owner, then Core. The report fans out to every effective handler: project config first, then each loaded integration in config order. Public handlers require --confirm-public per handler; internal handlers always run. A handler failure is isolated and does not prevent later handlers.',+ fn: 'gapReport',+ args: [{name: 'component', param: 'component', required: false}],+ options: [+ {+ flag: '--category <category>',+ param: 'options.category',+ description: 'Gap category (run --list-categories for values)',+ },+ {+ flag: '--reason <reason>',+ param: 'options.reason',+ description: 'What capability was missing or difficult',+ },+ {+ flag: '--additional-context <text>',+ param: 'options.detail',+ description: 'Optional additional context',+ },+ {+ flag: '--package <pkg>',+ param: 'options.package',+ description: 'Route to a specific loaded package',+ },+ {+ flag: '--confirm-public',+ param: 'options.confirmPublic',+ description: 'Consent to public handlers or GitHub issue creation',+ },+ {+ flag: '--list-categories',+ param: 'options.listCategories',+ description: 'List valid report categories without filing',+ },+ ],+ examples: [+ {label: 'List categories', cli: 'astryx gap-report --list-categories'},+ {+ label: 'Route an agent report',+ cli: "astryx gap-report Button --category missing_variant --reason 'Need a compact size'",+ },+ {+ label: 'Confirm public filing',+ cli: "astryx gap-report Button --category docs_gap --reason 'Missing keyboard example' --confirm-public",+ },+ ],+ exitCodes: [+ {+ code: 0,+ when: 'filed, routed-only, confirmation required, skipped, or categories listed',+ },+ {+ code: 1,+ when: 'failed or partial delivery, invalid input, or ambiguous routing',+ },+ ],+ related: ['component', 'discover', 'swizzle'],+};diff --git a/packages/cli/clients/cli/commands/gap-report.mjs b/packages/cli/clients/cli/commands/gap-report.mjsnew file mode 100644index 0000000000..4c57c72d70--- /dev/null+++ b/packages/cli/clients/cli/commands/gap-report.mjs@@ -0,0 +1,114 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `astryx gap-report` CLI adapter.+ */++import {gapReport as gapReportApi} from '../../../api/gap-report/gap-report.mjs';+import {NO_RESULT_SET, resultSet} from '../../../foundation/debug/index.mjs';+import {jsonOut} from '../../../foundation/response/json.mjs';+import {emit, record, records, section} from '../formatters/index.mjs';+import {cliError} from '../lib/cli-error.mjs';+import {defineCommand} from '../lib/define-command.mjs';+import {doc as gapReportCommand} from './gap-report.doc.mjs';+import {doc as gapReportFn} from '../../../api/gap-report/gap-report.doc.mjs';++/** @param {import('commander').Command} program */+export function registerGapReport(program) {+ defineCommand(program, gapReportCommand, {+ fn: gapReportFn,+ action: async (+ /** @type {string|undefined} */ component,+ /** @type {{category?: string, reason?: string, additionalContext?: string, package?: string, confirmPublic?: boolean, listCategories?: boolean}} */ options,+ ) => {+ /** @type {Awaited<ReturnType<typeof gapReportApi>>} */+ let result;+ try {+ result = await gapReportApi(component, {+ cwd: process.cwd(),+ category:+ /** @type {import('../../../api/gap-report/gap-report.type.mjs').GapReportCategory|undefined} */ (+ options.category+ ),+ reason: options.reason,+ detail: options.additionalContext,+ package: options.package,+ confirmPublic: options.confirmPublic,+ listCategories: options.listCategories,+ });+ } catch (error) {+ const err =+ /** @type {import('../../../api/error.mjs').AstryxError} */ (error);+ return cliError(err.message, {+ suggestions: err.suggestions,+ code: err.code,+ });+ }++ const answered =+ result.type === 'gap-report.categories'+ ? resultSet({count: result.data.length, resultKind: 'command'})+ : NO_RESULT_SET;++ // CLI exits nonzero for failed/partial but still emits the receipt+ const isFailure =+ result.type === 'gap-report.file' &&+ (result.data.status === 'failed' || result.data.status === 'partial');++ if (program.opts().json) {+ jsonOut(result);+ if (isFailure) process.exitCode = 1;+ return answered;+ }++ if (result.type === 'gap-report.categories') {+ emit(+ section('Gap report categories'),+ records(result.data, {fields: ['value', 'label']}),+ );+ return answered;+ }++ const heading =+ result.data.status === 'filed'+ ? 'Gap report filed'+ : result.data.status === 'partial'+ ? 'Gap report partially filed'+ : result.data.status === 'failed'+ ? 'Gap report failed'+ : 'Gap report route';++ emit(+ section(heading),+ record(result.data, {+ fields: [+ 'status',+ 'package',+ 'issuesUrl',+ 'filedCount',+ 'routedOnlyCount',+ ],+ }),+ );++ if (result.data.deliveries.length > 0) {+ emit(+ section('Deliveries'),+ records(result.data.deliveries, {+ fields: [+ 'handlerType',+ 'handler',+ 'audience',+ 'status',+ 'url',+ 'message',+ ],+ }),+ );+ }++ if (isFailure) process.exitCode = 1;+ return answered;+ },+ });+}diff --git a/packages/cli/clients/cli/commands/gap-report.test.mjs b/packages/cli/clients/cli/commands/gap-report.test.mjsnew file mode 100644index 0000000000..a23a0ace9b--- /dev/null+++ b/packages/cli/clients/cli/commands/gap-report.test.mjs@@ -0,0 +1,198 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {describe, expect, it} from 'vitest';+import {gapReport} from '../../../api/gap-report/gap-report.mjs';+import {runCli} from '../../../test-utils/run-cli.mjs';++describe('gap-report CLI and API parity', () => {+ it('returns the same category catalog', async () => {+ const api = await gapReport(undefined, {listCategories: true});+ const cli = await runCli(['gap-report', '--list-categories', '--json']);++ expect(cli.status).toBe(0);+ const envelope = JSON.parse(cli.stdout);+ expect({type: envelope.type, data: envelope.data}).toEqual(api);+ });++ it('keeps the global --detail option separate from gap-report context', async () => {+ for (const args of [+ ['--detail', 'compact', 'gap-report', '--list-categories', '--json'],+ ['gap-report', '--list-categories', '--detail', 'compact', '--json'],+ ]) {+ const cli = await runCli(args);+ expect(cli.status).toBe(0);+ expect(JSON.parse(cli.stdout)).toMatchObject({+ type: 'gap-report.categories',+ });+ }+ });++ it('maps --additional-context to the API detail field', async () => {+ const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-gap-context-'));+ try {+ fs.writeFileSync(+ path.join(cwd, 'package.json'),+ JSON.stringify({name: 'fixture-app'}),+ );+ fs.writeFileSync(+ path.join(cwd, 'astryx.config.mjs'),+ `export default {+ gapReport: {+ audience: 'internal',+ handle(report) {+ return {status: 'filed', message: report.detail};+ },+ },+};\n`,+ );++ const cli = await runCli(+ [+ 'gap-report',+ 'Button',+ '--category',+ 'docs_gap',+ '--reason',+ 'Need a keyboard example',+ '--additional-context',+ 'The example must show focus order.',+ '--json',+ ],+ {cwd},+ );++ expect(cli.status).toBe(0);+ expect(JSON.parse(cli.stdout)).toMatchObject({+ type: 'gap-report.file',+ data: {+ deliveries: [+ {+ handler: 'project',+ status: 'filed',+ message: 'The example must show focus order.',+ },+ ],+ },+ });+ } finally {+ fs.rmSync(cwd, {recursive: true, force: true});+ }+ });++ it('returns the same consent-required Core receipt without writing', async () => {+ const options = {+ category: 'docs_gap',+ reason: 'Need a keyboard example',+ cwd: process.cwd(),+ };+ const api = await gapReport('Button', options);+ const cli = await runCli([+ 'gap-report',+ 'Button',+ '--category',+ 'docs_gap',+ '--reason',+ 'Need a keyboard example',+ '--json',+ ]);++ expect(cli.status).toBe(0);+ const envelope = JSON.parse(cli.stdout);+ expect({type: envelope.type, data: envelope.data}).toEqual(api);+ expect(envelope.data.status).toBe('consent_required');+ });++ it('keeps the JSON receipt and exits nonzero for a partial fan-out', async () => {+ const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-gap-cli-'));+ try {+ fs.writeFileSync(+ path.join(cwd, 'package.json'),+ JSON.stringify({name: 'fixture-app'}),+ );+ fs.writeFileSync(+ path.join(cwd, 'astryx.config.mjs'),+ `export default {+ integrations: ['@test/receiver'],+ gapReport: {+ audience: 'internal',+ handle() { throw new Error('project failed'); },+ },+};\n`,+ );+ const integrationDir = path.join(+ cwd,+ 'node_modules',+ '@test',+ 'receiver',+ );+ fs.mkdirSync(integrationDir, {recursive: true});+ fs.writeFileSync(+ path.join(integrationDir, 'package.json'),+ JSON.stringify({name: '@test/receiver', version: '1.0.0'}),+ );+ fs.writeFileSync(+ path.join(integrationDir, 'astryx.integration.mjs'),+ `export const gapReport = {+ audience: 'internal',+ handle() { return {status: 'filed', message: 'received'}; },+};+export default {};\n`,+ );++ const cli = await runCli(+ [+ 'gap-report',+ 'Button',+ '--category',+ 'docs_gap',+ '--reason',+ 'Need a keyboard example',+ '--json',+ ],+ {cwd},+ );++ expect(cli.status).toBe(1);+ expect(JSON.parse(cli.stdout)).toMatchObject({+ type: 'gap-report.file',+ data: {+ status: 'partial',+ filedCount: 1,+ deliveries: [+ {handler: 'project', status: 'failed'},+ {handler: '@test/receiver', status: 'filed'},+ ],+ },+ });+ } finally {+ fs.rmSync(cwd, {recursive: true, force: true});+ }+ });++ it('reports missing required fields through the JSON error contract', async () => {+ const cli = await runCli(['gap-report', 'Button', '--json']);+ expect(cli.status).toBe(1);+ expect(JSON.parse(cli.stdout)).toMatchObject({+ code: 'ERR_MISSING_ARGUMENT',+ });+ });++ it('uses the existing unknown-category error code', async () => {+ const cli = await runCli([+ 'gap-report',+ 'Button',+ '--category',+ 'not_real',+ '--reason',+ 'Need something else',+ '--json',+ ]);+ expect(cli.status).toBe(1);+ expect(JSON.parse(cli.stdout)).toMatchObject({+ code: 'ERR_UNKNOWN_CATEGORY',+ });+ });+});diff --git a/packages/cli/clients/cli/index.mjs b/packages/cli/clients/cli/index.mjsindex c1594949c2..f6875a164b 100644--- a/packages/cli/clients/cli/index.mjs+++ b/packages/cli/clients/cli/index.mjs@@ -85,6 +85,7 @@ export const JSON_SUPPORTED = new Set(['search','build','swizzle',+ 'gap-report','template','hook','theme build',@@ -260,6 +261,7 @@ const commands = [{name: 'docs', path: './commands/docs.mjs', register: 'registerDocs'},{name: 'blog', path: './commands/blog.mjs', register: 'registerBlog'},{name: 'swizzle', path: './commands/swizzle.mjs', register: 'registerSwizzle'},+ {name: 'gap-report', path: './commands/gap-report.mjs', register: 'registerGapReport'},// agent-docs folded into init — functions still importable from agent-docs.mjs{name: 'template', path: './commands/template.mjs', register: 'registerTemplate'},{name: 'layout', path: './commands/layout.mjs', register: 'registerLayout'},diff --git a/packages/cli/clients/cli/lib/manifest.mjs b/packages/cli/clients/cli/lib/manifest.mjsindex 3991af94f8..2cc563ceec 100644--- a/packages/cli/clients/cli/lib/manifest.mjs+++ b/packages/cli/clients/cli/lib/manifest.mjs@@ -66,6 +66,7 @@ export const RESPONSE_TYPES = {search: ['search'],build: ['build.help', 'build.kit'],swizzle: ['swizzle.list', 'swizzle.copy'],+ 'gap-report': ['gap-report.categories', 'gap-report.file'],template: ['template.list','template.show',@@ -112,6 +113,10 @@ const EXAMPLES = {],build: ['astryx build', 'astryx build "analytics dashboard" --json'],swizzle: ['astryx swizzle XDSButton'],+ 'gap-report': [+ 'astryx gap-report --list-categories',+ "astryx gap-report Button --category docs_gap --reason 'Missing keyboard example'",+ ],template: ['astryx template --json','astryx template dashboard ./src/app',diff --git a/packages/cli/foundation/integrations/integrations.mjs b/packages/cli/foundation/integrations/integrations.mjsindex 74badd287e..71afc4dbf2 100644--- a/packages/cli/foundation/integrations/integrations.mjs+++ b/packages/cli/foundation/integrations/integrations.mjs@@ -22,6 +22,7 @@ import {unknownIntegrationKeys,} from '../../authoring/integration/schema.mjs';import {importUserModule, findPresentFiles} from '../fs/module-loader.mjs';+import {parseGapReportHandler} from '../../authoring/gap-report/parse.mjs';/*** A fully-resolved, loaded integration. Identity (`name`, `version`) comes from@@ -60,7 +61,10 @@ import {importUserModule, findPresentFiles} from '../fs/module-loader.mjs';* `optionalDependencies`)* @property {import('../../authoring/debug/type').DebugEventHandler} [__debug]* the manifest module's `debug` NAMED export, when it exported a function.- * Not a manifest key — see {@link loadManifest}.+ * @property {import('../../authoring/gap-report/type').GapReportHandler} [__gapReport]+ * validated package-owned handler from the `gapReport` NAMED export.+ * @property {string} [__gapReportError] isolated named-handler validation error.+ * Named exports are not manifest keys — see {@link loadManifest}.*//** Conventional manifest basenames, in load-precedence order. */@@ -81,6 +85,29 @@ export function findManifestPaths(dir) {return findPresentFiles(dir, MANIFEST_BASENAMES);}+/**+ * Parse the optional named gap-report handler without making it part of the+ * default manifest schema. A malformed handler is isolated from every other+ * integration contribution and represented as a failed delivery at fan-out.+ *+ * @param {unknown} value+ * @param {string} label+ * @returns {{handler?: import('../../authoring/gap-report/type').GapReportHandler, error?: string}}+ */+function parseGapReportHandlerExport(value, label) {+ if (value === undefined) return {};+ try {+ return {+ handler: parseGapReportHandler(+ value,+ `${label} named export "gapReport"`,+ ),+ };+ } catch (error) {+ return {error: error instanceof Error ? error.message : String(error)};+ }+}+/*** Load and validate a manifest module's default export, while isolating the* optional `agentDocs` contribution from the manifest's other fields.@@ -91,13 +118,13 @@ export function findManifestPaths(dir) {* The raw object is also inspected before parsing so unknown-key warnings retain* forward compatibility.*- * `debug` comes back separately because it is a named export, not a manifest- * key. A CLI that does not know it simply does not read it.+ * `debug` and `gapReport` come back separately because they are named exports,+ * not manifest keys. A CLI that does not know them simply does not read them.** @param {string} file absolute manifest path* @param {string} [label] used in error messages* @param {{fresh?: boolean}} [options]- * @returns {Promise<{manifest: import('../../authoring/integration/type').AstryxIntegration, unknownKeys: string[], debug?: import('../../authoring/debug/type').DebugEventHandler, agentDocsError?: string}>}+ * @returns {Promise<{manifest: import('../../authoring/integration/type').AstryxIntegration, unknownKeys: string[], debug?: import('../../authoring/debug/type').DebugEventHandler, gapReport?: import('../../authoring/gap-report/type').GapReportHandler, gapReportError?: string, agentDocsError?: string}>}*/export async function loadManifest(file,@@ -107,6 +134,7 @@ export async function loadManifest(const mod = await importUserModule(file, {fresh});const raw = mod?.default;const baseManifest = parseIntegrationBase(raw, label);+ const gapReport = parseGapReportHandlerExport(mod?.gapReport, label);const hasAgentDocs =raw != null &&typeof raw === 'object' &&@@ -139,6 +167,8 @@ export async function loadManifest(mod.debug): undefined,+ gapReport: gapReport.handler,+ gapReportError: gapReport.error,agentDocsError,};}@@ -251,6 +281,10 @@ export async function loadLocalIntegration(packageDir, {fresh = false} = {}) {let unknownKeys;/** @type {import('../../authoring/debug/type').DebugEventHandler | undefined} */let debugHandler;+ /** @type {import('../../authoring/gap-report/type').GapReportHandler | undefined} */+ let gapReportHandler;+ /** @type {string | undefined} */+ let gapReportError;/** @type {string | undefined} */let agentDocsError;try {@@ -258,6 +292,8 @@ export async function loadLocalIntegration(packageDir, {fresh = false} = {}) {manifest,unknownKeys,debug: debugHandler,+ gapReport: gapReportHandler,+ gapReportError,agentDocsError,} = await loadManifest(manifestFile, `Integration ${spec}`, {fresh}));} catch (err) {@@ -295,6 +331,8 @@ export async function loadLocalIntegration(packageDir, {fresh = false} = {}) {__agentDocsError: agentDocsError,__unknownKeys: unknownKeys,__debug: debugHandler,+ __gapReport: gapReportHandler,+ __gapReportError: gapReportError,__spec: spec,__packageDir: packageDir,__packageExports: pkg.exports ?? null,@@ -339,6 +377,10 @@ export async function loadIntegrations(let unknownKeys;/** @type {import('../../authoring/debug/type').DebugEventHandler | undefined} */let debugHandler;+ /** @type {import('../../authoring/gap-report/type').GapReportHandler | undefined} */+ let gapReportHandler;+ /** @type {string | undefined} */+ let gapReportError;/** @type {string | undefined} */let agentDocsError;try {@@ -346,6 +388,8 @@ export async function loadIntegrations(manifest,unknownKeys,debug: debugHandler,+ gapReport: gapReportHandler,+ gapReportError,agentDocsError,} = await loadManifest(manifestFile, `Integration ${spec}`, {fresh}));} catch (err) {@@ -388,6 +432,8 @@ export async function loadIntegrations(__agentDocsError: agentDocsError,__unknownKeys: unknownKeys,__debug: debugHandler,+ __gapReport: gapReportHandler,+ __gapReportError: gapReportError,__spec: spec,__packageDir: packageDir,__packageExports: pkg.exports ?? null,diff --git a/packages/cli/foundation/integrations/integrations.test.mjs b/packages/cli/foundation/integrations/integrations.test.mjsindex 2d35ebe3cd..e430490d2c 100644--- a/packages/cli/foundation/integrations/integrations.test.mjs+++ b/packages/cli/foundation/integrations/integrations.test.mjs@@ -4,13 +4,20 @@ import {afterEach, beforeEach, describe, expect, it} from 'vitest';import * as fs from 'node:fs';import * as path from 'node:path';import {Project} from '../config/project.mjs';-import {loadIntegrations, resolvePackageDir} from './integrations.mjs';+import {+ loadIntegrations,+ loadLocalIntegration,+ resolvePackageDir,+} from './integrations.mjs';import {discover} from '../../api/discover/discover.mjs';let tmpDir;let originalCwd;-function writeManifestPackage(dir, {basename = 'astryx.integration.mjs', body}) {+function writeManifestPackage(+ dir,+ {basename = 'astryx.integration.mjs', body},+) {const pkgDir = path.join(dir, 'node_modules', '@acme', 'widgets');fs.mkdirSync(pkgDir, {recursive: true});fs.writeFileSync(@@ -141,26 +148,32 @@ describe('configured integrations', () => {['wrong outer shape', []],['wrong append shape', {append: 'not-an-array'}],['non-string entry', {append: ['ok', 42]}],- ['too many lines', {append: Array.from({length: 9}, (_, i) => `line ${i}`)}],+ [+ 'too many lines',+ {append: Array.from({length: 9}, (_, i) => `line ${i}`)},+ ],['too many code points', {append: ['😀'.repeat(241)]}],['control character', {append: ['bad\u0001line']}],['managed marker', {append: ['ASTRYX:START']}],- ])('isolates invalid agentDocs (%s) from valid roots', async (_label, agentDocs) => {- const pkgDir = writeManifestPackage(tmpDir, {- body: `export default ${JSON.stringify({- components: './components',- agentDocs,- })};\n`,- });- fs.mkdirSync(path.join(pkgDir, 'components'));-- const [loaded] = await loadIntegrations(['@acme/widgets'], {cwd: tmpDir});-- expect(loaded.__loadError).toBeUndefined();- expect(loaded.components).toBe(path.join(pkgDir, 'components'));- expect(loaded.agentDocs).toBeUndefined();- expect(loaded.__agentDocsError).toMatch(/agentDocs/i);- });+ ])(+ 'isolates invalid agentDocs (%s) from valid roots',+ async (_label, agentDocs) => {+ const pkgDir = writeManifestPackage(tmpDir, {+ body: `export default ${JSON.stringify({+ components: './components',+ agentDocs,+ })};\n`,+ });+ fs.mkdirSync(path.join(pkgDir, 'components'));++ const [loaded] = await loadIntegrations(['@acme/widgets'], {cwd: tmpDir});++ expect(loaded.__loadError).toBeUndefined();+ expect(loaded.components).toBe(path.join(pkgDir, 'components'));+ expect(loaded.agentDocs).toBeUndefined();+ expect(loaded.__agentDocsError).toMatch(/agentDocs/i);+ },+ );it('errors when the package has no conventional root manifest', async () => {const pkgDir = path.join(tmpDir, 'node_modules', '@acme', 'widgets');@@ -169,9 +182,9 @@ describe('configured integrations', () => {path.join(pkgDir, 'package.json'),JSON.stringify({name: '@acme/widgets'}),);- await expect(loadIntegrations(['@acme/widgets'], {cwd: tmpDir})).rejects.toThrow(- /no conventional root manifest/,- );+ await expect(+ loadIntegrations(['@acme/widgets'], {cwd: tmpDir}),+ ).rejects.toThrow(/no conventional root manifest/);});it('errors when the package has multiple root manifests', async () => {@@ -182,15 +195,69 @@ describe('configured integrations', () => {path.join(pkgDir, 'astryx.integration.js'),`module.exports = {};\n`,);- await expect(loadIntegrations(['@acme/widgets'], {cwd: tmpDir})).rejects.toThrow(- /multiple root manifests/,- );+ await expect(+ loadIntegrations(['@acme/widgets'], {cwd: tmpDir}),+ ).rejects.toThrow(/multiple root manifests/);});it('errors when the package is not installed', async () => {- await expect(loadIntegrations(['@acme/missing'], {cwd: tmpDir})).rejects.toThrow(- /Could not find installed integration package/,+ await expect(+ loadIntegrations(['@acme/missing'], {cwd: tmpDir}),+ ).rejects.toThrow(/Could not find installed integration package/);+ });+});++describe('local integration self-resolution', () => {+ it('preserves a valid gapReport named export', async () => {+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({name: '@acme/local', version: '1.0.0'}),+ );+ fs.writeFileSync(+ path.join(tmpDir, 'astryx.integration.mjs'),+ `export const gapReport = {+ audience: 'internal',+ handle(report) { return {status: 'filed', message: report.component}; },+};+export default {};+`,+ );++ const loaded = await loadLocalIntegration(tmpDir, {fresh: true});++ expect(loaded).toMatchObject({name: '@acme/local', __local: true});+ expect(loaded?.__gapReport?.audience).toBe('internal');+ expect(+ loaded?.__gapReport?.handle(+ /** @type {any} */ ({component: 'LocalWidget'}),+ /** @type {any} */ ({signal: new AbortController().signal}),+ ),+ ).toEqual({status: 'filed', message: 'LocalWidget'});+ expect(loaded?.__gapReportError).toBeUndefined();+ });++ it('preserves a malformed gapReport error without dropping the manifest', async () => {+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({name: '@acme/local', version: '1.0.0'}),+ );+ fs.writeFileSync(+ path.join(tmpDir, 'astryx.integration.mjs'),+ `export const gapReport = {audience: 'internal', command: './report.mjs'};+export default {issuesUrl: 'https://example.com/issues'};+`,);++ const loaded = await loadLocalIntegration(tmpDir, {fresh: true});++ expect(loaded).toMatchObject({+ name: '@acme/local',+ issuesUrl: 'https://example.com/issues',+ __local: true,+ });+ expect(loaded?.__loadError).toBeUndefined();+ expect(loaded?.__gapReport).toBeUndefined();+ expect(loaded?.__gapReportError).toMatch(/gapReport.*handle/i);});});@@ -198,7 +265,9 @@ describe('resolvePackageDir — spec must be a bare package name', () => {it.each(['../../../etc', 'a/../../b', '/abs/evil', 'foo/..', '..'])('rejects a traversal/absolute spec %s',spec => {- expect(() => resolvePackageDir(spec, '/proj')).toThrow(/Invalid|outside node_modules/i);+ expect(() => resolvePackageDir(spec, '/proj')).toThrow(+ /Invalid|outside node_modules/i,+ );},);@@ -223,7 +292,10 @@ describe('a broken integration manifest degrades gracefully (skip + warn)', () =]) {const dir = path.join(tmpDir, 'node_modules', ...name.split('/'));fs.mkdirSync(dir, {recursive: true});- fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({name, version: '1.0.0'}));+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ JSON.stringify({name, version: '1.0.0'}),+ );fs.writeFileSync(path.join(dir, 'astryx.integration.mjs'), body);}@@ -279,3 +351,54 @@ describe('the `debug` named export', () => {expect(loaded.__unknownKeys).toEqual([]);});});++describe('the `gapReport` named export', () => {+ it('loads a function handler without turning it into a manifest key', async () => {+ writeManifestPackage(tmpDir, {+ body:+ `const handle = async report => ({status: 'filed', message: report.component});\n` ++ `export const gapReport = {audience: 'public', handle};\n` ++ `export default {issuesUrl: 'https://example.com/i'};\n`,+ });++ const [loaded] = await loadIntegrations(['@acme/widgets'], {cwd: tmpDir});++ expect(loaded.__gapReport?.audience).toBe('public');+ expect(typeof loaded.__gapReport?.handle).toBe('function');+ await expect(+ loaded.__gapReport?.handle(/** @type {any} */ ({component: 'Button'})),+ ).resolves.toEqual({+ status: 'filed',+ message: 'Button',+ });+ expect(loaded.__gapReportError).toBeUndefined();+ expect(loaded.__unknownKeys).toEqual([]);+ expect(loaded.issuesUrl).toBe('https://example.com/i');+ });++ it('isolates an invalid named handler from the default manifest', async () => {+ writeManifestPackage(tmpDir, {+ body:+ `export const gapReport = {audience: 'internal', command: './report.mjs'};\n` ++ `export default {issuesUrl: 'https://example.com/i'};\n`,+ });++ const [loaded] = await loadIntegrations(['@acme/widgets'], {cwd: tmpDir});++ expect(loaded.__loadError).toBeUndefined();+ expect(loaded.__gapReport).toBeUndefined();+ expect(loaded.__gapReportError).toMatch(/gapReport/);+ expect(loaded.issuesUrl).toBe('https://example.com/i');+ });++ it('keeps a same-named default-manifest field unknown instead of treating it as a handler', async () => {+ writeManifestPackage(tmpDir, {+ body: `export default {gapReport: {audience: 'public', handle: () => {}}};\n`,+ });++ const [loaded] = await loadIntegrations(['@acme/widgets'], {cwd: tmpDir});++ expect(loaded.__gapReport).toBeUndefined();+ expect(loaded.__unknownKeys).toEqual(['gapReport']);+ });+});diff --git a/packages/cli/foundation/response/response-types.doc.mjs b/packages/cli/foundation/response/response-types.doc.mjsindex ee355f1f17..2c0ca54e45 100644--- a/packages/cli/foundation/response/response-types.doc.mjs+++ b/packages/cli/foundation/response/response-types.doc.mjs@@ -138,6 +138,17 @@ export const doc = {'An eject receipt: component name, owning package, output directory, files-copied count, the written file names, whether any file uses StyleX, and an optional maintainer note.',},+ // gap reports+ {+ value: 'gap-report.categories',+ description: 'The fixed gap category values and human-readable labels.',+ },+ {+ value: 'gap-report.file',+ description:+ 'An aggregate receipt with overall status, the selected package and issues URL, ordered per-handler deliveries, and filedCount/routedOnlyCount totals.',+ },+// template{value: 'template.list',