An open source design system that's fully customizable and agent ready
TypeScript
fix(doctor)!: fail when the CLI cannot load what astryx.config asks for (#7130)
Joey19da79e3942f
diff --git a/.changeset/doctor-exit-policy.md b/.changeset/doctor-exit-policy.mdnew file mode 100644index 0000000000..5d7757cfc2--- /dev/null+++ b/.changeset/doctor-exit-policy.md@@ -0,0 +1,17 @@+---+'@astryxdesign/cli': minor+---++[breaking] Doctor fails when the CLI cannot load what astryx.config asks for+@josephfarina++A new `configured-integrations` check fails when an integration named in astryx.config cannot be loaded: not installed, installed without a manifest, or a manifest that throws or fails its schema. Such an integration is withdrawn whole and contributes nothing. The config check fails, instead of warning, when astryx.config imports but the CLI cannot load the project from it.++Unchanged: a problem inside one contribution kind (an invalid component doc, a missing or unreadable root, an unresolved replacement) stays a warning under `integration-issues` (spec:AST-035 FR9), and an autolinked dependency that cannot be loaded stays informational.++Classification: incompatible-fix.+Released victim: published 0.6.8 (the latest stable) exits 0 for both cases.+No codemod: nothing in a project's source changes; the fix is to install the integration, repair its manifest, or edit `integrations` in astryx.config, which only the project's owner can decide.++What counts as configured is every name astryx.config lists, read from the provider ledger: a package set aside for a provider conflict and the package being authored when its own config names it both count.+Migration: install the integration, fix its manifest, or remove it from `integrations`; fix the astryx.config field the message names.diff --git a/packages/cli/api/doctor/doctor.doc.mjs b/packages/cli/api/doctor/doctor.doc.mjsindex 3c9eb55fce..d68f0eb269 100644--- a/packages/cli/api/doctor/doctor.doc.mjs+++ b/packages/cli/api/doctor/doctor.doc.mjs@@ -18,7 +18,8 @@ export const doc = {description:'Runs a series of diagnostics: Node version, ' +'@astryxdesign/core install and version alignment with the CLI, installed ' +- 'themes and wiring, astryx.config validity, integrations linked from ' ++ 'themes and wiring, astryx.config validity, whether every integration ' ++ 'astryx.config names loads (a failed one fails the run), integrations linked from ' +'package.json without a config entry, core peer dependencies, ' +'integration provider identity and contribution issues, agent docs, the ' +'detected package manager, and the health of the docs the CLI reads (authoring ' +diff --git a/packages/cli/api/doctor/doctor.mjs b/packages/cli/api/doctor/doctor.mjsindex 6c71228864..599bb78b7d 100644--- a/packages/cli/api/doctor/doctor.mjs+++ b/packages/cli/api/doctor/doctor.mjs@@ -82,6 +82,11 @@ import {checkAppThemes, checkThemes} from './theme-checks.mjs';* could not be built, when it could not.* @property {Array<{package: string, code: string, severity: 'warning'|'error', message: string}>|null} [integrationIssues]* @property {Array<{spec: string, error: string}>|null} [autolinkFailures]+ * @property {Array<{spec: string, label: string, error: string|null}>|null} [configuredIntegrations]+ * Every name astryx.config lists, from the provider ledger: the package it+ * reached (or failed to reach) and why loading failed, if it did. Set aside+ * for a provider conflict, replaced by the package being authored, or+ * repeated under another name all still count as configured.* installed dependencies whose integration manifest could not be loaded* Combined project-level integration issues, including cross-package template replacement warnings.* @property {Error|null} [configError] - Error thrown while resolving the config@@ -319,12 +324,12 @@ export async function checkConfig(ctx) {}// Importing is not the whole test: the CLI also validates the config, and// a config it rejects leaves every project-aware command without the- // project. That config is not clean, so this warns (exit code unchanged).+ // project. Doctor is the CI gate, so that fails.if (ctx.projectError) {return {id: 'config',label: 'astryx.config.mjs',- status: 'warn',+ status: 'fail',message: `astryx.config.mjs loads, but the CLI could not load the project from it: ${firstLine(ctx.projectError)}`,fix: 'Fix what the message names. `astryx docs authoring config` lists every field astryx.config accepts.',};@@ -475,6 +480,88 @@ function describeUnreadableManifests(failures) {);}+/**+ * Every integration named in astryx.config loads.+ *+ * A configured integration that cannot be loaded (not installed, no+ * manifest, or a manifest that throws or fails its schema) is withdrawn+ * whole, because none of its contribution roots is trustworthy+ * (spec:AST-035 FR9). The project then runs without something it asked+ * for, so this fails the CI gate.+ *+ * Two neighbours stay as they were. A problem inside one contribution kind+ * leaves the rest of the integration working, so `integration-issues` keeps+ * warning about it (spec:AST-035 FR9). An autolinked dependency that cannot+ * be loaded stays informational in `implicit-integrations`: the project did+ * not ask for it.+ *+ * @param {DoctorContext} ctx+ * @returns {DoctorCheck}+ */+export function checkConfiguredIntegrations(ctx) {+ const id = 'configured-integrations';+ const label = 'Configured integrations';+ if (ctx.integrations == null) {+ // The config check reports a config the CLI cannot load.+ return {+ id,+ label,+ status: 'info',+ message: skippedBecause(ctx, 'the project configuration could not be read'),+ };+ }+ // What counts as configured is what astryx.config names, read from the+ // provider ledger so a package set aside for a provider conflict, or the+ // package being authored when its own config names it, still counts.+ const configured =+ ctx.configuredIntegrations ??+ ctx.integrations+ .filter(integration => !integration.__autolinked && !integration.__local)+ .map(integration => ({+ spec: integration.__spec,+ label: integration.name ?? integration.__spec,+ error:+ integration.__loadError == null+ ? null+ : String(integration.__loadError),+ }));+ if (configured.length === 0) {+ return {+ id,+ label,+ status: 'info',+ message: 'No integration is named in astryx.config.',+ };+ }+ const plural = configured.length === 1 ? '' : 's';+ const withdrawn = configured.filter(entry => entry.error != null);+ if (withdrawn.length > 0) {+ const listed = withdrawn+ .map(+ entry =>+ `${entry.label} (${firstLine(String(entry.error)).slice(0, 160)})`,+ )+ .join('; ');+ return {+ id,+ label,+ status: 'fail',+ message:+ `${withdrawn.length} of ${configured.length} integration${plural} named in astryx.config could not be loaded, ` ++ `so ${withdrawn.length === 1 ? 'it contributes' : 'they contribute'} nothing: ${listed}.`,+ fix:+ 'Install each one, fix its astryx.integration.* manifest (`astryx doctor integration validate <package>` says what is wrong), ' ++ 'or remove it from `integrations` in astryx.config.',+ };+ }+ return {+ id,+ label,+ status: 'pass',+ message: `${configured.length} integration${plural} named in astryx.config loaded: ${configured.map(entry => entry.label).join(', ')}.`,+ };+}+/*** Check 7 — agent docs exist and contain the Astryx section markers.* @param {DoctorContext} ctx@@ -1201,6 +1288,7 @@ export const SYNC_CHECKS = [checkCoreInstalled,checkVersionAlignment,checkImplicitIntegrations,+ checkConfiguredIntegrations,checkProviderIdentity,checkIntegrationIssues,checkAgentDocs,@@ -1244,6 +1332,8 @@ export async function runChecks(options = {}) {let integrationIssues = null;/** @type {Array<{spec: string, error: string}>|null} */let autolinkFailures = null;+ /** @type {Array<{spec: string, label: string, error: string|null}>|null} */+ let configuredIntegrations = null;/** @type {string|null} */let projectError = null;/** @type {import('../../foundation/config/project.mjs').Project | null} */@@ -1261,7 +1351,66 @@ export async function runChecks(options = {}) {integrations = project.loadedIntegrations;// An installed dependency whose manifest cannot be loaded is kept out of// loadedIntegrations on purpose. The provider ledger still records it.- autolinkFailures = [...providerLedgerOf(project).values()]+ const ledgerMap = providerLedgerOf(project);+ const ledger = [...ledgerMap.values()];+ // The package that stands for a configured name: when the package+ // being authored replaces the configured copy, the authored package's+ // outcome is the one that matters, so a broken authored manifest fails+ // the check even though the configured copy itself loaded. A package+ // set aside for a provider conflict keeps its own outcome.+ /** @param {import('../../foundation/integrations/provider-resolution.mjs').ProviderLedgerEntry} entry */+ const standsFor = entry => {+ let current = entry;+ const seen = new Set();+ while (+ current.outcome === 'set-aside' &&+ current.reason === 'replaced-by-authored' &&+ current.winner != null &&+ !seen.has(current.winner) &&+ ledgerMap.has(current.winner)+ ) {+ seen.add(current.winner);+ current = /** @type {typeof entry} */ (ledgerMap.get(current.winner));+ }+ return current;+ };+ // Every package a configured name reached, however it was resolved.+ configuredIntegrations = ledger+ .filter(entry =>+ entry.refs.some(+ ref => ref.source === 'configured' && ref.repeat !== true,+ ),+ )+ .map(entry => {+ const ref = entry.refs.find(+ candidate => candidate.source === 'configured',+ );+ const effective = standsFor(entry);+ // When node_modules/<name> links back to the package being authored,+ // the configured and local candidates share one real path and one+ // entry whose outcome is the set-aside; the authored (`local`)+ // candidate on that entry carries the load error, so it is the+ // outcome that counts. Reading it from the ref, not by comparing+ // paths, holds whether or not the working directory is itself a+ // symlink.+ const authored = effective.refs.find(+ candidate => candidate.source === 'local',+ );+ const authoredError =+ authored?.integration?.__loadError ?? authored?.error ?? null;+ const loadError =+ effective.outcome === 'load-failed'+ ? (effective.error ?? 'its manifest could not be loaded')+ : authoredError != null+ ? String(authoredError)+ : null;+ return {+ spec: ref?.spec ?? entry.label,+ label: entry.integration?.name ?? ref?.spec ?? entry.label,+ error: loadError,+ };+ });+ autolinkFailures = ledger.filter(entry =>entry.outcome === 'load-failed' &&@@ -1300,6 +1449,7 @@ export async function runChecks(options = {}) {docsCatalogError,integrationIssues,autolinkFailures,+ configuredIntegrations,configError,projectError,};diff --git a/packages/cli/api/doctor/doctor.test.mjs b/packages/cli/api/doctor/doctor.test.mjsindex 25f668f1f6..ef63acb3b0 100644--- a/packages/cli/api/doctor/doctor.test.mjs+++ b/packages/cli/api/doctor/doctor.test.mjs@@ -1042,7 +1042,7 @@ describe('doctor says why it skipped and what it checked', () => {}it(- 'warns, and quotes the reason, when the CLI cannot load the project from a config that imports',+ 'fails, and quotes the reason, when the CLI cannot load the project from a config that imports',async () => {const dir = cwdProject({'package.json': '{"name":"app"}',@@ -1051,7 +1051,7 @@ describe('doctor says why it skipped and what it checked', () => {});const {checks, summary} = (await doctor({cwd: dir})).data;const by = Object.fromEntries(checks.map(c => [c.id, c]));- expect(by.config.status).toBe('warn');+ expect(by.config.status).toBe('fail');expect(by.config.message).toMatch(/^astryx\.config\.mjs loads, but the CLI could not load the project from it: .*integrations/,);@@ -1064,8 +1064,8 @@ describe('doctor says why it skipped and what it checked', () => {expect(by['integration-issues'].message).toMatch(/^Skipped — the project integration graph could not be loaded: .*integrations/,);- // A warning: the exit code a released CLI gave this project is unchanged.- expect(summary.fail).toBe(0);+ // The config check is the one failure; the skipped checks stay info.+ expect(summary.fail).toBe(1);},SLOW,);@@ -1123,6 +1123,252 @@ describe('doctor says why it skipped and what it checked', () => {});});+describe('a configured integration that cannot load fails the gate', () => {+ const CORE_STUB = {+ 'node_modules/@astryxdesign/core/package.json': JSON.stringify({+ name: '@astryxdesign/core',+ version: '0.6.3',+ }),+ };+ const WIDGETS = 'node_modules/@acme/widgets';+ /** @param {string} [manifest] */+ const widgets = (+ manifest = "export default {components: './components'};\n",+ ) => ({+ [`${WIDGETS}/package.json`]: JSON.stringify({+ name: '@acme/widgets',+ version: '1.0.0',+ }),+ [`${WIDGETS}/astryx.integration.mjs`]: manifest,+ [`${WIDGETS}/components/AcmeCard.doc.mjs`]:+ "export default {type: 'component', name: 'AcmeCard', displayName: 'AcmeCard', description: 'Fixture.', props: []};\n",+ [`${WIDGETS}/components/AcmeCard.tsx`]:+ 'export default function AcmeCard() { return null; }\n',+ });+ const APP = {+ 'package.json': '{"name":"app"}',+ ...CORE_STUB,+ 'astryx.config.mjs': "export default { integrations: ['@acme/widgets'] };\n",+ };++ /** Run doctor on a project under the working directory. */+ async function report(files) {+ const dir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-doctor-gate-'));+ tmpDirs.push(dir);+ for (const [rel, content] of Object.entries(files)) {+ const abs = path.join(dir, rel);+ fs.mkdirSync(path.dirname(abs), {recursive: true});+ fs.writeFileSync(abs, content);+ }+ const {checks, summary} = (await doctor({cwd: dir})).data;+ return {by: Object.fromEntries(checks.map(c => [c.id, c])), summary};+ }++ it.each([+ ['not installed', {}, /Could not find installed integration package "@acme\/widgets"/],+ [+ 'installed without a manifest',+ {[`${WIDGETS}/package.json`]: JSON.stringify({name: '@acme/widgets', version: '1.0.0'})},+ /no conventional root manifest/,+ ],+ ['installed with a manifest that throws', widgets('export default { not valid ((\n'), /Unexpected/],+ ])(+ 'fails when a configured integration is %s, and names it',+ async (_shape, extra, reason) => {+ const {by, summary} = await report({...APP, ...extra});+ const check = by['configured-integrations'];+ expect(check.status).toBe('fail');+ expect(check.message).toMatch(+ /^1 of 1 integration named in astryx\.config could not be loaded, so it contributes nothing: @acme\/widgets \(/,+ );+ expect(check.message).toMatch(reason);+ expect(check.fix).toContain('astryx doctor integration validate <package>');+ expect(summary.fail).toBe(1);+ },+ SLOW,+ );++ it(+ 'counts the package being authored when its own config names it',+ async () => {+ const {by} = await report({+ ...CORE_STUB,+ 'package.json': JSON.stringify({name: '@acme/widgets', version: '1.0.0'}),+ 'astryx.integration.mjs': "export default {components: './components'};\n",+ 'components/AcmeCard.doc.mjs':+ "export default {type: 'component', name: 'AcmeCard', displayName: 'AcmeCard', description: 'Fixture.', props: []};\n",+ 'components/AcmeCard.tsx': 'export default function AcmeCard() { return null; }\n',+ 'astryx.config.mjs': "export default { integrations: ['@acme/widgets'] };\n",+ });+ expect(by['configured-integrations'].status).toBe('pass');+ expect(by['configured-integrations'].message).toBe(+ '1 integration named in astryx.config loaded: @acme/widgets.',+ );+ },+ SLOW,+ );++ it(+ 'fails when the package being authored is named by its own config and its manifest throws',+ async () => {+ const {by, summary} = await report({+ ...CORE_STUB,+ 'package.json': JSON.stringify({name: '@acme/widgets', version: '1.0.0'}),+ 'astryx.integration.mjs': 'export default { not valid ((\n',+ 'astryx.config.mjs': "export default { integrations: ['@acme/widgets'] };\n",+ });+ const check = by['configured-integrations'];+ expect(check.status).toBe('fail');+ expect(check.message).toMatch(+ /^1 of 1 integration named in astryx\.config could not be loaded, so it contributes nothing: @acme\/widgets \(/,+ );+ expect(summary.fail).toBe(1);+ },+ SLOW,+ );++ it(+ 'fails when node_modules links the configured name back to the authored package and its manifest throws',+ async () => {+ const dir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-doctor-gate-'));+ tmpDirs.push(dir);+ const files = {+ ...CORE_STUB,+ 'package.json': JSON.stringify({name: '@acme/widgets', version: '1.0.0'}),+ 'astryx.integration.mjs': 'export default { not valid ((\n',+ 'astryx.config.mjs': "export default { integrations: ['@acme/widgets'] };\n",+ };+ for (const [rel, content] of Object.entries(files)) {+ const abs = path.join(dir, rel);+ fs.mkdirSync(path.dirname(abs), {recursive: true});+ fs.writeFileSync(abs, content);+ }+ fs.mkdirSync(path.join(dir, 'node_modules/@acme'), {recursive: true});+ fs.symlinkSync(dir, path.join(dir, 'node_modules/@acme/widgets'), 'dir');+ const {checks, summary} = (await doctor({cwd: dir})).data;+ const by = Object.fromEntries(checks.map(c => [c.id, c]));+ expect(by['configured-integrations'].status).toBe('fail');+ expect(by['configured-integrations'].message).toMatch(+ /^1 of 1 integration named in astryx\.config could not be loaded/,+ );+ expect(summary.fail).toBe(1);+ },+ SLOW,+ );++ it(+ 'fails for the self-linked authored package when the working directory is itself a symlink',+ async () => {+ const real = fs.mkdtempSync(path.join(process.cwd(), '.astryx-doctor-gate-'));+ tmpDirs.push(real);+ const linkParent = fs.mkdtempSync(path.join(process.cwd(), '.astryx-doctor-gate-'));+ tmpDirs.push(linkParent);+ const cwd = path.join(linkParent, 'link');+ fs.symlinkSync(real, cwd, 'dir');+ const files = {+ ...CORE_STUB,+ 'package.json': JSON.stringify({name: '@acme/widgets', version: '1.0.0'}),+ 'astryx.integration.mjs': 'export default { not valid ((\n',+ 'astryx.config.mjs': "export default { integrations: ['@acme/widgets'] };\n",+ };+ for (const [rel, content] of Object.entries(files)) {+ const abs = path.join(real, rel);+ fs.mkdirSync(path.dirname(abs), {recursive: true});+ fs.writeFileSync(abs, content);+ }+ fs.mkdirSync(path.join(real, 'node_modules/@acme'), {recursive: true});+ fs.symlinkSync(real, path.join(real, 'node_modules/@acme/widgets'), 'dir');+ const {checks, summary} = (await doctor({cwd})).data;+ const by = Object.fromEntries(checks.map(c => [c.id, c]));+ expect(by['configured-integrations'].status).toBe('fail');+ expect(summary.fail).toBe(1);+ },+ SLOW,+ );++ it(+ 'still counts a configured package that was set aside for a provider conflict',+ async () => {+ const CHARTS = 'node_modules/@acme/charts';+ const {by} = await report({+ ...APP,+ 'astryx.config.mjs':+ "export default { integrations: ['@acme/widgets', '@acme/charts'] };\n",+ ...widgets("export default {providerId: 'acme', components: './components'};\n"),+ [`${CHARTS}/package.json`]: JSON.stringify({name: '@acme/charts', version: '1.0.0'}),+ [`${CHARTS}/astryx.integration.mjs`]:+ "export default {providerId: 'acme', components: './components'};\n",+ [`${CHARTS}/components/AcmeChart.doc.mjs`]:+ "export default {type: 'component', name: 'AcmeChart', displayName: 'AcmeChart', description: 'Fixture.', props: []};\n",+ [`${CHARTS}/components/AcmeChart.tsx`]: 'export default function AcmeChart() { return null; }\n',+ });+ expect(by['configured-integrations'].status).toBe('pass');+ expect(by['configured-integrations'].message).toMatch(/^2 integrations named in astryx\.config loaded: /);+ expect(by['configured-integrations'].message).toContain('@acme/charts');+ },+ SLOW,+ );++ it(+ 'passes, naming each one, when every configured integration loads',+ async () => {+ const {by, summary} = await report({...APP, ...widgets()});+ expect(by['configured-integrations']).toEqual({+ id: 'configured-integrations',+ label: 'Configured integrations',+ status: 'pass',+ message: '1 integration named in astryx.config loaded: @acme/widgets.',+ });+ expect(summary.fail).toBe(0);+ },+ SLOW,+ );++ it.each([+ [+ 'an invalid component doc',+ {[`${WIDGETS}/components/AcmeCard.doc.mjs`]: 'export default {;\n'},+ ],+ [+ 'a declared root missing on disk',+ {+ [`${WIDGETS}/astryx.integration.mjs`]:+ "export default {components: './components', templates: './templates'};\n",+ },+ ],+ ])(+ 'keeps %s a warning, because the rest of the integration still loads (spec:AST-035 FR9)',+ async (_shape, extra) => {+ const {by, summary} = await report({...APP, ...widgets(), ...extra});+ expect(by['configured-integrations'].status).toBe('pass');+ expect(by['integration-issues'].status).toBe('warn');+ expect(summary.fail).toBe(0);+ },+ SLOW,+ );++ it(+ 'leaves an autolinked dependency that cannot load informational',+ async () => {+ const {by, summary} = await report({+ 'package.json': JSON.stringify({+ name: 'app',+ dependencies: {'@acme/widgets': '1.0.0'},+ }),+ ...CORE_STUB,+ ...widgets('export default { not valid ((\n'),+ });+ expect(by['configured-integrations']).toMatchObject({+ status: 'info',+ message: 'No integration is named in astryx.config.',+ });+ expect(by['implicit-integrations'].status).toBe('info');+ expect(summary.fail).toBe(0);+ },+ SLOW,+ );+});+describe('no Astryx-owned environment variables (spec:AST-017 FR14)', () => {it('no source file reads an ASTRYX_* env var', () => {const cliDir = path.resolve(REPO, 'packages/cli');diff --git a/packages/cli/clients/cli/commands/doctor.doc.mjs b/packages/cli/clients/cli/commands/doctor.doc.mjsindex 6d75f0caa4..495204829c 100644--- a/packages/cli/clients/cli/commands/doctor.doc.mjs+++ b/packages/cli/clients/cli/commands/doctor.doc.mjs@@ -16,7 +16,7 @@ export const doc = {summary: 'Diagnose Astryx projects and integration packages',description:'Runs read-only project health diagnostics by default: Node version, @astryxdesign/core ' +- 'install and version alignment, theme packages, generated app themes when present, earlier copied-theme migration, config, integrations (linked without a config entry, ' ++ 'install and version alignment, theme packages, generated app themes when present, earlier copied-theme migration, config, integrations (every one astryx.config names must load, linked without a config entry, ' +'provider identity, contribution issues), agent docs, core peer dependencies, package manager, ' +"and the docs the CLI reads. It writes nothing, but loading astryx.config runs that file's code. " +'The `integration` subcommands provide authoring checks for one integration package.',diff --git a/packages/cli/clients/cli/commands/doctor.test.mjs b/packages/cli/clients/cli/commands/doctor.test.mjsindex 04931a1ad1..3f999c8e1d 100644--- a/packages/cli/clients/cli/commands/doctor.test.mjs+++ b/packages/cli/clients/cli/commands/doctor.test.mjs@@ -403,3 +403,36 @@ describe('doctor — text output mirrors the JSON', () => {}}, 60_000);});++describe('doctor — a configured integration that cannot load', () => {+ it('sets exit code 1 and reports it in the JSON', async () => {+ const dir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-doctor-exit-'));+ const prevCwd = process.cwd();+ const prevExit = process.exitCode;+ process.exitCode = undefined;+ try {+ fs.writeFileSync(path.join(dir, 'package.json'), '{"name":"app"}');+ fs.writeFileSync(+ path.join(dir, 'astryx.config.mjs'),+ "export default { integrations: ['@acme/missing'] };\n",+ );+ const coreDir = path.join(dir, 'node_modules', '@astryxdesign', 'core');+ fs.mkdirSync(coreDir, {recursive: true});+ fs.writeFileSync(+ path.join(coreDir, 'package.json'),+ JSON.stringify({name: '@astryxdesign/core', version: '0.6.3'}),+ );+ process.chdir(dir);+ await createProgram().parseAsync(['node', 'astryx', '--json', 'doctor']);+ expect(process.exitCode).toBe(1);+ const {data} = JSON.parse(logCalls.join('\n'));+ expect(+ data.checks.find(c => c.id === 'configured-integrations'),+ ).toMatchObject({status: 'fail'});+ } finally {+ process.chdir(prevCwd);+ process.exitCode = prevExit;+ fs.rmSync(dir, {recursive: true, force: true});+ }+ }, 60_000);+});