An open source design system that's fully customizable and agent ready
TypeScript
feat(cli): add integration authoring checks to doctor (#6173)
Joey54ecd59ea714
diff --git a/.changeset/doctor-integration-authoring.md b/.changeset/doctor-integration-authoring.mdnew file mode 100644index 0000000000..283242cac6--- /dev/null+++ b/.changeset/doctor-integration-authoring.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[feat] Add `doctor integration` checks for structural validation and Core template, component, and doc overlaps (#6173).++@josephfarinadiff --git a/packages/cli/README.md b/packages/cli/README.mdindex 1ddaf09f39..ac51c5537b 100644--- a/packages/cli/README.md+++ b/packages/cli/README.md@@ -58,23 +58,22 @@ Options:<!-- BEGIN GENERATED: commands -->-| Command | Description |-| ---------------------- | ----------------------------------------------------------------------------- |-| `blog` | Read the Astryx blog from the published feed |-| `build` | Build a page: composition kit for an idea, or the workflow playbook (no args) |-| `component` | List components or print component docs |-| `discover` | Discover external packages and components |-| `docs` | Print reference docs |-| `doctor` | Diagnose your XDS setup and report problems with fixes |-| `hook` | List hooks or print hook docs |-| `init` | Initialize the design system in your project |-| `layout` | Generate XDS layouts from compressed expressions (XLE/XLO) |-| `search` | Search components, hooks, docs, and templates in one ranked list |-| `swizzle` | Copy component source for customization |-| `template` | Inject a page or block template |-| `theme` | Theme tools: build, export, and manage themes |-| `upgrade` | Run codemods to migrate between versions |-| `validate-integration` | Validate an Astryx integration package (manifest + contributions) |+| Command | Description |+| ----------- | ----------------------------------------------------------------------------- |+| `blog` | Read the Astryx blog from the published feed |+| `build` | Build a page: composition kit for an idea, or the workflow playbook (no args) |+| `component` | List components or print component docs |+| `discover` | Discover external packages and components |+| `docs` | Print reference docs |+| `doctor` | Diagnose your XDS setup and report problems with fixes |+| `hook` | List hooks or print hook docs |+| `init` | Initialize the design system in your project |+| `layout` | Generate XDS layouts from compressed expressions (XLE/XLO) |+| `search` | Search components, hooks, docs, and templates in one ranked list |+| `swizzle` | Copy component source for customization |+| `template` | Inject a page or block template |+| `theme` | Theme tools: build, export, and manage themes |+| `upgrade` | Run codemods to migrate between versions |<!-- END GENERATED: commands --><!-- Generated by scripts/generate-cli-readme.mjs from `astryx manifest`. Run `pnpm -F @astryxdesign/cli readme`. -->@@ -387,55 +386,58 @@ Every response has a `type` discriminant. The full set is below (generated from<!-- BEGIN GENERATED: response-types -->-| Type | What `data` carries |-| --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `init.run` | The install receipt: the `mode` (`default` \| `features`), the features run, agent-doc files written, any soft `docsError`, whether theme guidance was emitted, the template outcome (`workflow` \| `created` \| `skipped`) plus its path, and whether the next-steps were emitted. |-| `init.remove` | Confirmation that the managed agent-docs block was removed (`data.removed: true`) — returned when --remove-agents is set. |-| `component.list` | The component catalog grouped by category: `detail` (the level: names \| compact \| full) and `components`, the grouped map of names+package, brief entries, or a full ComponentDoc per entry. |-| `component.detail` | One component's authored ComponentDoc plus ownership metadata (owner package, import specifier, and whether source is available). |-| `component.detail.props` | Just one component's props table (ComponentPropDoc[]). |-| `component.detail.source` | One component's source file, as {component, source}. |-| `component.detail.showcase` | One component's showcase example, as {component, aspectRatio, source}. |-| `component.detail.blocks` | One component's example blocks, as {component, showcase, examples, related} of BlockEntry. |-| `docs.list` | All reference-doc topics as DocsListEntry[] ({topic, description}), in discovery order. |-| `docs.detail` | One topic's full ReferenceDoc, with token-ref blocks inlined. |-| `docs.detail.section` | A single ReferenceSection of a topic: the first whose title contains the section query. |-| `blog.list` | The feed URL plus every post parsed from the RSS feed, each with slug, title, description, date, type, authors, link, and plaintext URL. |-| `blog.detail` | One post's metadata plus the feed URL and the post's full plaintext body. |-| `discover.list` | The configured external packages (name, category, components, version, description); when empty it carries meta.configured to tell "nothing configured" from "nothing discovered". |-| `discover.detail` | A single external package entry, for an @scope/name query. |-| `discover.detail.doc` | The validated ComponentDoc for one external component: an @scope/name/Component query, or a free-text term resolving to exactly one component. |-| `discover.search` | The echoed query plus the matching {package, component} pairs, when a free-text term matches several components. |-| `search` | The echoed query, `matchCount` (how many candidates matched in total, before `limit`), plus a ranked SearchResultEntry[] bounded by `limit` (domain, name, score, reason, description, follow-up command, and import path where relevant). |-| `build.help` | A marker (`playbook: true`) that the renderer expands into the how-to-build-a-page workflow; emitted when no query is given. |-| `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. |-| `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. |-| `template.copy` | A scaffold receipt: template id, output directory, written file name, and file count. |-| `template.cdn` | A write receipt for the no-build-step CDN starter page: the path (relative to cwd), the Astryx version every CDN URL was pinned to, whether it was written, and the reason it was not. `exists` when a file was already there, which is a success. |-| `hook.list` | The hook catalog grouped by category: `detail` (the level: names \| compact \| full) and `components`, the grouped map of hook names, brief entries, or a full HookDoc per entry. |-| `hook.detail` | One hook's full authored HookDoc. |-| `hook.detail.params` | Just one hook's parameters table (HookParamDoc[]). |-| `theme.build` | A theme build receipt: name, token- and component-override counts, output size, the written outputs {css, js, dts, and variantsDts when applicable}, and any validation warnings. |-| `theme.build.check` | The --check receipt: theme name, an upToDate flag, the stale outputs (each {path, reason: missing \| outdated}), and the full list of checked paths. Writes nothing. |-| `theme.build.batch` | Several themes built in one invocation: `count` plus one {file, receipt} per theme in argument order, where receipt is that theme's theme.build (or theme.build.check) envelope, or null when it produced no CSS. |-| `theme.list` | Every bundled theme as a ThemeListEntry[]: each with slug, displayName, description, and a maintained flag. |-| `theme.add` | A scaffold receipt: resolved slug, displayName, maintained flag, outputDir (relative to cwd), the theme entry file, its exportName, and the files written. |-| `theme.template` | A write receipt for the annotated theme template: the path (relative to cwd), whether it was written, and the reason it was not. `exists` when a file was already there, which is a success. |-| `theme.targets` | The whole themeable surface: the echoed filter, the component count, and one entry per theming target — {key, className, component, props, states}, where props and states are its legal override keys. |-| `theme.palette.generate` | An author-reviewable OKLCH palette candidate, its reproducibility receipt, summary counts, and optional candidate/receipt file-write result. |-| `upgrade.list` | Every available codemod, oldest→newest, as {name, title, version, optional}; returned for --list without running anything. |-| `upgrade.status` | A short-circuit outcome with no codemods run (up_to_date, no_codemods, or config_fixable), each carrying the agent-docs summary. |-| `upgrade.run` | The run receipt: from/to versions, codemod count, integrations processed, the agent-docs summary, and (apply mode) filesChanged, transformsApplied, and per-codemod errors. |-| `manifest` | The self-describing CLI capability manifest: name, version, apiVersion, global options, the command tree (args, options, json flag, response types, examples), the jsonSupported allowlist, and the flat responseTypes index. |-| `doctor` | The health-check report: `checks` (each with id, label, status: pass \| warn \| fail \| info, a message, and a fix when not passing) plus a `summary` of counts per status. |-| `integration.validate` | The validation result: the package name and version (both null when no local manifest is found) plus issues, an AstryxIntegrationIssue[] of {code, severity: warning \| error, message}. |-| `layout.expand` | The expansion: parsed form, generated TSX code, componentsUsed, states (count of useState hooks scaffolded), todos, blocksReferenced (each {name, mode}), warnings, and written (the output path, or null when nothing was written). |-| `layout.check` | The validation result: a valid flag, the detected form, errors (each with line/col, message, formatted text, and suggestions), warnings, and the expression re-printed in both canonical surfaces (compact and outline). |-| `layout.grammar` | The XLE/XLO grammar cheatsheet: a text field with the full reference plus an aliases map (short name → canonical component) generated from this install's registry. |+| Type | What `data` carries |+| --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `init.run` | The install receipt: the `mode` (`default` \| `features`), the features run, agent-doc files written, any soft `docsError`, whether theme guidance was emitted, the template outcome (`workflow` \| `created` \| `skipped`) plus its path, and whether the next-steps were emitted. |+| `init.remove` | Confirmation that the managed agent-docs block was removed (`data.removed: true`) — returned when --remove-agents is set. |+| `component.list` | The component catalog grouped by category: `detail` (the level: names \| compact \| full) and `components`, the grouped map of names+package, brief entries, or a full ComponentDoc per entry. |+| `component.detail` | One component's authored ComponentDoc plus ownership metadata (owner package, import specifier, and whether source is available). |+| `component.detail.props` | Just one component's props table (ComponentPropDoc[]). |+| `component.detail.source` | One component's source file, as {component, source}. |+| `component.detail.showcase` | One component's showcase example, as {component, aspectRatio, source}. |+| `component.detail.blocks` | One component's example blocks, as {component, showcase, examples, related} of BlockEntry. |+| `docs.list` | All reference-doc topics as DocsListEntry[] ({topic, description}), in discovery order. |+| `docs.detail` | One topic's full ReferenceDoc, with token-ref blocks inlined. |+| `docs.detail.section` | A single ReferenceSection of a topic: the first whose title contains the section query. |+| `blog.list` | The feed URL plus every post parsed from the RSS feed, each with slug, title, description, date, type, authors, link, and plaintext URL. |+| `blog.detail` | One post's metadata plus the feed URL and the post's full plaintext body. |+| `discover.list` | The configured external packages (name, category, components, version, description); when empty it carries meta.configured to tell "nothing configured" from "nothing discovered". |+| `discover.detail` | A single external package entry, for an @scope/name query. |+| `discover.detail.doc` | The validated ComponentDoc for one external component: an @scope/name/Component query, or a free-text term resolving to exactly one component. |+| `discover.search` | The echoed query plus the matching {package, component} pairs, when a free-text term matches several components. |+| `search` | The echoed query, `matchCount` (how many candidates matched in total, before `limit`), plus a ranked SearchResultEntry[] bounded by `limit` (domain, name, score, reason, description, follow-up command, and import path where relevant). |+| `build.help` | A marker (`playbook: true`) that the renderer expands into the how-to-build-a-page workflow; emitted when no query is given. |+| `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. |+| `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. |+| `template.copy` | A scaffold receipt: template id, output directory, written file name, and file count. |+| `template.cdn` | A write receipt for the no-build-step CDN starter page: the path (relative to cwd), the Astryx version every CDN URL was pinned to, whether it was written, and the reason it was not. `exists` when a file was already there, which is a success. |+| `hook.list` | The hook catalog grouped by category: `detail` (the level: names \| compact \| full) and `components`, the grouped map of hook names, brief entries, or a full HookDoc per entry. |+| `hook.detail` | One hook's full authored HookDoc. |+| `hook.detail.params` | Just one hook's parameters table (HookParamDoc[]). |+| `theme.build` | A theme build receipt: name, token- and component-override counts, output size, the written outputs {css, js, dts, and variantsDts when applicable}, and any validation warnings. |+| `theme.build.check` | The --check receipt: theme name, an upToDate flag, the stale outputs (each {path, reason: missing \| outdated}), and the full list of checked paths. Writes nothing. |+| `theme.build.batch` | Several themes built in one invocation: `count` plus one {file, receipt} per theme in argument order, where receipt is that theme's theme.build (or theme.build.check) envelope, or null when it produced no CSS. |+| `theme.list` | Every bundled theme as a ThemeListEntry[]: each with slug, displayName, description, and a maintained flag. |+| `theme.add` | A scaffold receipt: resolved slug, displayName, maintained flag, outputDir (relative to cwd), the theme entry file, its exportName, and the files written. |+| `theme.template` | A write receipt for the annotated theme template: the path (relative to cwd), whether it was written, and the reason it was not. `exists` when a file was already there, which is a success. |+| `theme.targets` | The whole themeable surface: the echoed filter, the component count, and one entry per theming target — {key, className, component, props, states}, where props and states are its legal override keys. |+| `theme.palette.generate` | An author-reviewable OKLCH palette candidate, its reproducibility receipt, summary counts, and optional candidate/receipt file-write result. |+| `upgrade.list` | Every available codemod, oldest→newest, as {name, title, version, optional}; returned for --list without running anything. |+| `upgrade.status` | A short-circuit outcome with no codemods run (up_to_date, no_codemods, or config_fixable), each carrying the agent-docs summary. |+| `upgrade.run` | The run receipt: from/to versions, codemod count, integrations processed, the agent-docs summary, and (apply mode) filesChanged, transformsApplied, and per-codemod errors. |+| `manifest` | The self-describing CLI capability manifest: name, version, apiVersion, global options, the command tree (args, options, json flag, response types, examples), the jsonSupported allowlist, and the flat responseTypes index. |+| `doctor` | The health-check report: `checks` (each with id, label, status: pass \| warn \| fail \| info, a message, and a fix when not passing) plus a `summary` of counts per status. |+| `integration.validate` | The validation result: the package name and version (both null when no local manifest is found) plus issues, an AstryxIntegrationIssue[] of {code, severity: warning \| error, message}. |+| `integration.template-conflicts` | The integration identity, structural issues, and non-blocking conflicts where an integration template id is also owned by Core; each conflict includes the exact package-qualified command. |+| `integration.component-conflicts` | The integration identity, structural issues, and non-blocking conflicts where an integration component name is also owned by Core; each conflict includes the exact package-qualified command. |+| `integration.doc-conflicts` | The integration identity, structural issues, and Core doc overlaps classified as intentional replacements, intentional extensions, or accidental same-name conflicts. |+| `layout.expand` | The expansion: parsed form, generated TSX code, componentsUsed, states (count of useState hooks scaffolded), todos, blocksReferenced (each {name, mode}), warnings, and written (the output path, or null when nothing was written). |+| `layout.check` | The validation result: a valid flag, the detected form, errors (each with line/col, message, formatted text, and suggestions), warnings, and the expression re-printed in both canonical surfaces (compact and outline). |+| `layout.grammar` | The XLE/XLO grammar cheatsheet: a text field with the full reference plus an aliases map (short name → canonical component) generated from this install's registry. |<!-- END GENERATED: response-types --><!-- Generated by scripts/generate-cli-readme.mjs from the response-types EnumDoc. Run `pnpm -F @astryxdesign/cli readme`. -->@@ -613,8 +615,10 @@ everything this one understands.Discovery is resilient: a broken or misconfigured integration is skipped with aone-line warning on stderr instead of crashing the CLI, and it never corrupts a`--json` envelope. To inspect problems, run-`astryx validate-integration <package>` for a detailed report on one package, or-`astryx doctor` for an overall health check.+`astryx doctor integration validate <package>` for structure, then use `templates`,+`components`, or `docs` under the same `astryx doctor integration` group to check+Core identity overlaps before publishing. Bare `astryx doctor` checks overall+project health.For the full authoring walkthrough (component doc format, template packagingand `exports` requirements, and codemod authoring), see the guide:diff --git a/packages/cli/api/index.mjs b/packages/cli/api/index.mjsindex 5f9626630a..8f2cdb56cc 100644--- a/packages/cli/api/index.mjs+++ b/packages/cli/api/index.mjs@@ -38,6 +38,11 @@ export {validateIntegration,summarizeIssues,} from './integration/validate-integration.mjs';+export {+ integrationTemplateConflicts,+ integrationComponentConflicts,+ integrationDocConflicts,+} from './integration/authoring-checks.mjs';export {AstryxError} from './error.mjs';// The one shared logger: the `logger` instance side-effecting commands write// through, plus its generated `Logger` type. Part of the public surface so an@@ -66,3 +71,4 @@ export * from './init/init.type.mjs';export * from './doctor/doctor.type.mjs';export * from './layout/layout.type.mjs';export * from './integration/validate-integration.type.mjs';+export * from './integration/authoring-checks.type.mjs';diff --git a/packages/cli/api/integration/authoring-checks.mjs b/packages/cli/api/integration/authoring-checks.mjsnew file mode 100644index 0000000000..7307e24ff6--- /dev/null+++ b/packages/cli/api/integration/authoring-checks.mjs@@ -0,0 +1,283 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Integration authoring diagnostics against the built-in Core catalog.+ *+ * Components and templates may intentionally share a Core identity, but+ * unqualified lookup then fails closed and callers must select the package.+ * Docs have explicit `replaces` / `extends` relationships, so the check can+ * distinguish intentional ownership from an accidental same-name shadow.+ */++import {getCliInvocation} from '../../foundation/env/package-manager.mjs';+import {findCoreDir} from '../../foundation/fs/paths.mjs';+import {+ discoverIntegrationComponents,+ discoverOwnedComponents,+} from '../../foundation/discovery/component-discovery.mjs';+import {+ discoverBuiltinTopics,+ discoverIntegrationDocs,+} from '../../foundation/discovery/docs-discovery.mjs';+import {+ discoverCoreTemplates,+ discoverIntegrationTemplatesForOne,+} from '../../foundation/discovery/template-adapter.mjs';+import {+ validateInstalledIntegration,+ validateLocalIntegration,+} from './validate-integration.mjs';++/** @param {string} value */+export function shellArg(value) {+ if (/^[A-Za-z0-9@/._-]+$/.test(value)) return value;+ return `'${value.replace(/'/g, `'\\''`)}'`;+}++/**+ * Resolve one local or installed integration for an authoring check.+ * @param {string | undefined} pkg+ * @param {string} cwd+ */+async function resolveIntegration(pkg, cwd) {+ return pkg+ ? validateInstalledIntegration(pkg, cwd)+ : validateLocalIntegration(cwd);+}++/**+ * Add discovery errors once to an issue list.+ * @param {Array<{code: string, severity: 'warning' | 'error', message: string}>} issues+ * @param {Array<{message: string} | Error>} errors+ * @param {string} code+ */+function addErrors(issues, errors, code) {+ for (const error of errors) {+ const message = error.message;+ if (issues.some(issue => issue.code === code && issue.message === message)) {+ continue;+ }+ issues.push({code, severity: 'error', message});+ }+}++/**+ * Find integration template ids that are also owned by Core.+ * @param {string} [pkg] Installed integration package; omit for the local package.+ * @param {import('./authoring-checks.type.mjs').IntegrationAuthoringOptions} [options]+ * @returns {Promise<import('./authoring-checks.type.mjs').IntegrationTemplateConflictResponse>}+ */+export async function integrationTemplateConflicts(pkg, options = {}) {+ const {cwd = process.cwd()} = options;+ const resolved = await resolveIntegration(pkg, cwd);+ const name = resolved.found ? (resolved.name ?? null) : null;+ const version = resolved.found ? (resolved.version ?? null) : null;+ const issues = [...resolved.issues];++ if (!resolved.integration?.templates || name == null) {+ return {+ type: 'integration.template-conflicts',+ data: {name, version, conflicts: [], issues},+ };+ }++ const [{templates, errors}, coreTemplates] = await Promise.all([+ discoverIntegrationTemplatesForOne(resolved.integration),+ discoverCoreTemplates(),+ ]);+ addErrors(issues, errors, 'invalid_template');++ /** @type {Map<string, Array<{type: 'page' | 'block', name: string}>>} */+ const coreById = new Map();+ for (const template of coreTemplates) {+ const matches = coreById.get(template.dirName) ?? [];+ matches.push({type: template.type, name: template.name});+ coreById.set(template.dirName, matches);+ }+ for (const matches of coreById.values()) {+ matches.sort((a, b) =>+ `${a.type}:${a.name}`.localeCompare(`${b.type}:${b.name}`),+ );+ }++ const run = getCliInvocation(cwd);+ const conflicts = templates+ .flatMap(template => {+ const coreMatches = coreById.get(template.dirName);+ if (!coreMatches) return [];+ const command = `${run} template ${shellArg(template.dirName)} --package ${shellArg(name)}`;+ const coreKinds = coreMatches+ .map(match => `${match.type} "${match.name}"`)+ .join(', ');+ return [+ {+ id: template.dirName,+ severity: /** @type {const} */ ('warning'),+ integrationPackage: name,+ integrationType: template.type,+ integrationName: template.name,+ coreMatches,+ message:+ `Template id "${template.dirName}" conflicts with Core (${coreKinds}). ` ++ 'Consider renaming the integration template. If you keep it, always select it with --package.',+ command,+ },+ ];+ })+ .sort((a, b) => a.id.localeCompare(b.id));++ return {+ type: 'integration.template-conflicts',+ data: {name, version, conflicts, issues},+ };+}++/**+ * Find integration component names that are also owned by Core.+ * @param {string} [pkg]+ * @param {import('./authoring-checks.type.mjs').IntegrationAuthoringOptions} [options]+ * @returns {Promise<import('./authoring-checks.type.mjs').IntegrationComponentConflictResponse>}+ */+export async function integrationComponentConflicts(pkg, options = {}) {+ const {cwd = process.cwd()} = options;+ const resolved = await resolveIntegration(pkg, cwd);+ const name = resolved.found ? (resolved.name ?? null) : null;+ const version = resolved.found ? (resolved.version ?? null) : null;+ const issues = [...resolved.issues];++ if (!resolved.integration?.components || name == null) {+ return {+ type: 'integration.component-conflicts',+ data: {name, version, conflicts: [], issues},+ };+ }++ const coreDir = findCoreDir(cwd);+ if (!coreDir) {+ issues.push({+ code: 'core_not_found',+ severity: 'error',+ message:+ 'Could not resolve @astryxdesign/core, so component names could not be checked. Install Core and run this check again.',+ });+ return {+ type: 'integration.component-conflicts',+ data: {name, version, conflicts: [], issues},+ };+ }++ const coreNames = new Set(+ discoverOwnedComponents(coreDir, [])+ .filter(record => record.package === '@astryxdesign/core')+ .map(record => record.name),+ );+ const run = getCliInvocation(cwd);+ const conflicts = discoverIntegrationComponents(resolved.integration)+ .filter(component => coreNames.has(component.name))+ .map(component => ({+ name: component.name,+ severity: /** @type {const} */ ('warning'),+ integrationPackage: name,+ message:+ `Component "${component.name}" conflicts with Core. Consider renaming the integration component. ` ++ 'If you keep it, always select it with --package.',+ command: `${run} component ${shellArg(component.name)} --package ${shellArg(name)}`,+ }))+ .sort((a, b) => a.name.localeCompare(b.name));++ return {+ type: 'integration.component-conflicts',+ data: {name, version, conflicts, issues},+ };+}++/**+ * Classify integration docs that overlap with built-in Core topics.+ * @param {string} [pkg]+ * @param {import('./authoring-checks.type.mjs').IntegrationAuthoringOptions} [options]+ * @returns {Promise<import('./authoring-checks.type.mjs').IntegrationDocConflictResponse>}+ */+export async function integrationDocConflicts(pkg, options = {}) {+ const {cwd = process.cwd()} = options;+ const resolved = await resolveIntegration(pkg, cwd);+ const name = resolved.found ? (resolved.name ?? null) : null;+ const version = resolved.found ? (resolved.version ?? null) : null;+ const issues = [...resolved.issues];++ if (!resolved.integration?.docs || name == null) {+ return {+ type: 'integration.doc-conflicts',+ data: {name, version, findings: [], issues},+ };+ }++ const [{records, errors}, builtinTopics] = await Promise.all([+ discoverIntegrationDocs(resolved.integration),+ Promise.resolve(discoverBuiltinTopics()),+ ]);+ addErrors(issues, errors, 'invalid_doc');+ const coreTopicsByKey = new Map(+ Object.keys(builtinTopics).map(topic => [topic.toLowerCase(), topic]),+ );++ /** @type {import('./authoring-checks.type.mjs').IntegrationDocFinding[]} */+ const findings = [];+ for (const record of records) {+ const replacedCore =+ record.replaces == null+ ? undefined+ : coreTopicsByKey.get(record.replaces.toLowerCase());+ const extendedCore =+ record.extendsTopic == null+ ? undefined+ : coreTopicsByKey.get(record.extendsTopic.toLowerCase());+ const sameNameCore = coreTopicsByKey.get(record.name.toLowerCase());++ if (replacedCore != null) {+ findings.push({+ topic: record.name,+ severity: 'info',+ relationship: 'replaces',+ coreTopic: replacedCore,+ message: `Intentional override: "${record.name}" replaces the Core topic "${replacedCore}".`,+ });+ }+ if (extendedCore != null) {+ findings.push({+ topic: record.name,+ severity: 'info',+ relationship: 'extends',+ coreTopic: extendedCore,+ message: `Intentional extension: "${record.name}" extends the Core topic "${extendedCore}".`,+ });+ }++ // An extension never owns its own name. A replacement does, so it may only+ // reuse a Core name when that is the Core topic it explicitly replaces.+ if (+ sameNameCore != null &&+ record.extendsTopic == null &&+ replacedCore !== sameNameCore+ ) {+ findings.push({+ topic: record.name,+ severity: 'error',+ relationship: 'accidental',+ coreTopic: sameNameCore,+ message:+ `Accidental conflict: "${record.name}" is already a Core topic. ` ++ `Rename it, declare replaces: '${sameNameCore}' to take it over, or declare extends: '${sameNameCore}' to merge sections.`,+ });+ }+ }+ findings.sort((a, b) =>+ `${a.topic}:${a.relationship}`.localeCompare(+ `${b.topic}:${b.relationship}`,+ ),+ );++ return {+ type: 'integration.doc-conflicts',+ data: {name, version, findings, issues},+ };+}diff --git a/packages/cli/api/integration/authoring-checks.test.mjs b/packages/cli/api/integration/authoring-checks.test.mjsnew file mode 100644index 0000000000..f658db4a91--- /dev/null+++ b/packages/cli/api/integration/authoring-checks.test.mjs@@ -0,0 +1,353 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Hermetic integration authoring checks against the real Core catalogs.+ */++import {afterEach, beforeEach, describe, expect, it} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {discoverCoreTemplates} from '../../foundation/discovery/template-adapter.mjs';+import {discoverOwnedComponents} from '../../foundation/discovery/component-discovery.mjs';+import {discoverBuiltinTopics} from '../../foundation/discovery/docs-discovery.mjs';+import {findCoreDir} from '../../foundation/fs/paths.mjs';+import {+ integrationComponentConflicts,+ integrationDocConflicts,+ integrationTemplateConflicts,+ shellArg,+} from './authoring-checks.mjs';++let tmpDir;++function writeIntegration({id, name, type = 'block', root = tmpDir}) {+ fs.mkdirSync(root, {recursive: true});+ fs.writeFileSync(+ path.join(root, 'package.json'),+ JSON.stringify({name: '@acme/widgets', version: '1.2.3'}),+ );+ fs.writeFileSync(+ path.join(root, 'astryx.integration.mjs'),+ `export default {templates: './templates'};\n`,+ );+ const stem = path.join(root, 'templates', id);+ fs.mkdirSync(path.dirname(stem), {recursive: true});+ fs.writeFileSync(+ `${stem}.template.mjs`,+ `export default {type: '${type}', name: ${JSON.stringify(name)}, description: 'fixture'};\n`,+ );+ fs.writeFileSync(+ `${stem}.tsx`,+ 'export default function Fixture() { return null; }\n',+ );+}++function writeComponentIntegration(componentName) {+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({name: '@acme/widgets', version: '1.2.3'}),+ );+ fs.writeFileSync(+ path.join(tmpDir, 'astryx.integration.mjs'),+ `export default {components: './components'};\n`,+ );+ fs.mkdirSync(path.join(tmpDir, 'components'), {recursive: true});+ fs.writeFileSync(+ path.join(tmpDir, 'components', `${componentName}.doc.mjs`),+ `export default {type: 'component', name: ${JSON.stringify(componentName)}, displayName: ${JSON.stringify(componentName)}, description: 'Fixture component.', props: []};\n`,+ );+ fs.writeFileSync(+ path.join(tmpDir, 'components', `${componentName}.tsx`),+ 'export default function Fixture() { return null; }\n',+ );+}++function writeDocIntegration({name, replaces, extendsTopic}) {+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({name: '@acme/widgets', version: '1.2.3'}),+ );+ fs.writeFileSync(+ path.join(tmpDir, 'astryx.integration.mjs'),+ `export default {docs: './docs'};\n`,+ );+ fs.mkdirSync(path.join(tmpDir, 'docs'), {recursive: true});+ const relationship =+ replaces != null+ ? `, replaces: ${JSON.stringify(replaces)}`+ : extendsTopic != null+ ? `, extends: ${JSON.stringify(extendsTopic)}`+ : '';+ fs.writeFileSync(+ path.join(tmpDir, 'docs', `${name}.doc.mjs`),+ `export default {type: 'generic', name: ${JSON.stringify(name)}, title: 'Fixture', description: 'Fixture topic.'${relationship}, sections: [{title: 'Overview', content: [{type: 'prose', text: 'Fixture.'}]}]};\n`,+ );+}++beforeEach(() => {+ tmpDir = fs.mkdtempSync(+ path.join(process.cwd(), '.astryx-template-conflicts-'),+ );+});++afterEach(() => {+ fs.rmSync(tmpDir, {recursive: true, force: true});+});++describe('integrationTemplateConflicts', () => {+ it('warns on an id shared with Core and gives the package-qualified command', async () => {+ const [core] = await discoverCoreTemplates();+ expect(core).toBeDefined();+ writeIntegration({+ id: core.dirName,+ name: 'Integration override',+ type: core.type,+ });++ const result = await integrationTemplateConflicts(undefined, {cwd: tmpDir});++ expect(result.type).toBe('integration.template-conflicts');+ expect(result.data.name).toBe('@acme/widgets');+ expect(result.data.issues).toEqual([]);+ expect(result.data.conflicts).toHaveLength(1);+ expect(result.data.conflicts[0]).toMatchObject({+ id: core.dirName,+ severity: 'warning',+ integrationPackage: '@acme/widgets',+ integrationName: 'Integration override',+ });+ expect(result.data.conflicts[0].message).toContain('Consider renaming');+ expect(result.data.conflicts[0].command).toContain(+ `template ${core.dirName} --package @acme/widgets`,+ );+ });++ it('does not flag a shared display name when the ids differ', async () => {+ const [core] = await discoverCoreTemplates();+ expect(core).toBeDefined();+ writeIntegration({+ id: 'integration-only-id',+ name: core.name,+ type: core.type,+ });++ const result = await integrationTemplateConflicts(undefined, {cwd: tmpDir});++ expect(result.data.conflicts).toEqual([]);+ expect(result.data.issues).toEqual([]);+ });++ it('loads an installed integration through the same conflict path', async () => {+ const [core] = await discoverCoreTemplates();+ expect(core).toBeDefined();+ const installed = path.join(tmpDir, 'node_modules', '@acme', 'widgets');+ writeIntegration({+ id: core.dirName,+ name: 'Installed override',+ type: core.type,+ root: installed,+ });++ const result = await integrationTemplateConflicts('@acme/widgets', {+ cwd: tmpDir,+ });++ expect(result.data.name).toBe('@acme/widgets');+ expect(result.data.conflicts.map(conflict => conflict.id)).toContain(+ core.dirName,+ );+ });++ it('shell-quotes unusual ids instead of allowing command substitution', () => {+ expect(shellArg('safe/id')).toBe('safe/id');+ expect(shellArg('my$thing')).toBe("'my$thing'");+ expect(shellArg("a'b")).toBe("'a'\\''b'");+ expect(shellArg('foo`id`')).toBe("'foo`id`'");+ });++ it('returns a malformed template once as an invalid_template issue', async () => {+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({name: '@acme/widgets', version: '1.2.3'}),+ );+ fs.writeFileSync(+ path.join(tmpDir, 'astryx.integration.mjs'),+ `export default {templates: './templates'};\n`,+ );+ fs.mkdirSync(path.join(tmpDir, 'templates'), {recursive: true});+ fs.writeFileSync(+ path.join(tmpDir, 'templates', 'broken.template.mjs'),+ `throw new Error('broken fixture');\n`,+ );+ fs.writeFileSync(+ path.join(tmpDir, 'templates', 'broken.tsx'),+ 'export default function Broken() { return null; }\n',+ );++ const result = await integrationTemplateConflicts(undefined, {cwd: tmpDir});+ const invalid = result.data.issues.filter(+ issue => issue.code === 'invalid_template',+ );++ expect(result.data.conflicts).toEqual([]);+ expect(invalid).toHaveLength(1);+ expect(invalid[0].message).toContain('broken fixture');+ });++ it('returns structural issues instead of claiming a broken integration is clean', async () => {+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({name: '@acme/widgets', version: '1.2.3'}),+ );+ fs.writeFileSync(+ path.join(tmpDir, 'astryx.integration.mjs'),+ `export default {templates: './missing'};\n`,+ );++ const result = await integrationTemplateConflicts(undefined, {cwd: tmpDir});++ expect(result.data.conflicts).toEqual([]);+ expect(+ result.data.issues.some(issue => issue.code === 'missing_root'),+ ).toBe(true);+ });+});++describe('integrationComponentConflicts', () => {+ it('warns on a Core component name and gives the package-qualified command', async () => {+ const coreDir = findCoreDir(tmpDir);+ expect(coreDir).not.toBeNull();+ const [core] = discoverOwnedComponents(coreDir, []);+ expect(core).toBeDefined();+ writeComponentIntegration(core.name);++ const result = await integrationComponentConflicts(undefined, {cwd: tmpDir});++ expect(result.type).toBe('integration.component-conflicts');+ expect(result.data.issues).toEqual([]);+ expect(result.data.conflicts).toEqual([+ expect.objectContaining({+ name: core.name,+ severity: 'warning',+ integrationPackage: '@acme/widgets',+ command: expect.stringContaining(+ `component ${core.name} --package @acme/widgets`,+ ),+ }),+ ]);+ });++ it('does not flag an integration-only component name', async () => {+ writeComponentIntegration('AcmeOnlyWidget');++ const result = await integrationComponentConflicts(undefined, {cwd: tmpDir});++ expect(result.data.conflicts).toEqual([]);+ expect(result.data.issues).toEqual([]);+ });+});++describe('integrationDocConflicts', () => {+ it('marks an explicit Core replacement as intentional', async () => {+ const [coreTopic] = Object.keys(discoverBuiltinTopics());+ expect(coreTopic).toBeDefined();+ writeDocIntegration({name: 'acme-setup', replaces: coreTopic});++ const result = await integrationDocConflicts(undefined, {cwd: tmpDir});++ expect(result.type).toBe('integration.doc-conflicts');+ expect(result.data.issues).toEqual([]);+ expect(result.data.findings).toEqual([+ expect.objectContaining({+ topic: 'acme-setup',+ severity: 'info',+ relationship: 'replaces',+ coreTopic,+ }),+ ]);+ });++ it('marks an explicit Core extension as intentional', async () => {+ const [coreTopic] = Object.keys(discoverBuiltinTopics());+ expect(coreTopic).toBeDefined();+ writeDocIntegration({name: 'acme-extra', extendsTopic: coreTopic});++ const result = await integrationDocConflicts(undefined, {cwd: tmpDir});++ expect(result.data.findings).toEqual([+ expect.objectContaining({+ topic: 'acme-extra',+ severity: 'info',+ relationship: 'extends',+ coreTopic,+ }),+ ]);+ });++ it('reports a same-name Core topic without a relationship as accidental', async () => {+ const [coreTopic] = Object.keys(discoverBuiltinTopics());+ expect(coreTopic).toBeDefined();+ writeDocIntegration({name: coreTopic});++ const result = await integrationDocConflicts(undefined, {cwd: tmpDir});++ expect(result.data.findings).toEqual([+ expect.objectContaining({+ topic: coreTopic,+ severity: 'error',+ relationship: 'accidental',+ coreTopic,+ }),+ ]);+ expect(result.data.findings[0].message).toContain(+ `replaces: '${coreTopic}'`,+ );+ expect(result.data.findings[0].message).toContain(+ `extends: '${coreTopic}'`,+ );+ });++ it('reports a Core name as accidental when replacing a different topic', async () => {+ const [replacedCore, nameCore] = Object.keys(discoverBuiltinTopics());+ expect(replacedCore).toBeDefined();+ expect(nameCore).toBeDefined();+ writeDocIntegration({name: nameCore, replaces: replacedCore});++ const result = await integrationDocConflicts(undefined, {cwd: tmpDir});++ expect(result.data.findings).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ topic: nameCore,+ severity: 'info',+ relationship: 'replaces',+ coreTopic: replacedCore,+ }),+ expect.objectContaining({+ topic: nameCore,+ severity: 'error',+ relationship: 'accidental',+ coreTopic: nameCore,+ }),+ ]),+ );+ });++ it('matches Core topic identity case-insensitively like docs lookup', async () => {+ const [coreTopic] = Object.keys(discoverBuiltinTopics());+ expect(coreTopic).toBeDefined();+ const mixedCase = coreTopic.toUpperCase();+ writeDocIntegration({name: mixedCase});++ const result = await integrationDocConflicts(undefined, {cwd: tmpDir});++ expect(result.data.findings).toEqual([+ expect.objectContaining({+ topic: mixedCase,+ severity: 'error',+ relationship: 'accidental',+ coreTopic,+ }),+ ]);+ });+});diff --git a/packages/cli/api/integration/authoring-checks.type.mjs b/packages/cli/api/integration/authoring-checks.type.mjsnew file mode 100644index 0000000000..5afc6713b4--- /dev/null+++ b/packages/cli/api/integration/authoring-checks.type.mjs@@ -0,0 +1,64 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @file Colocated types for integration authoring diagnostics. */++/**+ * @typedef {object} IntegrationAuthoringOptions+ * @property {string} [cwd]+ */++/**+ * @typedef {object} CoreTemplateMatch+ * @property {'page' | 'block'} type+ * @property {string} name+ */++/**+ * @typedef {object} IntegrationTemplateConflict+ * @property {string} id+ * @property {'warning'} severity+ * @property {string} integrationPackage+ * @property {'page' | 'block'} integrationType+ * @property {string} integrationName+ * @property {CoreTemplateMatch[]} coreMatches+ * @property {string} message+ * @property {string} command+ */++/**+ * @typedef {object} IntegrationComponentConflict+ * @property {string} name+ * @property {'warning'} severity+ * @property {string} integrationPackage+ * @property {string} message+ * @property {string} command+ */++/**+ * @typedef {object} IntegrationDocFinding+ * @property {string} topic+ * @property {'info' | 'error'} severity+ * @property {'replaces' | 'extends' | 'accidental'} relationship+ * @property {string} coreTopic+ * @property {string} message+ */++/**+ * @typedef {object} IntegrationTemplateConflictResponse+ * @property {'integration.template-conflicts'} type+ * @property {{name: string | null, version: string | null, conflicts: IntegrationTemplateConflict[], issues: import('../../foundation/integrations/issue').AstryxIntegrationIssue[]}} data+ */++/**+ * @typedef {object} IntegrationComponentConflictResponse+ * @property {'integration.component-conflicts'} type+ * @property {{name: string | null, version: string | null, conflicts: IntegrationComponentConflict[], issues: import('../../foundation/integrations/issue').AstryxIntegrationIssue[]}} data+ */++/**+ * @typedef {object} IntegrationDocConflictResponse+ * @property {'integration.doc-conflicts'} type+ * @property {{name: string | null, version: string | null, findings: IntegrationDocFinding[], issues: import('../../foundation/integrations/issue').AstryxIntegrationIssue[]}} data+ */++export {};diff --git a/packages/cli/api/integration/integrationComponentConflicts.doc.mjs b/packages/cli/api/integration/integrationComponentConflicts.doc.mjsnew file mode 100644index 0000000000..db7028ef09--- /dev/null+++ b/packages/cli/api/integration/integrationComponentConflicts.doc.mjs@@ -0,0 +1,36 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @file FunctionDoc for integration component-conflict diagnostics. */++/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */+export const doc = {+ type: 'function',+ kind: 'api',+ name: 'integrationComponentConflicts',+ displayName: 'integrationComponentConflicts()',+ summary: 'Find integration component names that also exist in Core.',+ description:+ 'Loads one local or installed integration, compares its component names with ' ++ 'Core, and returns non-blocking conflicts with the exact package-qualified ' ++ 'component command required to keep an intentional overlap.',+ importPath: '@astryxdesign/cli/api',+ signature:+ 'integrationComponentConflicts(pkg?: string, options?: IntegrationAuthoringOptions): Promise<IntegrationComponentConflictResponse>',+ keywords: ['integration', 'component', 'conflict', 'authoring', 'doctor'],+ params: [+ {name: 'pkg', type: 'string', description: 'Installed package; omit for the local package.'},+ {name: 'options.cwd', type: 'string', description: 'Resolution directory.'},+ ],+ returns: [+ {+ type: 'integration.component-conflicts',+ description:+ 'Integration identity, structural issues, and Core component-name conflicts with package-qualified commands.',+ },+ ],+ examples: [+ {label: 'Check the local integration', code: 'await integrationComponentConflicts();'},+ ],+ command: 'doctor integration components',+ related: ['integrationTemplateConflicts', 'component'],+};diff --git a/packages/cli/api/integration/integrationDocConflicts.doc.mjs b/packages/cli/api/integration/integrationDocConflicts.doc.mjsnew file mode 100644index 0000000000..0e1365f080--- /dev/null+++ b/packages/cli/api/integration/integrationDocConflicts.doc.mjs@@ -0,0 +1,36 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @file FunctionDoc for integration doc-relationship diagnostics. */++/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */+export const doc = {+ type: 'function',+ kind: 'api',+ name: 'integrationDocConflicts',+ displayName: 'integrationDocConflicts()',+ summary: 'Classify integration doc overlaps with Core topics.',+ description:+ 'Loads one local or installed integration and classifies Core doc overlaps as ' ++ 'intentional replacements, intentional extensions, or accidental same-name ' ++ 'conflicts that need an explicit relationship or a rename.',+ importPath: '@astryxdesign/cli/api',+ signature:+ 'integrationDocConflicts(pkg?: string, options?: IntegrationAuthoringOptions): Promise<IntegrationDocConflictResponse>',+ keywords: ['integration', 'docs', 'replace', 'extend', 'authoring', 'doctor'],+ params: [+ {name: 'pkg', type: 'string', description: 'Installed package; omit for the local package.'},+ {name: 'options.cwd', type: 'string', description: 'Resolution directory.'},+ ],+ returns: [+ {+ type: 'integration.doc-conflicts',+ description:+ 'Integration identity, structural issues, and classified Core doc relationships.',+ },+ ],+ examples: [+ {label: 'Check the local integration', code: 'await integrationDocConflicts();'},+ ],+ command: 'doctor integration docs',+ related: ['validateIntegration', 'docs'],+};diff --git a/packages/cli/api/integration/integrationTemplateConflicts.doc.mjs b/packages/cli/api/integration/integrationTemplateConflicts.doc.mjsnew file mode 100644index 0000000000..97414f8f36--- /dev/null+++ b/packages/cli/api/integration/integrationTemplateConflicts.doc.mjs@@ -0,0 +1,55 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file FunctionDoc for integration template-conflict diagnostics.+ */++/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */+export const doc = {+ type: 'function',+ kind: 'api',+ name: 'integrationTemplateConflicts',+ displayName: 'integrationTemplateConflicts()',+ summary: 'Find integration template ids that also exist in Core.',+ description:+ 'Loads one local or installed integration, compares its template ids with the ' ++ 'built-in Core page and block templates, and returns non-blocking conflicts with ' ++ 'the exact package-qualified CLI command required to keep an intentional overlap.',+ importPath: '@astryxdesign/cli/api',+ signature:+ 'integrationTemplateConflicts(pkg?: string, options?: IntegrationAuthoringOptions): Promise<IntegrationTemplateConflictResponse>',+ keywords: ['integration', 'template', 'conflict', 'authoring', 'doctor'],+ params: [+ {+ name: 'pkg',+ type: 'string',+ description:+ 'Installed integration package; omit to inspect the local package.',+ },+ {+ name: 'options.cwd',+ type: 'string',+ description:+ 'Directory used to resolve the local or installed integration.',+ },+ ],+ returns: [+ {+ type: 'integration.template-conflicts',+ description:+ 'The integration identity, structural issues, and every Core template-id conflict with a package-qualified command.',+ },+ ],+ examples: [+ {+ label: 'Check the local integration',+ code: 'await integrationTemplateConflicts();',+ },+ {+ label: 'Check an installed integration',+ code: "await integrationTemplateConflicts('@acme/widgets');",+ },+ ],+ command: 'doctor integration templates',+ related: ['validateIntegration', 'template'],+};diff --git a/packages/cli/api/integration/validate-integration.mjs b/packages/cli/api/integration/validate-integration.mjsindex 3ddd8b1a3d..e1f1a3675f 100644--- a/packages/cli/api/integration/validate-integration.mjs+++ b/packages/cli/api/integration/validate-integration.mjs@@ -1,7 +1,8 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * @file Programmatic API for `astryx validate-integration`.+ * @file Integration structure validation for+ * `astryx doctor integration validate`.** Validates exactly ONE integration package at a time and reports findings* using the AstryxIntegrationIssue model@@ -15,7 +16,7 @@** Both return a { found, name, version, manifestFile, issues } result. `found`* is false only for the no-manifest local case, which is guidance (not an- * error) so `validate-integration` can stay exit-0 in a non-integration dir.+ * error) so the Doctor check stays exit-0 in a non-integration dir.** The on-disk contribution validators themselves (roots + codemods/templates/* components/docs, behind `validateLoadedIntegration`) live in@@ -58,6 +59,7 @@ export {validateLoadedIntegration};* @property {string} [version] Integration package version.* @property {string} [manifestFile] Absolute path to the loaded manifest.* @property {Issue[]} issues+ * @property {import('../../foundation/integrations/integrations.mjs').LoadedIntegration} [integration]*//**@@ -76,7 +78,6 @@ function findNearestPackageJson(cwd) {}}-/*** Validate a single integration given its package directory and identity.* Shared core for the local and installed entry points.@@ -171,6 +172,7 @@ async function validateAtPackageDir(packageDir, identity) {__packageDir: packageDir,__manifestFile: manifestFile,};+ result.integration = loaded;// Roots + contribution checks are shared with validateLoadedIntegration so// the everyday-command nudge runs the exact same validators.@@ -283,8 +285,8 @@ export async function validateIntegration(pkg, options = {}) {return {type: 'integration.validate',data: {- name: result.found ? result.name ?? null : null,- version: result.found ? result.version ?? null : null,+ name: result.found ? (result.name ?? null) : null,+ version: result.found ? (result.version ?? null) : null,issues: result.issues,},};diff --git a/packages/cli/api/integration/validate-integration.type.mjs b/packages/cli/api/integration/validate-integration.type.mjsindex 887ceb995b..5c4a5b8bdd 100644--- a/packages/cli/api/integration/validate-integration.type.mjs+++ b/packages/cli/api/integration/validate-integration.type.mjs@@ -1,10 +1,9 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * @file Colocated types for the `validate-integration` command — source of truth- * for its options + response. `AstryxIntegrationIssue` stays shared in- * types/integration.d.ts (it's not command-owned). Re-exported by- * types/validate-integration.d.ts so the public surface resolves the same names.+ * @file Colocated types for `doctor integration validate` structure checks.+ * `AstryxIntegrationIssue` stays shared in `foundation/integrations/issue.ts`;+ * the generated public API surface re-exports these response types.*//**@@ -32,7 +31,7 @@*//**- * `astryx --json validate-integration [package]`.+ * `astryx --json doctor integration validate [package]`.* @typedef {object} ValidateIntegrationResponse* @property {'integration.validate'} type* @property {{name: string | null, version: string | null, issues: import('../../foundation/integrations/issue').AstryxIntegrationIssue[]}} datadiff --git a/packages/cli/api/integration/validateIntegration.doc.mjs b/packages/cli/api/integration/validateIntegration.doc.mjsindex fcdd9722a2..dfc2a6208d 100644--- a/packages/cli/api/integration/validateIntegration.doc.mjs+++ b/packages/cli/api/integration/validateIntegration.doc.mjs@@ -1,7 +1,7 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * @file FunctionDoc for `validateIntegration()` / `astryx validate-integration`.+ * @file FunctionDoc for `validateIntegration()` / `astryx doctor integration validate`.* Colocated with the API function it documents; the shape source of truth stays* in `validate-integration.type.mjs`.* @position packages/cli/api/integration — function documentation@@ -58,6 +58,6 @@ export const doc = {code: "await validateIntegration('@acme/astryx-integration');",},],- command: 'validate-integration',- related: ['summarizeIssues', 'doctor', 'upgrade'],+ command: 'doctor integration validate',+ related: ['summarizeIssues', 'doctor integration templates', 'upgrade'],};diff --git a/packages/cli/api/template/template.mjs b/packages/cli/api/template/template.mjsindex a672be9171..36459bc727 100644--- a/packages/cli/api/template/template.mjs+++ b/packages/cli/api/template/template.mjs@@ -8,7 +8,7 @@* the requested one, and routes to a leaf (list/show/skeleton/copy/cdn). The shared* discovery/IO + cross-command helpers live in `foundation/discovery/template-adapter.mjs` and are* RE-EXPORTED here so external import paths (`api/template/template.mjs`) —- * used by component, layout, search, init, discover, validate-integration, and+ * used by component, layout, search, init, discover, Doctor integration, and* lib/project — keep resolving unchanged.** @position api/template — the template dispatcher + barrel; leaves live under@@ -32,6 +32,7 @@ export {discoverAll,discoverAll as discoverTemplates,discoverAllWithErrors,+ discoverCoreTemplates,discoverIntegrationTemplatesForOne,stripTemplateAssetRefs,listTemplates,diff --git a/packages/cli/assets/docs/cli-integrations.doc.mjs b/packages/cli/assets/docs/cli-integrations.doc.mjsindex 5f550317f5..4d93eba18c 100644--- a/packages/cli/assets/docs/cli-integrations.doc.mjs+++ b/packages/cli/assets/docs/cli-integrations.doc.mjs@@ -69,6 +69,10 @@ export const docs = {type: 'prose',text: 'Export your components from your library however you like, and consumers still import them from your package. For each component the CLI should document, ship a `.doc.{ts,mjs,js}` file with the same stem, for example `AcmeCarousel.tsx` alongside `AcmeCarousel.doc.ts`.',},+ {+ type: 'prose',+ text: 'Component names are package-aware. If an integration name matches Core, unqualified lookup fails closed instead of choosing one. Run `astryx doctor integration components <package>` before publishing: it recommends renaming and prints the exact `--package` command when the overlap is intentional.',+ },{type: 'code',lang: 'typescript',@@ -84,6 +88,10 @@ export const docs = {type: 'prose',text: 'Templates are usually not exported from the package directly. Instead, consumers browse them through the CLI and materialize them into their app. Define a template as a plain object stamped with `type: \'page\'` (full pages) or `type: \'block\'` (smaller chunks) in a `.template.{ts,mjs,js}` file next to the source, for example `AcmeLandingPage.tsx` and `AcmeLandingPage.template.ts`.',},+ {+ type: 'prose',+ text: 'A template id is its source-relative path with the metadata suffix removed; the display `name` is not its identity and may repeat. If an integration id matches a Core id, unqualified lookup fails closed instead of choosing one. Run `astryx doctor integration templates <package>` before publishing: it recommends renaming, but an intentional overlap is allowed when callers always pass `--package <package>`.',+ },{type: 'code',lang: 'typescript',@@ -143,6 +151,7 @@ export const docs = {"A name that collides with an existing topic and declares neither `replaces` nor `extends` is an error, not a silent override; the CLI will not guess which one you meant.",'`replaces` and `extends` are exclusive: a topic either takes another\'s place or merges onto it.','Two integrations replacing one topic is a warning, and the one configured later in `astryx.config` wins.',+ '`astryx doctor integration docs <package>` classifies Core overlaps as intentional replacements, intentional extensions, or accidental same-name conflicts.',],},],@@ -226,7 +235,7 @@ export const docs = {},{type: 'prose',- text: 'To inspect problems, run `astryx validate-integration <package>` for a detailed report on one package, or `astryx doctor` for an overall health check of the setup.',+ text: 'To inspect problems, run `astryx doctor integration validate <package>` for structure, then use `templates`, `components`, or `docs` under the same `astryx doctor integration` group to check Core identity overlaps before publishing. Bare `astryx doctor` checks overall project health.',},],},diff --git a/packages/cli/authoring/integration/integration.doc.mjs b/packages/cli/authoring/integration/integration.doc.mjsindex 653102e879..da40b7fd0d 100644--- a/packages/cli/authoring/integration/integration.doc.mjs+++ b/packages/cli/authoring/integration/integration.doc.mjs@@ -95,7 +95,7 @@ export const doc = {{type: 'prose',text:- 'Validate a manifest with `astryx validate-integration`. It is checked ' ++ 'Validate a manifest with `astryx doctor integration validate`. It is checked ' +'at the load boundary (parseIntegration): a known field of the wrong ' +'type is an error, and issuesUrl must be a valid URL. A field this CLI ' +'does not know is ignored with a warning rather than rejected, so a ' +diff --git a/packages/cli/clients/cli/commands/component/index.mjs b/packages/cli/clients/cli/commands/component/index.mjsindex cdfca5ef93..5cc2cb195f 100644--- a/packages/cli/clients/cli/commands/component/index.mjs+++ b/packages/cli/clients/cli/commands/component/index.mjs@@ -109,7 +109,7 @@ export function registerComponent(program) {// Non-blocking nudge: if any configured integration has validation// issues, print one compact line to stderr pointing at- // validate-integration. Best-effort; suppressed in --json mode.+ // doctor integration validate. Best-effort; suppressed in --json mode.try {const project = await Project.load(process.cwd());await warnOnIntegrationIssues(project.loadedIntegrations, {json});diff --git a/packages/cli/clients/cli/commands/discover.broken-integration.test.mjs b/packages/cli/clients/cli/commands/discover.broken-integration.test.mjsindex 21f5ece510..7068c73077 100644--- a/packages/cli/clients/cli/commands/discover.broken-integration.test.mjs+++ b/packages/cli/clients/cli/commands/discover.broken-integration.test.mjs@@ -70,7 +70,7 @@ describe('astryx discover with a manifest that fails to load', () => {expect(status).toBe(0);expect(stderr).toContain('Warning: @test/broken has 1 integration issue(s). ' +- 'Run: astryx validate-integration @test/broken',+ 'Run: astryx doctor integration validate @test/broken',);expect(stdout).not.toContain('No integrations configured.');expect(stdout).toContain('No external components found in configured integrations.');@@ -102,7 +102,7 @@ describe('astryx search with a manifest that fails to load', () => {expect(status).toBe(0);expect(stderr).toContain('Warning: @test/broken has 1 integration issue(s). ' +- 'Run: astryx validate-integration @test/broken',+ 'Run: astryx doctor integration validate @test/broken',);const asJson = await runCli(['search', 'button', '--json'], {cwd: project});diff --git a/packages/cli/clients/cli/commands/discover.mjs b/packages/cli/clients/cli/commands/discover.mjsindex b15797c53a..d2da8e29ca 100644--- a/packages/cli/clients/cli/commands/discover.mjs+++ b/packages/cli/clients/cli/commands/discover.mjs@@ -80,7 +80,7 @@ export function registerDiscover(program) {// Non-blocking nudge: if any configured integration has validation// issues, print one compact line to stderr pointing at- // validate-integration. Best-effort; suppressed in --json mode.+ // doctor integration validate. Best-effort; suppressed in --json mode.try {const project = await Project.load(process.cwd());await warnOnIntegrationIssues(project.loadedIntegrations, {json});diff --git a/packages/cli/clients/cli/commands/doctor-integration-components.doc.mjs b/packages/cli/clients/cli/commands/doctor-integration-components.doc.mjsnew file mode 100644index 0000000000..1f63ff3fa8--- /dev/null+++ b/packages/cli/clients/cli/commands/doctor-integration-components.doc.mjs@@ -0,0 +1,30 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @file CommandDoc for `astryx doctor integration components`. */++/** @type {import('@astryxdesign/cli/authoring').CommandDoc} */+export const doc = {+ type: 'command',+ name: 'doctor integration components',+ displayName: 'astryx doctor integration components',+ namespace: 'cli',+ summary: 'Warn when integration component names conflict with Core',+ description:+ 'Compares one local or installed integration with Core component names. A ' ++ 'conflict is allowed and exits successfully, but the report recommends ' ++ 'renaming and gives the exact --package command for an intentional overlap.',+ fn: 'integrationComponentConflicts',+ args: [{name: 'package', param: 'pkg', required: false}],+ examples: [+ {label: 'Check the local integration', cli: 'astryx doctor integration components'},+ {+ label: 'Check an installed integration',+ cli: 'astryx doctor integration components @acme/widgets --json',+ },+ ],+ exitCodes: [+ {code: 0, when: 'the check completed; component conflicts are warnings'},+ {code: 1, when: 'the integration is invalid or Core cannot be resolved'},+ ],+ related: ['doctor integration templates', 'component'],+};diff --git a/packages/cli/clients/cli/commands/doctor-integration-docs.doc.mjs b/packages/cli/clients/cli/commands/doctor-integration-docs.doc.mjsnew file mode 100644index 0000000000..08f791558c--- /dev/null+++ b/packages/cli/clients/cli/commands/doctor-integration-docs.doc.mjs@@ -0,0 +1,30 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @file CommandDoc for `astryx doctor integration docs`. */++/** @type {import('@astryxdesign/cli/authoring').CommandDoc} */+export const doc = {+ type: 'command',+ name: 'doctor integration docs',+ displayName: 'astryx doctor integration docs',+ namespace: 'cli',+ summary: 'Classify integration doc overlaps with Core topics',+ description:+ 'Reports intentional Core topic replacements and extensions as information. ' ++ 'A same-name topic without `replaces` or `extends` is an accidental conflict ' ++ 'and fails until the author declares the relationship or renames it.',+ fn: 'integrationDocConflicts',+ args: [{name: 'package', param: 'pkg', required: false}],+ examples: [+ {label: 'Check the local integration', cli: 'astryx doctor integration docs'},+ {+ label: 'Check an installed integration',+ cli: 'astryx doctor integration docs @acme/widgets --json',+ },+ ],+ exitCodes: [+ {code: 0, when: 'all Core overlaps are explicitly declared or no overlap exists'},+ {code: 1, when: 'an overlap is accidental or the integration docs are invalid'},+ ],+ related: ['doctor integration validate', 'docs'],+};diff --git a/packages/cli/clients/cli/commands/doctor-integration-templates.doc.mjs b/packages/cli/clients/cli/commands/doctor-integration-templates.doc.mjsnew file mode 100644index 0000000000..b74408a7a5--- /dev/null+++ b/packages/cli/clients/cli/commands/doctor-integration-templates.doc.mjs@@ -0,0 +1,36 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file CommandDoc for `astryx doctor integration templates`.+ */++/** @type {import('@astryxdesign/cli/authoring').CommandDoc} */+export const doc = {+ type: 'command',+ name: 'doctor integration templates',+ displayName: 'astryx doctor integration templates',+ namespace: 'cli',+ summary: 'Warn when integration template ids conflict with Core',+ description:+ 'Compares one local or installed integration with the built-in Core page and ' ++ 'block template ids. A conflict is allowed and exits successfully, but the ' ++ 'report recommends renaming and gives the exact --package command required ' ++ 'to select the integration template when the overlap is intentional.',+ fn: 'integrationTemplateConflicts',+ args: [{name: 'package', param: 'pkg', required: false}],+ examples: [+ {+ label: 'Check the local integration',+ cli: 'astryx doctor integration templates',+ },+ {+ label: 'Check an installed integration',+ cli: 'astryx doctor integration templates @acme/widgets --json',+ },+ ],+ exitCodes: [+ {code: 0, when: 'the check completed; template conflicts are warnings'},+ {code: 1, when: 'the integration or one of its templates is invalid'},+ ],+ related: ['doctor integration validate', 'template'],+};diff --git a/packages/cli/clients/cli/commands/doctor-integration-validate.doc.mjs b/packages/cli/clients/cli/commands/doctor-integration-validate.doc.mjsnew file mode 100644index 0000000000..1d048d758d--- /dev/null+++ b/packages/cli/clients/cli/commands/doctor-integration-validate.doc.mjs@@ -0,0 +1,35 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file CommandDoc for `astryx doctor integration validate`.+ */++/** @type {import('@astryxdesign/cli/authoring').CommandDoc} */+export const doc = {+ type: 'command',+ name: 'doctor integration validate',+ displayName: 'astryx doctor integration validate',+ namespace: 'cli',+ summary: 'Validate an integration manifest and its contributions',+ description:+ 'Validates one integration at a time: the local package rooted at cwd, or an ' ++ 'installed package resolved by name. It schema-checks the manifest, verifies ' ++ 'every declared contribution root, and reports every finding. Safe as a CI gate.',+ fn: 'validateIntegration',+ args: [{name: 'package', param: 'pkg', required: false}],+ examples: [+ {+ label: 'Validate the local package',+ cli: 'astryx doctor integration validate',+ },+ {+ label: 'Validate an installed package',+ cli: 'astryx doctor integration validate @acme/widgets --json',+ },+ ],+ exitCodes: [+ {code: 0, when: 'no error-severity issues (warnings are allowed)'},+ {code: 1, when: 'one or more error-severity issues'},+ ],+ related: ['doctor integration templates', 'template'],+};diff --git a/packages/cli/clients/cli/commands/doctor-integration.doc.mjs b/packages/cli/clients/cli/commands/doctor-integration.doc.mjsnew file mode 100644index 0000000000..e0090fe108--- /dev/null+++ b/packages/cli/clients/cli/commands/doctor-integration.doc.mjs@@ -0,0 +1,34 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file CommandDoc for the `astryx doctor integration` authoring-check group.+ */++/** @type {import('@astryxdesign/cli/authoring').CommandDoc} */+export const doc = {+ type: 'command',+ name: 'doctor integration',+ displayName: 'astryx doctor integration',+ namespace: 'cli',+ summary: 'Check an integration package while authoring it',+ description:+ 'The integration-authoring diagnostics group. Validate a manifest and all ' ++ 'contributions with `validate`, or check templates, components, and docs ' ++ 'against built-in Core identities before publishing.',+ subcommands: ['validate', 'templates', 'components', 'docs'],+ examples: [+ {+ label: 'Validate a local integration',+ cli: 'astryx doctor integration validate',+ },+ {+ label: 'Check template ids against Core',+ cli: 'astryx doctor integration templates',+ },+ ],+ exitCodes: [+ {code: 0, when: 'help is shown or the selected check has no errors'},+ {code: 1, when: 'the selected check reports an error'},+ ],+ related: ['doctor', 'template'],+};diff --git a/packages/cli/clients/cli/commands/doctor-integration.test.mjs b/packages/cli/clients/cli/commands/doctor-integration.test.mjsnew file mode 100644index 0000000000..d1f1af075a--- /dev/null+++ b/packages/cli/clients/cli/commands/doctor-integration.test.mjs@@ -0,0 +1,360 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Command-level coverage for `astryx doctor integration` authoring checks.+ */++import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {Command} from 'commander';+import {discoverCoreTemplates} from '../../../foundation/discovery/template-adapter.mjs';+import {discoverOwnedComponents} from '../../../foundation/discovery/component-discovery.mjs';+import {discoverBuiltinTopics} from '../../../foundation/discovery/docs-discovery.mjs';+import {findCoreDir} from '../../../foundation/fs/paths.mjs';+import {registerDoctor} from './doctor.mjs';++let tmpDir;+let previousCwd;+let previousExitCode;+let logCalls;++function createProgram() {+ const program = new Command();+ program.exitOverride();+ program.option('--json', 'Output as typed JSON');+ registerDoctor(program);+ return program;+}++function writeIntegration({+ id,+ name = 'Integration template',+ missingRoot = false,+}) {+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({name: '@acme/widgets', version: '1.2.3'}),+ );+ fs.writeFileSync(+ path.join(tmpDir, 'astryx.integration.mjs'),+ `export default {templates: '${missingRoot ? './missing' : './templates'}'};\n`,+ );+ if (missingRoot || id == null) return;+ const stem = path.join(tmpDir, 'templates', id);+ fs.mkdirSync(path.dirname(stem), {recursive: true});+ fs.writeFileSync(+ `${stem}.template.mjs`,+ `export default {type: 'page', name: ${JSON.stringify(name)}, description: 'fixture'};\n`,+ );+ fs.writeFileSync(+ `${stem}.tsx`,+ 'export default function Fixture() { return null; }\n',+ );+}++function writeComponentIntegration(componentName) {+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({name: '@acme/widgets', version: '1.2.3'}),+ );+ fs.writeFileSync(+ path.join(tmpDir, 'astryx.integration.mjs'),+ `export default {components: './components'};\n`,+ );+ fs.mkdirSync(path.join(tmpDir, 'components'), {recursive: true});+ fs.writeFileSync(+ path.join(tmpDir, 'components', `${componentName}.doc.mjs`),+ `export default {type: 'component', name: ${JSON.stringify(componentName)}, displayName: ${JSON.stringify(componentName)}, description: 'Fixture component.', props: []};\n`,+ );+ fs.writeFileSync(+ path.join(tmpDir, 'components', `${componentName}.tsx`),+ 'export default function Fixture() { return null; }\n',+ );+}++function writeDocIntegration({name, replaces, extendsTopic}) {+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({name: '@acme/widgets', version: '1.2.3'}),+ );+ fs.writeFileSync(+ path.join(tmpDir, 'astryx.integration.mjs'),+ `export default {docs: './docs'};\n`,+ );+ fs.mkdirSync(path.join(tmpDir, 'docs'), {recursive: true});+ const relationship =+ replaces != null+ ? `, replaces: ${JSON.stringify(replaces)}`+ : extendsTopic != null+ ? `, extends: ${JSON.stringify(extendsTopic)}`+ : '';+ fs.writeFileSync(+ path.join(tmpDir, 'docs', `${name}.doc.mjs`),+ `export default {type: 'generic', name: ${JSON.stringify(name)}, title: 'Fixture', description: 'Fixture topic.'${relationship}, sections: [{title: 'Overview', content: [{type: 'prose', text: 'Fixture.'}]}]};\n`,+ );+}++beforeEach(() => {+ previousCwd = process.cwd();+ previousExitCode = process.exitCode;+ process.exitCode = undefined;+ tmpDir = fs.mkdtempSync(+ path.join(previousCwd, '.astryx-doctor-integration-'),+ );+ logCalls = [];+ vi.spyOn(console, 'log').mockImplementation((...args) => {+ logCalls.push(args.join(' '));+ });+ vi.spyOn(console, 'error').mockImplementation(() => {});+});++afterEach(() => {+ process.chdir(previousCwd);+ process.exitCode = previousExitCode;+ fs.rmSync(tmpDir, {recursive: true, force: true});+ vi.restoreAllMocks();+});++describe('doctor integration — command', () => {+ it('prints the authoring subcommands when invoked without a leaf', async () => {+ const writes = [];+ vi.spyOn(process.stdout, 'write').mockImplementation(chunk => {+ writes.push(String(chunk));+ return true;+ });++ await createProgram().parseAsync(['node', 'astryx', 'doctor', 'integration']);++ const output = writes.join('');+ expect(output).toContain('validate [package]');+ expect(output).toContain('templates [package]');+ expect(output).toContain('components [package]');+ expect(output).toContain('docs [package]');+ expect(process.exitCode).toBeUndefined();+ });++ it('templates explains how to check an installed package when no local manifest exists', async () => {+ fs.writeFileSync(path.join(tmpDir, 'package.json'), JSON.stringify({name: 'plain'}));+ process.chdir(tmpDir);++ await createProgram().parseAsync([+ 'node',+ 'astryx',+ 'doctor',+ 'integration',+ 'templates',+ ]);++ expect(logCalls.join('\n')).toContain(+ 'astryx doctor integration templates <package>',+ );+ expect(process.exitCode).toBeUndefined();+ });++ it('validate keeps the integration.validate JSON contract', async () => {+ writeIntegration({id: 'integration-only'});+ process.chdir(tmpDir);++ await createProgram().parseAsync([+ 'node',+ 'astryx',+ '--json',+ 'doctor',+ 'integration',+ 'validate',+ ]);++ const parsed = JSON.parse(logCalls.join('\n'));+ expect(parsed.type).toBe('integration.validate');+ expect(parsed.data.name).toBe('@acme/widgets');+ expect(parsed.data.issues).toEqual([]);+ expect(process.exitCode).toBeUndefined();+ });++ it('templates warns on a Core id and writes the exact --package command', async () => {+ const [core] = await discoverCoreTemplates();+ expect(core).toBeDefined();+ writeIntegration({id: core.dirName});+ process.chdir(tmpDir);++ await createProgram().parseAsync([+ 'node',+ 'astryx',+ 'doctor',+ 'integration',+ 'templates',+ ]);++ const output = logCalls.join('\n');+ expect(output).toContain('[warn]');+ expect(output).toContain(core.dirName);+ expect(output).toContain('Consider renaming');+ expect(output).toContain(`--package @acme/widgets`);+ expect(process.exitCode).toBeUndefined();+ });++ it('templates exposes conflicts as structured JSON warnings', async () => {+ const [core] = await discoverCoreTemplates();+ expect(core).toBeDefined();+ writeIntegration({id: core.dirName});+ process.chdir(tmpDir);++ await createProgram().parseAsync([+ 'node',+ 'astryx',+ '--json',+ 'doctor',+ 'integration',+ 'templates',+ ]);++ const parsed = JSON.parse(logCalls.join('\n'));+ expect(parsed.type).toBe('integration.template-conflicts');+ expect(parsed.data.conflicts[0]).toMatchObject({+ id: core.dirName,+ severity: 'warning',+ integrationPackage: '@acme/widgets',+ });+ expect(parsed.data.conflicts[0].command).toContain(+ `--package @acme/widgets`,+ );+ expect(process.exitCode).toBeUndefined();+ });++ it('templates exits 1 when structural errors prevent a trustworthy check', async () => {+ writeIntegration({missingRoot: true});+ process.chdir(tmpDir);++ await createProgram().parseAsync([+ 'node',+ 'astryx',+ '--json',+ 'doctor',+ 'integration',+ 'templates',+ ]);++ const parsed = JSON.parse(logCalls.join('\n'));+ expect(parsed.data.conflicts).toEqual([]);+ expect(+ parsed.data.issues.some(issue => issue.code === 'missing_root'),+ ).toBe(true);+ expect(process.exitCode).toBe(1);+ });++ it('components warns with the exact package-qualified command', async () => {+ const coreDir = findCoreDir(tmpDir);+ expect(coreDir).not.toBeNull();+ const [core] = discoverOwnedComponents(coreDir, []);+ writeComponentIntegration(core.name);+ process.chdir(tmpDir);++ await createProgram().parseAsync([+ 'node',+ 'astryx',+ 'doctor',+ 'integration',+ 'components',+ ]);++ const output = logCalls.join('\n');+ expect(output).toContain('[warn]');+ expect(output).toContain(core.name);+ expect(output).toContain(+ `component ${core.name} --package @acme/widgets`,+ );+ expect(process.exitCode).toBeUndefined();+ });++ it('components exposes conflicts as structured JSON warnings', async () => {+ const coreDir = findCoreDir(tmpDir);+ expect(coreDir).not.toBeNull();+ const [core] = discoverOwnedComponents(coreDir, []);+ writeComponentIntegration(core.name);+ process.chdir(tmpDir);++ await createProgram().parseAsync([+ 'node',+ 'astryx',+ '--json',+ 'doctor',+ 'integration',+ 'components',+ ]);++ const parsed = JSON.parse(logCalls.join('\n'));+ expect(parsed.type).toBe('integration.component-conflicts');+ expect(parsed.data.conflicts[0]).toMatchObject({+ name: core.name,+ severity: 'warning',+ integrationPackage: '@acme/widgets',+ });+ expect(parsed.data.conflicts[0].command).toContain(+ `--package @acme/widgets`,+ );+ expect(process.exitCode).toBeUndefined();+ });++ it('docs reports an intentional replacement as info', async () => {+ const [coreTopic] = Object.keys(discoverBuiltinTopics());+ writeDocIntegration({name: 'acme-setup', replaces: coreTopic});+ process.chdir(tmpDir);++ await createProgram().parseAsync([+ 'node',+ 'astryx',+ 'doctor',+ 'integration',+ 'docs',+ ]);++ const output = logCalls.join('\n');+ expect(output).toContain('[info]');+ expect(output).toContain('Intentional override');+ expect(process.exitCode).toBeUndefined();+ });++ it('docs reports an intentional extension as info', async () => {+ const [coreTopic] = Object.keys(discoverBuiltinTopics());+ writeDocIntegration({name: 'acme-extra', extendsTopic: coreTopic});+ process.chdir(tmpDir);++ await createProgram().parseAsync([+ 'node',+ 'astryx',+ 'doctor',+ 'integration',+ 'docs',+ ]);++ const output = logCalls.join('\n');+ expect(output).toContain('[info]');+ expect(output).toContain('Intentional extension');+ expect(process.exitCode).toBeUndefined();+ });++ it('docs exits 1 for an accidental same-name Core topic', async () => {+ const [coreTopic] = Object.keys(discoverBuiltinTopics());+ writeDocIntegration({name: coreTopic});+ process.chdir(tmpDir);++ await createProgram().parseAsync([+ 'node',+ 'astryx',+ '--json',+ 'doctor',+ 'integration',+ 'docs',+ ]);++ const parsed = JSON.parse(logCalls.join('\n'));+ expect(parsed.type).toBe('integration.doc-conflicts');+ expect(parsed.data.findings[0]).toMatchObject({+ topic: coreTopic,+ severity: 'error',+ relationship: 'accidental',+ });+ expect(process.exitCode).toBe(1);+ });+});diff --git a/packages/cli/clients/cli/commands/doctor.doc.mjs b/packages/cli/clients/cli/commands/doctor.doc.mjsindex 397a545601..d717b33049 100644--- a/packages/cli/clients/cli/commands/doctor.doc.mjs+++ b/packages/cli/clients/cli/commands/doctor.doc.mjs@@ -15,13 +15,22 @@ export const doc = {namespace: 'cli',summary: 'Diagnose your XDS setup and report problems with fixes',description:- 'Runs read-only diagnostics: Node version, @astryxdesign/core install and version ' +- 'alignment, installed themes, config validity, agent docs, and the package manager, ' +- 'and reports pass/warn/fail with an actionable fix for each problem. Safe as a CI gate.',+ 'Runs read-only project diagnostics by default: Node version, @astryxdesign/core ' ++ 'install and version alignment, themes, config, agent docs, and package manager. ' ++ 'The `integration` subcommands provide authoring checks for one integration package.',fn: 'doctor',+ subcommands: ['integration'],examples: [- {label: 'Run diagnostics', cli: 'astryx doctor'},- {label: 'Machine-readable report', cli: 'astryx doctor --json'},+ {label: 'Run project diagnostics', cli: 'astryx doctor'},+ {label: 'Machine-readable project report', cli: 'astryx doctor --json'},+ {+ label: 'Validate an integration',+ cli: 'astryx doctor integration validate @acme/widgets',+ },+ {+ label: 'Check template ids against Core',+ cli: 'astryx doctor integration templates @acme/widgets',+ },],exitCodes: [{code: 0, when: 'no checks failed (warnings are allowed)'},diff --git a/packages/cli/clients/cli/commands/doctor.mjs b/packages/cli/clients/cli/commands/doctor.mjsindex 58aa839812..34d24411a4 100644--- a/packages/cli/clients/cli/commands/doctor.mjs+++ b/packages/cli/clients/cli/commands/doctor.mjs@@ -1,28 +1,43 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * @file `astryx doctor` command — diagnose a project + environment and report- * PASS / WARN / FAIL for each check with an actionable fix.- *- * Designed to be usable both by humans (clean monochrome checklist) and by- * AI agents / CI (`--json`). Exit code is the contract: 0 when there are no- * FAILs (warnings are fine), 1 when any check FAILs — so `astryx doctor` works- * as a CI gate.+ * @file `astryx doctor` project health and integration-authoring diagnostics.+ * Human output uses plain stable tokens; every leaf also has a typed JSON+ * response. Exit 1 means a check found an error, while warnings remain exit 0.*/import {runChecks} from '../../../api/doctor/doctor.mjs';+import {+ integrationComponentConflicts,+ integrationDocConflicts,+ integrationTemplateConflicts,+} from '../../../api/integration/authoring-checks.mjs';+import {+ summarizeIssues,+ validateIntegration,+} from '../../../api/integration/validate-integration.mjs';import {jsonOut} from '../../../foundation/response/json.mjs';import {emit, section, records, text} from '../formatters/index.mjs';import {defineCommand} from '../lib/define-command.mjs';import {doc as doctorCommand} from './doctor.doc.mjs';+import {doc as doctorIntegrationGroup} from './doctor-integration.doc.mjs';+import {doc as doctorIntegrationValidateCommand} from './doctor-integration-validate.doc.mjs';+import {doc as doctorIntegrationTemplatesCommand} from './doctor-integration-templates.doc.mjs';+import {doc as doctorIntegrationComponentsCommand} from './doctor-integration-components.doc.mjs';+import {doc as doctorIntegrationDocsCommand} from './doctor-integration-docs.doc.mjs';import {doc as doctorFn} from '../../../api/doctor/doctor.doc.mjs';+import {doc as validateIntegrationFn} from '../../../api/integration/validateIntegration.doc.mjs';+import {doc as integrationTemplateConflictsFn} from '../../../api/integration/integrationTemplateConflicts.doc.mjs';+import {doc as integrationComponentConflictsFn} from '../../../api/integration/integrationComponentConflicts.doc.mjs';+import {doc as integrationDocConflictsFn} from '../../../api/integration/integrationDocConflicts.doc.mjs';import {NO_RESULT_SET} from '../../../foundation/debug/index.mjs';-/** Status -> ASCII token (plain, matching the rest of the CLI). */const STATUS = {pass: '[ok]',warn: '[warn]',+ warning: '[warn]',fail: '[fail]',+ error: '[fail]',info: '[info]',};@@ -31,10 +46,12 @@ function statusToken(status) {return STATUS[/** @type {keyof typeof STATUS} */ (status)] ?? status;}+/** @param {{name: string | null, version: string | null}} data */+function integrationLabel(data) {+ return data.version != null ? `${data.name}@${data.version}` : data.name;+}+/**- * Render the report as a human-readable checklist. Each check is a record whose- * fields mirror the JSON (status/label/message/fix); the status glyph is an- * ASCII token so the output is byte-deterministic in any terminal.* @param {import('../../../api/doctor/doctor.mjs').DoctorReport} report*/function printHuman(report) {@@ -63,37 +80,245 @@ function printHuman(report) {}/**- * Register the `astryx doctor` command.+ * @param {Array<{code: string, severity: string, message: string}>} issues+ * @returns {import('../formatters/index.mjs').Block[]}+ */+function issueBlocks(issues) {+ if (issues.length === 0) return [];+ return [+ section('Integration issues'),+ records(issues, {+ fields: ['severity', 'code', 'message'],+ format: {severity: statusToken},+ }),+ ];+}++/**+ * @param {import('../../../api/integration/validate-integration.type.mjs').ValidateIntegrationResponse['data']} data+ */+function printIntegrationValidation(data) {+ const {warnings, errors} = summarizeIssues(data.issues);+ emit(+ section(+ `Validating integration: ${integrationLabel(data) ?? '(local package)'}`,+ ),+ ...(data.issues.length > 0+ ? [+ records(data.issues, {+ fields: ['severity', 'code', 'message'],+ format: {severity: statusToken},+ }),+ ]+ : [text('[ok] No integration issues found.')]),+ text(+ `Summary: ${errors} error${errors === 1 ? '' : 's'}, ` ++ `${warnings} warning${warnings === 1 ? '' : 's'}`,+ ),+ );+}++/**+ * @param {import('../../../api/integration/authoring-checks.type.mjs').IntegrationTemplateConflictResponse['data']} data+ */+function printTemplateConflicts(data) {+ const output = [+ section(+ `Checking integration templates: ${integrationLabel(data) ?? '(local package)'}`,+ ),+ ...issueBlocks(data.issues),+ ];+ if (data.conflicts.length === 0) {+ output.push(text('[ok] No template ids conflict with Core.'));+ } else {+ output.push(+ records(data.conflicts, {+ fields: [+ 'severity',+ 'id',+ 'integrationPackage',+ 'integrationType',+ 'integrationName',+ 'message',+ 'command',+ ],+ format: {severity: statusToken},+ }),+ text(+ `${data.conflicts.length} Core template conflict(s). ` ++ 'Renaming is recommended but optional; keep the package-qualified command if the overlap is intentional.',+ ),+ );+ }+ emit(...output);+}++/**+ * @param {import('../../../api/integration/authoring-checks.type.mjs').IntegrationComponentConflictResponse['data']} data+ */+function printComponentConflicts(data) {+ const output = [+ section(+ `Checking integration components: ${integrationLabel(data) ?? '(local package)'}`,+ ),+ ...issueBlocks(data.issues),+ ];+ if (data.conflicts.length === 0) {+ output.push(text('[ok] No component names conflict with Core.'));+ } else {+ output.push(+ records(data.conflicts, {+ fields: ['severity', 'name', 'integrationPackage', 'message', 'command'],+ format: {severity: statusToken},+ }),+ text(+ `${data.conflicts.length} Core component conflict(s). ` ++ 'Renaming is recommended but optional; keep the package-qualified command if the overlap is intentional.',+ ),+ );+ }+ emit(...output);+}++/**+ * @param {import('../../../api/integration/authoring-checks.type.mjs').IntegrationDocConflictResponse['data']} data+ */+function printDocConflicts(data) {+ const output = [+ section(+ `Checking integration docs: ${integrationLabel(data) ?? '(local package)'}`,+ ),+ ...issueBlocks(data.issues),+ ];+ if (data.findings.length === 0) {+ output.push(text('[ok] No doc topics overlap with Core.'));+ } else {+ output.push(+ records(data.findings, {+ fields: ['severity', 'topic', 'relationship', 'coreTopic', 'message'],+ format: {severity: statusToken},+ }),+ );+ }+ emit(...output);+}++/** @param {import('commander').Command} program */+async function runProjectDoctor(program) {+ const report = await runChecks();+ if (program.opts().json) jsonOut({type: 'doctor', data: report});+ else printHuman(report);+ if (report.summary.fail > 0) process.exitCode = 1;+ return NO_RESULT_SET;+}++/**+ * @param {import('commander').Command} program+ * @param {string | undefined} pkg+ */+async function runIntegrationValidation(program, pkg) {+ const result = await validateIntegration(pkg);+ if (program.opts().json) jsonOut(result);+ else if (result.data.name === null) {+ emit(+ text(+ 'No astryx.integration.* found next to package.json. ' ++ 'To validate an installed integration: astryx doctor integration validate <package>',+ ),+ );+ } else printIntegrationValidation(result.data);+ if (summarizeIssues(result.data.issues).errors > 0) process.exitCode = 1;+ return NO_RESULT_SET;+}++/**+ * @param {import('commander').Command} program+ * @param {string | undefined} pkg+ * @param {'templates' | 'components' | 'docs'} kind+ */+async function runAuthoringCheck(program, pkg, kind) {+ const result =+ kind === 'templates'+ ? await integrationTemplateConflicts(pkg)+ : kind === 'components'+ ? await integrationComponentConflicts(pkg)+ : await integrationDocConflicts(pkg);++ if (program.opts().json) jsonOut(result);+ else if (result.data.name === null) {+ emit(+ text(+ 'No astryx.integration.* found next to package.json. ' ++ `To check an installed integration: astryx doctor integration ${kind} <package>`,+ ),+ );+ } else if (kind === 'templates') {+ printTemplateConflicts(+ /** @type {import('../../../api/integration/authoring-checks.type.mjs').IntegrationTemplateConflictResponse['data']} */ (+ result.data+ ),+ );+ } else if (kind === 'components') {+ printComponentConflicts(+ /** @type {import('../../../api/integration/authoring-checks.type.mjs').IntegrationComponentConflictResponse['data']} */ (+ result.data+ ),+ );+ } else {+ printDocConflicts(+ /** @type {import('../../../api/integration/authoring-checks.type.mjs').IntegrationDocConflictResponse['data']} */ (+ result.data+ ),+ );+ }++ const structuralErrors = summarizeIssues(result.data.issues).errors;+ const docErrors =+ result.type === 'integration.doc-conflicts'+ ? result.data.findings.filter(finding => finding.severity === 'error').length+ : 0;+ if (structuralErrors > 0 || docErrors > 0) process.exitCode = 1;+ return NO_RESULT_SET;+}++/**+ * Register `astryx doctor` and its integration-authoring leaves.* @param {import('commander').Command} program*/export function registerDoctor(program) {- defineCommand(program, doctorCommand, {+ const doctorCmd = defineCommand(program, doctorCommand, {fn: doctorFn,- action: async () => {- const json = program.opts().json || false;- const report = await runChecks();- const hasFailure = report.summary.fail > 0;-- if (json) {- jsonOut({type: 'doctor', data: report});- } else {- printHuman(report);- }-- // Exit code is the contract: any FAIL → exit 1. Warnings never fail.- if (hasFailure) {- process.exitCode = 1;- }-- // A diagnosis, not a lookup. The checks are a verdict on the project —- // counting them would say "doctor found 14 things", which is not what- // anyone means by a result. Read the summary counts from the report.- return NO_RESULT_SET;- },- }).addHelpText(+ action: async () => runProjectDoctor(program),+ });+ doctorCmd.addHelpText('after','\nExit code:\n' +' 0 no failures (warnings are allowed) — safe as a CI gate\n' +' 1 one or more checks failed\n',);++ /** @type {import('commander').Command} */+ let integrationCmd;+ integrationCmd = defineCommand(doctorCmd, doctorIntegrationGroup, {+ action: () => {+ integrationCmd.outputHelp();+ return NO_RESULT_SET;+ },+ });+ defineCommand(integrationCmd, doctorIntegrationValidateCommand, {+ fn: validateIntegrationFn,+ action: async pkg => runIntegrationValidation(program, pkg),+ });+ defineCommand(integrationCmd, doctorIntegrationTemplatesCommand, {+ fn: integrationTemplateConflictsFn,+ action: async pkg => runAuthoringCheck(program, pkg, 'templates'),+ });+ defineCommand(integrationCmd, doctorIntegrationComponentsCommand, {+ fn: integrationComponentConflictsFn,+ action: async pkg => runAuthoringCheck(program, pkg, 'components'),+ });+ defineCommand(integrationCmd, doctorIntegrationDocsCommand, {+ fn: integrationDocConflictsFn,+ action: async pkg => runAuthoringCheck(program, pkg, 'docs'),+ });}diff --git a/packages/cli/clients/cli/commands/layout.mjs b/packages/cli/clients/cli/commands/layout.mjsindex 777d689f4b..bfa705e525 100644--- a/packages/cli/clients/cli/commands/layout.mjs+++ b/packages/cli/clients/cli/commands/layout.mjs@@ -200,7 +200,7 @@ export function registerLayout(program) {// Exit code is the contract and must NOT depend on --json vs human: an// invalid (but parseable) layout exits 1 in BOTH modes so `layout check`// works as a CI gate / agent check without parsing stdout. Decide it- // before the JSON return (parity with doctor / validate-integration).+ // before the JSON return (parity with doctor integration validate).if (!result.data.valid) process.exitCode = 1;// A verdict on one expression: valid or not, with the errors that madediff --git a/packages/cli/clients/cli/commands/template.mjs b/packages/cli/clients/cli/commands/template.mjsindex 9b4eb4e7c1..fd363b573c 100644--- a/packages/cli/clients/cli/commands/template.mjs+++ b/packages/cli/clients/cli/commands/template.mjs@@ -86,7 +86,7 @@ export function registerTemplate(program) {// Non-blocking nudge: if any configured integration has validation// issues, print one compact line to stderr pointing at- // validate-integration. Best-effort; suppressed in --json mode.+ // doctor integration validate. Best-effort; suppressed in --json mode.try {const project = await Project.load(process.cwd());await warnOnIntegrationIssues(diff --git a/packages/cli/clients/cli/commands/validate-integration.doc.mjs b/packages/cli/clients/cli/commands/validate-integration.doc.mjsdeleted file mode 100644index 7dabd38576..0000000000--- a/packages/cli/clients/cli/commands/validate-integration.doc.mjs+++ /dev/null@@ -1,36 +0,0 @@-// Copyright (c) Meta Platforms, Inc. and affiliates.--/**- * @file CommandDoc for `astryx validate-integration`. The terminal binding of- * the `validateIntegration()` function (referenced via `fn`); its args/flags map- * to that function's params so a converter can build Commander config + --help- * from one source of truth.- * @position packages/cli/clients/cli/commands — command documentation- */--/** @type {import('@astryxdesign/cli/authoring').CommandDoc} */-export const doc = {- type: 'command',- name: 'validate-integration',- displayName: 'astryx validate-integration',- namespace: 'cli',- summary: 'Validate an Astryx integration package (manifest + contributions)',- description:- 'Validates ONE integration at a time: the local package rooted at cwd, or an ' +- 'installed package resolved by name, schema-checking its manifest, verifying each ' +- 'declared contribution root, and reporting every finding. Safe as a CI gate.',- fn: 'validateIntegration',- args: [{name: 'package', param: 'pkg', required: false}],- examples: [- {label: 'Validate the local package', cli: 'astryx validate-integration'},- {- label: 'Validate an installed package',- cli: 'astryx validate-integration @acme/widgets --json',- },- ],- exitCodes: [- {code: 0, when: 'no error-severity issues (warnings are allowed)'},- {code: 1, when: 'one or more error-severity issues'},- ],- related: ['doctor', 'upgrade'],-};diff --git a/packages/cli/clients/cli/commands/validate-integration.mjs b/packages/cli/clients/cli/commands/validate-integration.mjsdeleted file mode 100644index 0e9aab5bf6..0000000000--- a/packages/cli/clients/cli/commands/validate-integration.mjs+++ /dev/null@@ -1,100 +0,0 @@-// Copyright (c) Meta Platforms, Inc. and affiliates.--/**- * @file `astryx validate-integration` command — validate ONE integration- * package's manifest and contributions and report findings using the- * AstryxIntegrationIssue model.- *- * astryx validate-integration validate the local package (cwd)- * astryx validate-integration <pkg> validate an installed package- *- * Exit code is the contract: 0 when there are no severity:'error' issues- * (warnings are fine), 1 when any error issue is present — so it works as a CI- * gate. The no-arg + no-local-manifest case prints guidance and exits 0 (not- * an integration package is not a failure).- */--import {jsonOut} from '../../../foundation/response/json.mjs';-import {emit, section, text, records} from '../formatters/index.mjs';-import {defineCommand} from '../lib/define-command.mjs';-import {- validateIntegration,- summarizeIssues,-} from '../../../api/integration/validate-integration.mjs';-import {doc as validateIntegrationCommand} from './validate-integration.doc.mjs';-import {doc as validateIntegrationFn} from '../../../api/integration/validateIntegration.doc.mjs';-import {NO_RESULT_SET} from '../../../foundation/debug/index.mjs';--/**- * Render a validation result for humans.- * @param {import('../../../api/integration/validate-integration.type.mjs').ValidateIntegrationResponse['data']} data- */-function printHuman(data) {- const label =- data.version != null ? `${data.name}@${data.version}` : data.name;-- if (data.issues.length === 0) {- emit(- section(`Validating integration: ${label}`),- text('[ok] No issues found.'),- );- return;- }-- // The issue list is a projection of the JSON: one record per issue, fields- // mirroring the JSON keys (severity/code/message).- const {errors, warnings} = summarizeIssues(data.issues);- emit(- section(`Validating integration: ${label}`),- records(data.issues, {fields: ['severity', 'code', 'message']}),- text(- `${data.issues.length} issue(s): ${errors} error(s), ${warnings} warning(s)`,- ),- );-}--const NO_MANIFEST_GUIDANCE =- 'No astryx.integration.* found next to package.json. ' +- 'To validate an installed integration: astryx validate-integration <package>';--/**- * Register the `astryx validate-integration` command.- * @param {import('commander').Command} program- */-export function registerValidateIntegration(program) {- defineCommand(program, validateIntegrationCommand, {- fn: validateIntegrationFn,- action: async pkg => {- const json = program.opts().json || false;-- const result = await validateIntegration(pkg);-- if (json) {- jsonOut(result);- } else if (result.data.name === null) {- // No-arg + no local manifest: guidance, not an error.- emit(text(NO_MANIFEST_GUIDANCE));- } else {- printHuman(result.data);- }-- const {errors} = summarizeIssues(result.data.issues);- if (errors > 0) {- process.exitCode = 1;- }-- // A verdict on one integration, like doctor: issues are findings, not- // results, and an empty list is the GOOD outcome rather than an empty- // answer.- return NO_RESULT_SET;- },- }).addHelpText(- 'after',- '\nWith no argument, validates the integration package rooted at the\n' +- 'current directory. Pass a package name to validate an installed\n' +- 'integration resolved from ./node_modules.\n\n' +- 'Exit code:\n' +- ' 0 no error issues (warnings are allowed) — safe as a CI gate\n' +- ' 1 one or more error issues\n',- );-}diff --git a/packages/cli/clients/cli/commands/validate-integration.test.mjs b/packages/cli/clients/cli/commands/validate-integration.test.mjsdeleted file mode 100644index d51d6b55d4..0000000000--- a/packages/cli/clients/cli/commands/validate-integration.test.mjs+++ /dev/null@@ -1,124 +0,0 @@-// Copyright (c) Meta Platforms, Inc. and affiliates.--/**- * @file Command-level tests for `astryx validate-integration` — envelope shape- * and the no-manifest guidance path.- */--import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';-import * as fs from 'node:fs';-import * as path from 'node:path';-import {Command} from 'commander';--import {registerValidateIntegration} from './validate-integration.mjs';--let tmpDir;-let logCalls;-let prevCwd;-let prevExit;--beforeEach(() => {- // Temp dir under the repo root so manifest/node_modules paths are within- // Vite's allowed fs roots.- tmpDir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-validate-cmd-'));- logCalls = [];- vi.spyOn(console, 'log').mockImplementation((...args) => {- logCalls.push(args.join(' '));- });- vi.spyOn(console, 'error').mockImplementation(() => {});- prevCwd = process.cwd();- prevExit = process.exitCode;- process.exitCode = undefined;-});--afterEach(() => {- process.chdir(prevCwd);- process.exitCode = prevExit;- fs.rmSync(tmpDir, {recursive: true, force: true});- vi.restoreAllMocks();-});--function createProgram() {- const program = new Command();- program.exitOverride();- program.option('--json', 'Output as typed JSON');- registerValidateIntegration(program);- return program;-}--describe('validate-integration — command', () => {- it('--json emits an integration.validate envelope for a valid package', async () => {- fs.writeFileSync(- path.join(tmpDir, 'package.json'),- JSON.stringify({name: '@acme/widgets', version: '1.2.3'}),- );- fs.writeFileSync(- path.join(tmpDir, 'astryx.integration.mjs'),- 'export default {};\n',- );- process.chdir(tmpDir);-- const program = createProgram();- await program.parseAsync(['node', 'astryx', '--json', 'validate-integration']);-- const parsed = JSON.parse(logCalls.join('\n'));- expect(parsed.apiVersion).toBe(1);- expect(parsed.type).toBe('integration.validate');- expect(parsed.data.name).toBe('@acme/widgets');- expect(parsed.data.version).toBe('1.2.3');- expect(Array.isArray(parsed.data.issues)).toBe(true);- expect(parsed.data.issues).toHaveLength(0);- expect(process.exitCode).toBeUndefined();- });-- it('--json envelope carries issues and sets exit 1 on errors', async () => {- fs.writeFileSync(- path.join(tmpDir, 'package.json'),- JSON.stringify({name: '@acme/bad', version: '1.0.0'}),- );- fs.writeFileSync(- path.join(tmpDir, 'astryx.integration.mjs'),- 'export default { templates: "./gone" };\n',- );- process.chdir(tmpDir);-- const program = createProgram();- await program.parseAsync(['node', 'astryx', '--json', 'validate-integration']);-- const parsed = JSON.parse(logCalls.join('\n'));- expect(parsed.type).toBe('integration.validate');- expect(parsed.data.issues.some(i => i.code === 'missing_root')).toBe(true);- expect(process.exitCode).toBe(1);- });-- it('no-arg + no manifest prints guidance and stays exit 0', async () => {- fs.writeFileSync(- path.join(tmpDir, 'package.json'),- JSON.stringify({name: 'plain'}),- );- process.chdir(tmpDir);-- const program = createProgram();- await program.parseAsync(['node', 'astryx', 'validate-integration']);-- const out = logCalls.join('\n');- expect(out).toContain('No astryx.integration.* found next to package.json');- expect(process.exitCode).toBeUndefined();- });-- it('--json with no manifest yields a null-identity envelope', async () => {- fs.writeFileSync(- path.join(tmpDir, 'package.json'),- JSON.stringify({name: 'plain'}),- );- process.chdir(tmpDir);-- const program = createProgram();- await program.parseAsync(['node', 'astryx', '--json', 'validate-integration']);-- const parsed = JSON.parse(logCalls.join('\n'));- expect(parsed.type).toBe('integration.validate');- expect(parsed.data.name).toBeNull();- expect(parsed.data.issues).toEqual([]);- });-});diff --git a/packages/cli/clients/cli/index.mjs b/packages/cli/clients/cli/index.mjsindex c9e18e93fd..60ddf1964e 100644--- a/packages/cli/clients/cli/index.mjs+++ b/packages/cli/clients/cli/index.mjs@@ -96,7 +96,10 @@ export const JSON_SUPPORTED = new Set(['upgrade','manifest','doctor',- 'validate-integration',+ 'doctor integration validate',+ 'doctor integration templates',+ 'doctor integration components',+ 'doctor integration docs','layout expand','layout check','layout grammar',@@ -265,11 +268,6 @@ const commands = [{name: 'search', path: './commands/search.mjs', register: 'registerSearch'},{name: 'build', path: './commands/build.mjs', register: 'registerBuild'},{name: 'doctor', path: './commands/doctor.mjs', register: 'registerDoctor'},- {- name: 'validate-integration',- path: './commands/validate-integration.mjs',- register: 'registerValidateIntegration',- },];const UPDATE_HINT_COMMANDS = new Set(['component', 'docs']);diff --git a/packages/cli/clients/cli/lib/manifest.mjs b/packages/cli/clients/cli/lib/manifest.mjsindex ae17921c48..d07c731a7b 100644--- a/packages/cli/clients/cli/lib/manifest.mjs+++ b/packages/cli/clients/cli/lib/manifest.mjs@@ -83,7 +83,10 @@ export const RESPONSE_TYPES = {upgrade: ['upgrade.list', 'upgrade.status', 'upgrade.run'],manifest: ['manifest'],doctor: ['doctor'],- 'validate-integration': ['integration.validate'],+ 'doctor integration validate': ['integration.validate'],+ 'doctor integration templates': ['integration.template-conflicts'],+ 'doctor integration components': ['integration.component-conflicts'],+ 'doctor integration docs': ['integration.doc-conflicts'],'layout expand': ['layout.expand'],'layout check': ['layout.check'],'layout grammar': ['layout.grammar'],@@ -134,9 +137,21 @@ const EXAMPLES = {upgrade: ['astryx upgrade --json'],manifest: ['astryx manifest --json', 'astryx --json'],doctor: ['astryx doctor', 'astryx doctor --json'],- 'validate-integration': [- 'astryx validate-integration',- 'astryx validate-integration @acme/widgets --json',+ 'doctor integration validate': [+ 'astryx doctor integration validate',+ 'astryx doctor integration validate @acme/widgets --json',+ ],+ 'doctor integration templates': [+ 'astryx doctor integration templates',+ 'astryx doctor integration templates @acme/widgets --json',+ ],+ 'doctor integration components': [+ 'astryx doctor integration components',+ 'astryx doctor integration components @acme/widgets --json',+ ],+ 'doctor integration docs': [+ 'astryx doctor integration docs',+ 'astryx doctor integration docs @acme/widgets --json',],init: ['astryx init', 'astryx init --all --json'],'layout expand': [diff --git a/packages/cli/clients/cli/lib/manifest.test.mjs b/packages/cli/clients/cli/lib/manifest.test.mjsindex 930d3ad19b..88a005e8cf 100644--- a/packages/cli/clients/cli/lib/manifest.test.mjs+++ b/packages/cli/clients/cli/lib/manifest.test.mjs@@ -86,6 +86,18 @@ describe('manifest: drift guards', () => {}});+ it('exposes integration authoring only under doctor', () => {+ expect(allNames.has('validate-integration')).toBe(false);+ for (const name of [+ 'doctor integration validate',+ 'doctor integration templates',+ 'doctor integration components',+ 'doctor integration docs',+ ]) {+ expect(allNames.has(name), name).toBe(true);+ }+ });+it('sorts subcommands by name (stable, agent-facing order)', () => {for (const entry of allEntries) {if (!entry.subcommands) continue;diff --git a/packages/cli/foundation/discovery/template-adapter.mjs b/packages/cli/foundation/discovery/template-adapter.mjsindex f7f8c7bcff..43434db2db 100644--- a/packages/cli/foundation/discovery/template-adapter.mjs+++ b/packages/cli/foundation/discovery/template-adapter.mjs@@ -4,7 +4,7 @@* @file Shared template discovery + IO.** Owns everything the template leaves (list/show/skeleton/copy) AND other- * commands (component, layout, search, init, discover, validate-integration)+ * commands (component, layout, search, init, discover, Doctor integration)* share: template discovery across core/external/integration sources, the* template-spec loaders, and the cross-command helpers (stripTemplateAssetRefs,* findShowcase, findRelatedBlocks, extractComponents, listTemplates). The@@ -421,17 +421,31 @@ async function discoverAllBlocks(cwd = process.cwd()) {return [...core, ...external];}+/**+ * Discover only the templates built into @astryxdesign/core. Integration+ * authoring checks use this narrower surface so a broken project config or a+ * second integration cannot affect the core-collision result.+ * @returns {Promise<DiscoveredTemplate[]>}+ */+export async function discoverCoreTemplates() {+ const [pages, blocks] = await Promise.all([+ discoverPages(),+ discoverBlocks(),+ ]);+ return [...pages, ...blocks];+}+/*** @param {string} [cwd]* @returns {Promise<DiscoveredTemplate[]>}*/export async function discoverAll(cwd = process.cwd()) {- const [pages, blocks, integration] = await Promise.all([- discoverPages(),- discoverAllBlocks(cwd),+ const [core, external, integration] = await Promise.all([+ discoverCoreTemplates(),+ discoverExternalBlocks(cwd),discoverIntegrationTemplates(cwd),]);- return [...pages, ...blocks, ...integration.templates].sort((a, b) =>+ return [...core, ...external, ...integration.templates].sort((a, b) =>a.name.localeCompare(b.name),);}@@ -542,7 +556,7 @@ async function discoverIntegrationTemplates(cwd = process.cwd()) {* Discover the templates contributed by a SINGLE integration. Same per-template* rules as {@link discoverIntegrationTemplates} (same-stem source required,* page|block type required); broken templates are recorded in `errors` rather- * than thrown. Exposed for `validate-integration`.+ * than thrown. Exposed for `doctor integration validate` and template authoring checks.** @param {{name?: string, __spec?: string, templates?: string}} integration* @returns {Promise<{templates: DiscoveredTemplate[], errors: TemplateDiscoveryError[]}>}diff --git a/packages/cli/foundation/integrations/integration-warnings.mjs b/packages/cli/foundation/integrations/integration-warnings.mjsindex 945fe88935..440a851e79 100644--- a/packages/cli/foundation/integrations/integration-warnings.mjs+++ b/packages/cli/foundation/integrations/integration-warnings.mjs@@ -6,11 +6,11 @@* When a CONFIGURED integration (from the Project's `loadedIntegrations`) has* validation issues, the everyday commands (component / template / upgrade)* should print ONE compact, non-blocking line per integration telling the user- * to run `validate-integration` — instead of silently skipping broken+ * to run `doctor integration validate` — instead of silently skipping broken* contributions or spamming per-contribution diagnostics.** Design constraints (all enforced here):- * - Reuses the validate-integration validators (validateLoadedIntegration);+ * - Reuses the Doctor integration validators (validateLoadedIntegration);* no validation logic is duplicated.* - Writes to STDERR only, so it never corrupts a --json stdout envelope.* - Suppressed entirely in --json mode.@@ -23,10 +23,10 @@ import {validateLoadedIntegration} from './validate-contributions.mjs';/*** For each configured (already-loaded) integration, compute its issues using- * the shared validate-integration validators and, if any exist, print exactly+ * the shared integration validators and, if any exist, print exactly* ONE line per integration to stderr:*- * Warning: <pkg> has N integration issue(s). Run: astryx validate-integration <pkg>+ * Warning: <pkg> has N integration issue(s). Run: astryx doctor integration validate <pkg>** @param {Array<import('./integrations.mjs').LoadedIntegration>} loadedIntegrations the Project's loaded integrations* @param {{json?: boolean}} [options]@@ -53,7 +53,7 @@ export async function warnOnIntegrationIssues(loadedIntegrations, {json = false}// Stderr only — keeps stdout (and any --json envelope) clean.console.error(`Warning: ${pkg} has ${issues.length} integration issue(s). ` +- `Run: astryx validate-integration ${pkg}`,+ `Run: astryx doctor integration validate ${pkg}`,);}} catch {diff --git a/packages/cli/foundation/integrations/integration-warnings.test.mjs b/packages/cli/foundation/integrations/integration-warnings.test.mjsindex f27f1a51b4..3ee7cedd46 100644--- a/packages/cli/foundation/integrations/integration-warnings.test.mjs+++ b/packages/cli/foundation/integrations/integration-warnings.test.mjs@@ -58,7 +58,7 @@ describe('warnOnIntegrationIssues', () => {expect(errLines).toHaveLength(1);expect(errLines[0]).toBe('Warning: @acme/widgets has 1 integration issue(s). ' +- 'Run: astryx validate-integration @acme/widgets',+ 'Run: astryx doctor integration validate @acme/widgets',);});@@ -81,7 +81,7 @@ describe('warnOnIntegrationIssues', () => {expect(errLines).toHaveLength(1);expect(errLines[0]).toBe('Warning: @acme/stale has 1 integration issue(s). ' +- 'Run: astryx validate-integration @acme/stale',+ 'Run: astryx doctor integration validate @acme/stale',);});diff --git a/packages/cli/foundation/integrations/integrations.mjs b/packages/cli/foundation/integrations/integrations.mjsindex 356244632a..1f6b9ec62a 100644--- a/packages/cli/foundation/integrations/integrations.mjs+++ b/packages/cli/foundation/integrations/integrations.mjs@@ -27,7 +27,7 @@ import {importUserModule, findPresentFiles} from '../fs/module-loader.mjs';* A fully-resolved, loaded integration. Identity (`name`, `version`) comes from* the package's package.json; the `components`/`templates`/`codemods`/`docs`* roots are absolute paths resolved from the manifest. The `__`-prefixed fields- * are internal bookkeeping used by validate-integration and Project.+ * are internal bookkeeping used by Doctor integration validation and Project.* @typedef {object} LoadedIntegration* @property {string} name* @property {string} [version]@@ -61,7 +61,7 @@ export const MANIFEST_BASENAMES = [/*** Return the conventional root manifest paths present in `dir`, in* load-precedence order. Unlike {@link resolveManifestPath} this never throws —- * callers (e.g. validate-integration) decide how to treat zero / multiple.+ * callers (for example Doctor integration validation) decide how to treat zero / multiple.* @param {string} dir* @returns {string[]} absolute manifest paths*/@@ -134,7 +134,7 @@ export async function loadManifest(/*** Load and validate a manifest module's default export against the integration* schema. Throws if the default export is missing or invalid. Exposed for- * validate-integration.+ * Doctor integration validation.* @param {string} file absolute manifest path* @param {string} [label] used in error messages* @param {{fresh?: boolean}} [options]@@ -268,7 +268,7 @@ export async function loadIntegrations(try {return assertWithin(value, packageDir, {label: 'contribution root'});} catch {- // Root escapes the package — skip silently (logged by validate-integration).+ // Root escapes the package — skip silently (reported by Doctor validation).return undefined;}};diff --git a/packages/cli/foundation/integrations/validate-contributions.mjs b/packages/cli/foundation/integrations/validate-contributions.mjsindex 09e17e9585..d4ea333a41 100644--- a/packages/cli/foundation/integrations/validate-contributions.mjs+++ b/packages/cli/foundation/integrations/validate-contributions.mjs@@ -4,7 +4,7 @@* @file On-disk contribution checks for a LOADED integration.** These validators live in foundation rather than beside the- * `validate-integration` command because foundation itself needs them:+ * Doctor integration validation because foundation itself needs them:* `Project` collects integration issues while assembling components/templates,* and `integration-warnings` nudges about them on ordinary commands. Keeping* them here means those callers no longer reach up into `api/`.@@ -205,7 +205,7 @@ async function runContributionChecks(integration, issues) {* Validate an already-LOADED integration (as produced by `loadIntegrations` —* absolute contribution roots plus identity) and return its issues. This is the* reuse seam for everyday commands that have already loaded the configured- * integrations and want the SAME validators that `validate-integration` runs,+ * integrations and want the SAME validators that Doctor runs,* without re-resolving the manifest from disk.** @param {LoadedIntegration} loaded loaded-integration-shaped objectdiff --git a/packages/cli/foundation/response/response-types.doc.mjs b/packages/cli/foundation/response/response-types.doc.mjsindex 1eee9efcc0..60432f741e 100644--- a/packages/cli/foundation/response/response-types.doc.mjs+++ b/packages/cli/foundation/response/response-types.doc.mjs@@ -251,12 +251,27 @@ export const doc = {'The health-check report: `checks` (each with id, label, status: pass | warn | fail | info, a message, and a fix when not passing) plus a `summary` of counts per status.',},- // validate-integration+ // integration authoring{value: 'integration.validate',description:'The validation result: the package name and version (both null when no local manifest is found) plus issues, an AstryxIntegrationIssue[] of {code, severity: warning | error, message}.',},+ {+ value: 'integration.template-conflicts',+ description:+ 'The integration identity, structural issues, and non-blocking conflicts where an integration template id is also owned by Core; each conflict includes the exact package-qualified command.',+ },+ {+ value: 'integration.component-conflicts',+ description:+ 'The integration identity, structural issues, and non-blocking conflicts where an integration component name is also owned by Core; each conflict includes the exact package-qualified command.',+ },+ {+ value: 'integration.doc-conflicts',+ description:+ 'The integration identity, structural issues, and Core doc overlaps classified as intentional replacements, intentional extensions, or accidental same-name conflicts.',+ },// layout (XLE/XLO){