Skip to content

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

TypeScript

feat(cli): let integrations append agent-doc lines (#6170)

Joey95c8dbf67e2d
diff --git a/.changeset/bright-agent-guidance.md b/.changeset/bright-agent-guidance.md
new file mode 100644
index 0000000000..118a5324d0
--- /dev/null
+++ b/.changeset/bright-agent-guidance.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[feat] Let integration manifests add managed agent guidance
+@josephfarina
diff --git a/docs/architecture/cli-surface.md b/docs/architecture/cli-surface.md
index 691312163d..66b77be39d 100644
--- a/docs/architecture/cli-surface.md
+++ b/docs/architecture/cli-surface.md
@@ -18,6 +18,8 @@ verified_by:
clients/cli/cli-exit-codes.test.mjs,
clients/cli/error-envelope-code.test.mjs,
foundation/response/error-codes.test.mjs,
+ foundation/agent-docs/agent-docs.test.mjs,
+ clients/cli/commands/upgrade.integration-policy.test.mjs,
clients/cli/formatters/index.test.mjs,
]
deciding_specs: [spec:AST-017/DEC-4]
@@ -110,6 +112,10 @@ test, applicable text, and consumer-documentation projections.
- **INV12 — Human chatter never touches stdout in JSON mode.** `humanLog` and
`humanWarn` are the only chatter primitives, and both are no-ops under
`--json`.
+- **INV13 — Agent docs have one rendered source of truth.** Init and upgrade
+ render configured integration `agentDocs` through the existing `Project`
+ seam. Upgrade compares complete block bytes even when Core is unchanged and,
+ when codemods or hooks run, writes the prepared block only after they succeed.
## Change coupling
@@ -143,6 +149,8 @@ non-interactive guarantee.
- `foundation/response/error-codes.mjs` — the frozen, append-only code set.
- `foundation/config` — the `Project` discovery seam and the integration
manifest loader.
+- `foundation/agent-docs` — the shared expected-block renderer and managed-file
+ writer used by init and upgrade.
- `api/<subject>/…` — the scriptable functions the commands wrap; each owns the
`type` on its own envelope.
diff --git a/packages/cli/api/init/init.doc.mjs b/packages/cli/api/init/init.doc.mjs
index 873b1ef431..7895f833d5 100644
--- a/packages/cli/api/init/init.doc.mjs
+++ b/packages/cli/api/init/init.doc.mjs
@@ -17,7 +17,8 @@ export const doc = {
description:
'Sets a project up with NO prompts, so it behaves identically for humans, ' +
'agents, CI, and piped I/O. By default it installs the AGENTS.md/CLAUDE.md ' +
- 'agent-docs cheat sheet and prints getting-started guidance; `features` / ' +
+ 'agent-docs cheat sheet, including guidance from configured integrations, and ' +
+ 'prints getting-started guidance; `features` / ' +
'`all` add theme and page-building guidance and can scaffold a starter ' +
'template. With `removeAgents` it removes the managed agent-docs block ' +
'instead of installing.',
diff --git a/packages/cli/api/init/init.test.mjs b/packages/cli/api/init/init.test.mjs
index a69ff7e614..5534fcfc16 100644
--- a/packages/cli/api/init/init.test.mjs
+++ b/packages/cli/api/init/init.test.mjs
@@ -11,7 +11,6 @@
import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
import * as fs from 'node:fs';
import * as path from 'node:path';
-import * as os from 'node:os';
import {init, getNextSteps} from './init.mjs';
import {logger} from '../logger.mjs';
import {AstryxError} from '../error.mjs';
@@ -22,7 +21,7 @@ const MARKER_START = '<!-- ASTRYX:START -->';
let tmpDir;
beforeEach(() => {
- tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-init-api-'));
+ tmpDir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-init-api-'));
});
afterEach(() => {
@@ -34,6 +33,29 @@ const read = rel => fs.readFileSync(path.join(tmpDir, rel), 'utf8');
/** @param {string} rel */
const exists = rel => fs.existsSync(path.join(tmpDir, rel));
+function writeIntegration() {
+ fs.writeFileSync(
+ path.join(tmpDir, 'package.json'),
+ JSON.stringify({name: 'consumer'}),
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'astryx.config.mjs'),
+ `export default {integrations: ['@acme/widgets']};\n`,
+ );
+ const packageDir = path.join(tmpDir, 'node_modules', '@acme', 'widgets');
+ fs.mkdirSync(packageDir, {recursive: true});
+ fs.writeFileSync(
+ path.join(packageDir, 'package.json'),
+ JSON.stringify({name: '@acme/widgets'}),
+ );
+ fs.writeFileSync(
+ path.join(packageDir, 'astryx.integration.mjs'),
+ `export default {agentDocs: {
+ append: ['Run acme verify before finishing.'],
+ }};\n`,
+ );
+}
+
describe('init() — receipts + side effects', () => {
it('default mode installs AGENTS.md and returns an init.run receipt', async () => {
const res = await init({}, {cwd: tmpDir});
@@ -47,6 +69,47 @@ describe('init() — receipts + side effects', () => {
expect(read('AGENTS.md')).toContain(MARKER_START);
});
+ it('renders configured integration guidance into the real init block', async () => {
+ writeIntegration();
+
+ const res = await init({features: 'agents'}, {cwd: tmpDir});
+
+ expect(res.type).toBe('init.run');
+ if (res.type !== 'init.run') return;
+ expect(res.data.docsError).toBeNull();
+ const content = read('AGENTS.md');
+ expect(content).toContain(
+ '- `@acme/widgets`: Run acme verify before finishing.',
+ );
+ expect(
+ content.indexOf('Run acme verify before finishing.'),
+ ).toBeGreaterThan(content.indexOf('MORE CLI:'));
+ });
+
+ it('leaves existing agent docs unchanged when integration agentDocs is invalid', async () => {
+ writeIntegration();
+ fs.writeFileSync(
+ path.join(
+ tmpDir,
+ 'node_modules',
+ '@acme',
+ 'widgets',
+ 'astryx.integration.mjs',
+ ),
+ `export default {agentDocs: {append: [' invalid']}};\n`,
+ );
+ const before = '# Agents\n\nKeep this byte-for-byte.\n';
+ fs.writeFileSync(path.join(tmpDir, 'AGENTS.md'), before);
+
+ const res = await init({features: 'agents'}, {cwd: tmpDir});
+
+ expect(res.type).toBe('init.run');
+ if (res.type !== 'init.run') return;
+ expect(res.data.docsWritten).toEqual([]);
+ expect(res.data.docsError).toMatchObject({kind: 'install-failed'});
+ expect(read('AGENTS.md')).toBe(before);
+ });
+
it('writes to the cwd param, not process.cwd() (no chdir)', async () => {
// Regression guard: the fixture lives in tmpDir while process.cwd() stays
// the repo root. A cwd-honoring API must land AGENTS.md in tmpDir.
diff --git a/packages/cli/api/init/run/run.mjs b/packages/cli/api/init/run/run.mjs
index 8e858928e6..d90af31558 100644
--- a/packages/cli/api/init/run/run.mjs
+++ b/packages/cli/api/init/run/run.mjs
@@ -19,8 +19,10 @@ import * as fs from 'node:fs';
import {CLI_ROOT} from '../../../foundation/fs/paths.mjs';
import {PathSafetyError} from '../../../foundation/fs/path-safety.mjs';
import {getCliInvocation} from '../../../foundation/env/package-manager.mjs';
-import {installAgentDocs} from '../../../foundation/agent-docs/agent-docs.mjs';
-import {loadDocsCatalog} from '../../docs/_adapter.mjs';
+import {
+ installAgentDocs,
+ renderAgentDocsBlock,
+} from '../../../foundation/agent-docs/agent-docs.mjs';
import {themeTemplate} from '../../theme/template/template.mjs';
import {listTemplates} from '../../template/template.mjs';
import {AstryxError} from '../../error.mjs';
@@ -89,11 +91,12 @@ async function applyAgents(cwd, options, invocation, data) {
? options.agentDocsPath
: [options.agentDocsPath]
: undefined;
- // The block names the topics the agent can read, and an integration's
- // topics are part of that set — resolved here rather than inside
- // installAgentDocs, which is sync and cannot load a project.
- const topics = (await loadDocsCatalog(cwd)).names();
- const written = installAgentDocs(cwd, {agent: options.agent, paths, topics});
+ const renderedBlock = await renderAgentDocsBlock(cwd);
+ const written = installAgentDocs(cwd, {
+ agent: options.agent,
+ paths,
+ renderedBlock,
+ });
data.docsWritten = written;
logger.log(`✓ AI agent docs installed → ${written.join(', ')}`);
} catch (err) {
diff --git a/packages/cli/api/integration/validate-integration.mjs b/packages/cli/api/integration/validate-integration.mjs
index b464a246ff..3ddd8b1a3d 100644
--- a/packages/cli/api/integration/validate-integration.mjs
+++ b/packages/cli/api/integration/validate-integration.mjs
@@ -121,15 +121,17 @@ async function validateAtPackageDir(packageDir, identity) {
const manifestFile = manifests[0];
result.manifestFile = manifestFile;
- // loadManifest loads the default export and validates it against the
- // integration schema (the shared load boundary). A missing default export or
- // a schema failure throws; we convert either into a single invalid_manifest
- // error issue so validate-integration stays exit-1-but-not-crash.
+ // loadManifest validates the base manifest and isolates optional agent-doc
+ // validation. A missing default export or invalid base field throws and
+ // becomes invalid_manifest; invalid agentDocs is carried to the shared
+ // contribution validator so other valid roots remain available.
let manifest;
/** @type {string[]} */
let unknownKeys;
+ /** @type {string | undefined} */
+ let agentDocsError;
try {
- ({manifest, unknownKeys} = await loadManifest(
+ ({manifest, unknownKeys, agentDocsError} = await loadManifest(
manifestFile,
`Integration manifest (${path.basename(manifestFile)})`,
));
@@ -162,6 +164,8 @@ async function validateAtPackageDir(packageDir, identity) {
codemods: resolveRoot(manifest.codemods),
docs: resolveRoot(manifest.docs),
issuesUrl: manifest.issuesUrl,
+ agentDocs: manifest.agentDocs,
+ __agentDocsError: agentDocsError,
__unknownKeys: unknownKeys,
__spec: identity.name,
__packageDir: packageDir,
diff --git a/packages/cli/api/integration/validate-integration.test.mjs b/packages/cli/api/integration/validate-integration.test.mjs
index 630305f411..a9ac92faa5 100644
--- a/packages/cli/api/integration/validate-integration.test.mjs
+++ b/packages/cli/api/integration/validate-integration.test.mjs
@@ -133,6 +133,34 @@ describe('validate-integration API', () => {
expect(result.issues).toEqual([]);
});
+ it('reports invalid agentDocs without invalidating other manifest fields', async () => {
+ const pkgDir = path.join(tmpDir, 'pkg');
+ writePackage(pkgDir, {
+ manifest: `export default {
+ components: './components',
+ agentDocs: {append: [' invalid']},
+ };\n`,
+ });
+ const componentsDir = path.join(pkgDir, 'components');
+ fs.mkdirSync(componentsDir);
+ fs.writeFileSync(
+ path.join(componentsDir, 'Widget.doc.mjs'),
+ `export default {name: 'Widget'};\n`,
+ );
+ fs.writeFileSync(
+ path.join(componentsDir, 'Widget.tsx'),
+ `export function Widget() { return null; }\n`,
+ );
+
+ const result = await validateLocalIntegration(pkgDir);
+
+ expect(byCode(result.issues, 'invalid_manifest')).toHaveLength(0);
+ expect(byCode(result.issues, 'invalid_component')).toHaveLength(0);
+ const agentDocsIssues = byCode(result.issues, 'invalid_agent_docs');
+ expect(agentDocsIssues).toHaveLength(1);
+ expect(agentDocsIssues[0].severity).toBe('error');
+ });
+
it('flags a broken codemod as invalid_codemod error', async () => {
const pkgDir = path.join(tmpDir, 'pkg');
writePackage(pkgDir, {
diff --git a/packages/cli/api/upgrade/_adapter.mjs b/packages/cli/api/upgrade/_adapter.mjs
index 7fb81927d5..e4f4dbd7ea 100644
--- a/packages/cli/api/upgrade/_adapter.mjs
+++ b/packages/cli/api/upgrade/_adapter.mjs
@@ -26,14 +26,21 @@ import {
selectIntegrationCodemods,
} from '../../assets/codemods/integration-discovery.mjs';
import {runIntegrationCodemods} from '../../assets/codemods/integration-runner.mjs';
-import {installAgentDocs, inspectAgentDocs} from '../../foundation/agent-docs/agent-docs.mjs';
-import {loadDocsCatalog} from '../docs/_adapter.mjs';
+import {
+ installAgentDocs,
+ inspectAgentDocs,
+ renderAgentDocsBlock,
+} from '../../foundation/agent-docs/agent-docs.mjs';
import {formatCliCommand} from '../../foundation/env/package-manager.mjs';
import {Project} from '../../foundation/config/project.mjs';
import {loadIntegrations} from '../../foundation/integrations/integrations.mjs';
import {warnOnIntegrationIssues} from '../../foundation/integrations/integration-warnings.mjs';
import {logger} from '../logger.mjs';
+// Re-exported for the run leaf's lightweight agent-docs inspection path
+// (config_fixable short-circuit, where the full render cannot load config).
+export { inspectAgentDocs };
+
const execFileAsync = promisify(execFile);
/**
@@ -141,71 +148,103 @@ export async function runPostCodemodHooks(hooks, context) {
}
/**
- * Refresh (or, in dry-run, report) the managed agent-docs block after a version
- * bump. The block documents the INSTALLED library, so it must be re-synced on
- * EVERY upgrade path, including the no-codemods short-circuits (#4168).
+ * @typedef {object} AgentDocsRefreshPlan
+ * @property {string} cwd
+ * @property {string|null} renderedBlock
+ * @property {import('./upgrade.type.mjs').AgentDocsSummary} summary
+ */
+
+/**
+ * Compute the expected managed block and report staleness without writing.
+ * Apply-mode callers commit the prepared bytes only after codemods and hooks
+ * succeed.
*
- * @param {{cwd: string, installedVersion: string, apply: boolean}} ctx
- * @returns {Promise<import('./upgrade.type.mjs').AgentDocsSummary>}
+ * @param {{cwd: string, installedVersion: string, apply: boolean, fresh?: boolean}} ctx
+ * @returns {Promise<AgentDocsRefreshPlan>}
*/
-export async function refreshAgentDocs({cwd, installedVersion, apply}) {
- const inspection = inspectAgentDocs(cwd, installedVersion);
+export async function prepareAgentDocsRefresh({
+ cwd,
+ installedVersion,
+ apply,
+ fresh = false,
+}) {
+ const initial = inspectAgentDocs(cwd, installedVersion);
/** @type {import('./upgrade.type.mjs').AgentDocsSummary} */
const summary = {
- status: inspection.status,
+ status: initial.status,
installedVersion,
- fromVersions: inspection.blockVersions,
+ fromVersions: initial.blockVersions,
files: [],
refreshed: false,
action: 'none',
};
- // Never initialized — don't silently create docs during an upgrade; nudge.
- if (inspection.status === 'missing') {
+ if (initial.status === 'missing') {
summary.action = 'nudge-init';
logger.warn(
`No Astryx agent-docs block found — AI agents have no component index. Run \`${formatCliCommand('astryx init --features agents')}\` to install it.`,
);
- return summary;
+ return {cwd, renderedBlock: null, summary};
}
- if (inspection.status === 'current') return summary;
+ let renderedBlock;
+ try {
+ renderedBlock = await renderAgentDocsBlock(cwd, {
+ installedVersion,
+ fresh,
+ });
+ } catch {
+ summary.action = 'error';
+ summary.files = initial.files.map(file => file.path);
+ logger.warn(
+ `Could not render the expected agent docs. Run \`${formatCliCommand('astryx init --features agents')}\` to update them manually.`,
+ );
+ return {cwd, renderedBlock: null, summary};
+ }
- // Stale.
+ const inspection = inspectAgentDocs(cwd, installedVersion, renderedBlock);
+ summary.status = inspection.status;
+ summary.fromVersions = inspection.blockVersions;
summary.files = inspection.staleFiles;
- const fromLabel = summary.fromVersions.length
- ? `v${summary.fromVersions.join(', v')}`
- : 'an unknown version';
+ if (inspection.status === 'current') return {cwd, renderedBlock, summary};
+ summary.action = 'would-refresh';
if (!apply) {
- summary.action = 'would-refresh';
logger.warn(
- `Agent docs are stale: block is at ${fromLabel}, installed is v${installedVersion}. Re-run with --apply to refresh (${summary.files.join(', ')}).`,
+ `Agent docs differ from the installed Astryx and integration configuration. Re-run with --apply to refresh (${summary.files.join(', ')}).`,
);
- return summary;
}
+ return {cwd, renderedBlock, summary};
+}
+
+/**
+ * Commit a prepared agent-doc refresh.
+ * @param {AgentDocsRefreshPlan} plan
+ * @returns {import('./upgrade.type.mjs').AgentDocsSummary}
+ */
+export function applyAgentDocsRefresh(plan) {
+ const {cwd, renderedBlock, summary} = plan;
+ if (summary.action !== 'would-refresh' || renderedBlock == null)
+ return summary;
- // Apply: rewrite only files that already carry a marker (onlyReplace).
try {
const written = installAgentDocs(cwd, {
onlyReplace: true,
- topics: (await loadDocsCatalog(cwd)).names(),
+ renderedBlock,
});
summary.refreshed = written.length > 0;
summary.files = written;
+ summary.action = summary.refreshed ? 'refreshed' : 'error';
if (summary.refreshed) {
- summary.action = 'refreshed';
- logger.log(
- `✓ Agent docs refreshed → v${installedVersion} (from ${fromLabel}): ${written.join(', ')}`,
- );
+ logger.log(`✓ Agent docs refreshed → ${written.join(', ')}`);
} else {
- summary.action = 'error';
logger.warn(
- `Agent docs look stale but couldn't be refreshed — the <!-- ASTRYX:START -->/<!-- ASTRYX:END --> markers may be malformed. Run \`${formatCliCommand('astryx init --features agents')}\` to reinstall the block.`,
+ `Agent docs look stale but couldn't be refreshed. Run \`${formatCliCommand('astryx init --features agents')}\` to reinstall the block.`,
);
}
} catch {
summary.action = 'error';
+ summary.refreshed = false;
logger.warn(
`Could not refresh agent docs. Run \`${formatCliCommand('astryx init --features agents')}\` to update them manually.`,
);
@@ -276,7 +315,10 @@ export async function runCoreCodemods(versionManifests, {apply, path: srcPath, c
* @returns {Promise<{postCodemodHooks: import('../../authoring/config/type').PostCodemodHook[], integrations: import('../../foundation/integrations/integrations.mjs').LoadedIntegration[]}>}
*/
export async function loadProjectContext(cwd, extraIntegrationSpecs = []) {
- const project = await Project.load(cwd);
+ // The CLI debug preflight may already have imported this config before core
+ // CONFIG codemods run. Upgrade needs the bytes now on disk, not that module
+ // cache entry; ordinary Project discovery remains cached by default.
+ const project = await Project.load(cwd, {fresh: true});
const postCodemodHooks = project.config.hooks?.postCodemod ?? [];
const integrationSpecs = uniqueFiles([
...(project.integrations ?? []),
diff --git a/packages/cli/api/upgrade/run/run.mjs b/packages/cli/api/upgrade/run/run.mjs
index 921b54c948..2ec0b6bc73 100644
--- a/packages/cli/api/upgrade/run/run.mjs
+++ b/packages/cli/api/upgrade/run/run.mjs
@@ -9,18 +9,20 @@
* plus the early up_to_date exit — each delegated to the `status` leaf so the
* status envelope + its human lines live in one place.
*
- * Pipeline (--apply): detect installed core → refresh agent-docs (every path) →
- * run CORE codemods (before Project.load, so a core CONFIG codemod can repair an
- * otherwise-invalid config) → load config → discover + run INTEGRATION codemods
- * → post-codemod hooks. Integration DISCOVERY errors skip that integration;
- * EXECUTION errors abort. Errors throw AstryxError (stable code); human progress
- * is emitted through the shared `logger` (silent by default).
+ * Pipeline (--apply): detect installed core → run CORE codemods (before
+ * Project.load, so a core CONFIG codemod can repair an otherwise-invalid
+ * config) → load config → discover + run INTEGRATION codemods → post-codemod
+ * hooks → render + refresh agent docs from final post-upgrade state.
+ * Integration DISCOVERY errors skip that integration; execution errors abort
+ * before the agent-doc write.
*/
import * as path from 'node:path';
import {
detectInstalledTargetVersion,
- refreshAgentDocs,
+ prepareAgentDocsRefresh,
+ applyAgentDocsRefresh,
+ inspectAgentDocs,
uniqueFiles,
runPostCodemodHooks,
getCoreVersionManifests,
@@ -88,12 +90,21 @@ export async function run(options = {}, {cwd = process.cwd()} = {}) {
logger.log(`From version: ${currentVersion}`);
logger.log(`Installed target: ${targetVersion} (${installed.packageName})`);
- // Sync the managed agent-docs block FIRST — it documents the installed library
- // independent of codemods, so refresh on every path (issue #4168).
- const agentDocs = await refreshAgentDocs({cwd, installedVersion: targetVersion, apply: apply || false});
-
+ // Up-to-date check — no codemods will run, safe to render agent docs now.
if (!options.force && semverGte(currentVersion, targetVersion)) {
- return statusUpToDate({from: currentVersion, to: targetVersion, agentDocs});
+ const agentDocsPlan = await prepareAgentDocsRefresh({
+ cwd,
+ installedVersion: targetVersion,
+ apply,
+ });
+ const agentDocs = apply
+ ? applyAgentDocsRefresh(agentDocsPlan)
+ : agentDocsPlan.summary;
+ return statusUpToDate({
+ from: currentVersion,
+ to: targetVersion,
+ agentDocs,
+ });
}
const versionManifests = await getCoreVersionManifests(currentVersion, targetVersion);
@@ -152,13 +163,23 @@ export async function run(options = {}, {cwd = process.cwd()} = {}) {
// change (the codemod that would repair it).
const codemodWouldFixConfig = hasCoreConfigCodemod && (coreResult?.totalFilesChanged ?? 0) > 0;
if (!apply && codemodWouldFixConfig) {
+ // Lightweight inspection — no config/Project load (config is still broken
+ // in dry-run; the codemod previewed a fix but did not write it).
+ const inspection = inspectAgentDocs(cwd, targetVersion);
return statusConfigFixable(
{
from: currentVersion,
to: targetVersion,
configError: configErr.message,
configCodemods: coreConfigCodemodNames,
- agentDocs,
+ agentDocs: /** @type {import('../upgrade.type.mjs').AgentDocsSummary} */ ({
+ status: inspection.status,
+ installedVersion: targetVersion,
+ fromVersions: inspection.blockVersions,
+ files: inspection.staleFiles,
+ refreshed: false,
+ action: inspection.status === 'missing' ? 'nudge-init' : 'none',
+ }),
},
);
}
@@ -193,7 +214,20 @@ export async function run(options = {}, {cwd = process.cwd()} = {}) {
}
if (versionManifests.length === 0 && !hasIntegrationCodemods) {
- return statusNoCodemods({from: currentVersion, to: targetVersion, agentDocs});
+ // No codemods in range — safe to render agent docs from current state.
+ const agentDocsPlan = await prepareAgentDocsRefresh({
+ cwd,
+ installedVersion: targetVersion,
+ apply,
+ });
+ const agentDocs = apply
+ ? applyAgentDocsRefresh(agentDocsPlan)
+ : agentDocsPlan.summary;
+ return statusNoCodemods({
+ from: currentVersion,
+ to: targetVersion,
+ agentDocs,
+ });
}
if (totalTransforms === 0 && totalOptional === 0) {
@@ -217,8 +251,11 @@ export async function run(options = {}, {cwd = process.cwd()} = {}) {
to: targetVersion,
codemods: totalTransforms,
integrations: integrations.map(i => i.name ?? i.__spec),
- agentDocsRefreshed: agentDocs.refreshed,
- agentDocs,
+ agentDocsRefreshed: false,
+ agentDocs: /** @type {import('../upgrade.type.mjs').AgentDocsSummary} */ ({
+ status: 'current', installedVersion: targetVersion,
+ fromVersions: [], files: [], refreshed: false, action: 'none',
+ }),
};
let integrationResult = null;
@@ -260,6 +297,19 @@ export async function run(options = {}, {cwd = process.cwd()} = {}) {
throw new AstryxError(msg, undefined, ERROR_CODES.ERR_CODEMOD_FAILED);
}
+ // All codemods + hooks succeeded — render from final post-upgrade state.
+ const agentDocsPlan = await prepareAgentDocsRefresh({
+ cwd,
+ installedVersion: targetVersion,
+ apply,
+ fresh: true,
+ });
+ const completedAgentDocs = apply
+ ? applyAgentDocsRefresh(agentDocsPlan)
+ : agentDocsPlan.summary;
+ receipt.agentDocs = completedAgentDocs;
+ receipt.agentDocsRefreshed = completedAgentDocs.refreshed;
+
logger.log((apply ? 'Upgrade complete' : 'Dry run complete') + '\n');
return {
type: 'upgrade.run',
diff --git a/packages/cli/api/upgrade/upgrade.doc.mjs b/packages/cli/api/upgrade/upgrade.doc.mjs
index d4dcb467d1..740eaf9eb3 100644
--- a/packages/cli/api/upgrade/upgrade.doc.mjs
+++ b/packages/cli/api/upgrade/upgrade.doc.mjs
@@ -16,9 +16,11 @@ export const doc = {
'Run version-migration codemods and refresh the managed agent-docs block.',
description:
'Migrates project source from a previous Astryx version to the currently ' +
- 'installed one by running the registered codemods, and refreshes the managed ' +
- 'agent-docs block on every path. Dry-run by default (previews without ' +
- 'writing); pass `apply` to write changes to disk. Core codemods run before ' +
+ 'installed one by running the registered codemods, and compares the fully ' +
+ 'rendered managed agent-docs block on every path, including same-Core ' +
+ 'integration guidance changes. Dry-run previews without writing; `apply` ' +
+ 'writes the prepared block only after selected codemods and hooks succeed. ' +
+ 'Core codemods run before ' +
'the config is loaded so a config codemod can repair an otherwise-invalid ' +
'astryx.config.',
importPath: '@astryxdesign/cli/api',
diff --git a/packages/cli/api/upgrade/upgrade.type.mjs b/packages/cli/api/upgrade/upgrade.type.mjs
index 8514b7b475..7c0a05524d 100644
--- a/packages/cli/api/upgrade/upgrade.type.mjs
+++ b/packages/cli/api/upgrade/upgrade.type.mjs
@@ -28,15 +28,15 @@
/**
* State of the managed agent-docs block (`<!-- ASTRYX:START --> … END -->`)
- * relative to the installed core version, plus what `upgrade` did about it.
- * Present on every upgrade response (run, status, and the codemod/config error
- * envelopes) because the block is refreshed independently of codemods.
+ * relative to the fully rendered block for installed Core and configured
+ * integration manifests. Present on every upgrade response. Dry-run only
+ * reports; apply writes after selected codemods and hooks succeed.
*
* - `refreshed` — a stale block was rewritten (`--apply` only).
* - `would-refresh` — a stale block was detected in dry-run; nothing written.
* - `nudge-init` — no managed block exists; user should run `init`.
- * - `error` — refresh was attempted but writing failed.
- * - `none` — nothing to do (block already current).
+ * - `error` — the expected block could not be rendered or written.
+ * - `none` — nothing to do (block already matches expected content).
*
* @typedef {object} AgentDocsSummary
* @property {'missing' | 'stale' | 'current'} status
diff --git a/packages/cli/assets/docs/cli-integrations.doc.mjs b/packages/cli/assets/docs/cli-integrations.doc.mjs
index efaa1d5500..5f550317f5 100644
--- a/packages/cli/assets/docs/cli-integrations.doc.mjs
+++ b/packages/cli/assets/docs/cli-integrations.doc.mjs
@@ -147,6 +147,29 @@ export const docs = {
},
],
},
+ {
+ title: 'Agent Docs',
+ category: 'guide',
+ content: [
+ {
+ type: 'prose',
+ text: 'An integration can append a small amount of static package guidance to the end of the managed agent block through `agentDocs.append` in its default manifest. The CLI owns the section heading, package-labeled bullets, placement, markers, target files, and writes.',
+ },
+ {
+ type: 'code',
+ lang: 'typescript',
+ code: "// astryx.integration.ts\nimport type {AstryxIntegration} from '@astryxdesign/cli/authoring';\n\nexport default {\n components: './components',\n agentDocs: {\n append: ['Run acme verify before finishing.'],\n },\n} satisfies AstryxIntegration;",
+ },
+ {
+ type: 'prose',
+ text: '`append` is optional and may contain at most 8 lines per integration. A line is a trimmed, non-blank plain string of at most 240 Unicode code points with no line separators, control characters, NUL, or Astryx/XDS managed-marker text. A configured project may render at most 32 integration lines total.',
+ },
+ {
+ type: 'prose',
+ text: '`astryx init` renders the installed manifests. `astryx upgrade` compares the same expected block even when the Core version is unchanged, so a line addition, removal, reorder, or edit appears in dry-run and is written with `--apply`. When codemods or post-codemod hooks run, the block is refreshed only after they succeed; no integration codemod is required for guidance changes.',
+ },
+ ],
+ },
{
title: 'Codemods',
category: 'guide',
diff --git a/packages/cli/assets/docs/working-with-ai.doc.mjs b/packages/cli/assets/docs/working-with-ai.doc.mjs
index 1c07146573..08246fc846 100644
--- a/packages/cli/assets/docs/working-with-ai.doc.mjs
+++ b/packages/cli/assets/docs/working-with-ai.doc.mjs
@@ -38,7 +38,7 @@ export const docs = {
},
{
type: 'prose',
- text: 'That\'s it. The `init --features agents` command generates everything your AI needs (component index, behavioral rules, CLI reference) pulled from your installed version. After a version bump, run it again to update in place.',
+ text: "That's it. The `init --features agents` command generates everything your AI needs (component index, behavioral rules, CLI reference, and package guidance from configured integrations) from the installed project. After a dependency bump, `astryx upgrade` reports a stale block and `astryx upgrade --apply` refreshes it.",
},
{
type: 'prose',
@@ -72,7 +72,7 @@ npx @astryxdesign/cli init --features agents --agent codex # AGENTS.md (Copi
},
{
type: 'prose',
- text: 'It also includes rules that prevent common mistakes (no raw divs, no style={{}}, use tokens not magic values) and a CLI quick reference. After setup, you shouldn\'t need to manually correct your AI on these conventions; the agent docs handle it at the system level.',
+ text: "It also includes rules that prevent common mistakes (no raw divs, no style={{}}, use tokens not magic values), a CLI quick reference, and package-labeled integration guidance when a configured manifest declares `agentDocs`. After setup, you shouldn't need to manually correct your AI on these conventions; the agent docs handle it at the system level.",
},
],
},
diff --git a/packages/cli/authoring/integration/integration.doc.mjs b/packages/cli/authoring/integration/integration.doc.mjs
index dbd0dfbf66..653102e879 100644
--- a/packages/cli/authoring/integration/integration.doc.mjs
+++ b/packages/cli/authoring/integration/integration.doc.mjs
@@ -15,8 +15,8 @@ export const doc = {
description:
'The astryx.integration.* manifest that sits beside an integration ' +
"package's package.json. Points the CLI at the package's components, " +
- 'templates, codemods, and doc topics, and where to file issues. Every ' +
- 'field is optional.',
+ 'templates, codemods, doc topics, and managed agent guidance, and where to ' +
+ 'file issues. Every field is optional.',
appliesTo: 'astryx.integration.{ts,mjs,js}',
fields: [
{
@@ -46,6 +46,13 @@ export const doc = {
'Relative path to the reference-docs (topics) root (resolved to absolute). Every {topic}.doc.{ts,mjs,js} under it is served by `astryx docs` beside the built-in topics; a topic may also declare `replaces` or `extends` to take the place of a built-in one or merge onto it.',
example: "'./docs'",
},
+ {
+ name: 'agentDocs',
+ type: '{ append?: readonly string[] }',
+ description:
+ 'Static package guidance appended to the end of the managed agent block. The CLI owns the section heading, package labels, bullets, target files, and writes.',
+ example: "{ append: ['Run acme verify.'] }",
+ },
{
name: 'issuesUrl',
type: 'string',
@@ -61,6 +68,9 @@ export const doc = {
templates: './src/templates',
codemods: './codemods',
docs: './docs',
+ agentDocs: {
+ append: ['Run acme verify before finishing.'],
+ },
issuesUrl: 'https://github.com/acme/widgets/issues',
};`,
},
@@ -73,6 +83,15 @@ export const doc = {
"package's package.json, not from this manifest. The manifest only " +
'declares where the CLI finds each kind of artifact.',
},
+ {
+ type: 'prose',
+ text:
+ '`agentDocs.append` may contain at most eight lines. Each line is a ' +
+ 'trimmed, non-blank string of at most 240 Unicode code points with no ' +
+ 'line separators, control characters, NUL, or Astryx/XDS managed-marker ' +
+ 'text. The configured project may contain at most 32 integration lines ' +
+ 'total.',
+ },
{
type: 'prose',
text:
diff --git a/packages/cli/authoring/integration/parse.test.mjs b/packages/cli/authoring/integration/parse.test.mjs
index 3a4a9fc444..99d4db80c7 100644
--- a/packages/cli/authoring/integration/parse.test.mjs
+++ b/packages/cli/authoring/integration/parse.test.mjs
@@ -55,7 +55,14 @@ describe('parseIntegration (load boundary)', () => {
// exist yet. A hand-maintained list would pass today and start warning
// falsely about a supported field the day someone forgot to update it.
const everyKnownKey = Object.fromEntries(
- Object.keys(integrationSchema.shape).map(key => [key, './x']),
+ Object.keys(integrationSchema.shape).map(key => [
+ key,
+ key === 'issuesUrl'
+ ? 'https://example.com/issues'
+ : key === 'agentDocs'
+ ? {}
+ : './x',
+ ]),
);
expect(unknownIntegrationKeys(everyKnownKey)).toEqual([]);
});
@@ -69,4 +76,74 @@ describe('parseIntegration (load boundary)', () => {
it('rejects a non-URL issuesUrl', () => {
expect(reason({issuesUrl: 'nope'})).toContain('issuesUrl');
});
+
+ it('accepts an optional append array as manifest data', () => {
+ expect(
+ parseIntegration({
+ agentDocs: {
+ append: ['Run acme verify before finishing.'],
+ },
+ }),
+ ).toEqual({
+ agentDocs: {
+ append: ['Run acme verify before finishing.'],
+ },
+ });
+ });
+
+ it('strips future nested agentDocs keys without rejecting append', () => {
+ expect(
+ parseIntegration({
+ agentDocs: {
+ append: ['Run acme verify before finishing.'],
+ futureField: true,
+ },
+ }),
+ ).toEqual({
+ agentDocs: {
+ append: ['Run acme verify before finishing.'],
+ },
+ });
+ });
+
+ it('caps append at eight lines', () => {
+ expect(
+ reason({
+ agentDocs: {
+ append: Array.from({length: 9}, (_, index) => `after ${index}`),
+ },
+ }),
+ ).toMatch(/at most 8 lines/);
+ });
+
+ it('counts Unicode code points rather than UTF-16 code units', () => {
+ expect(() =>
+ parseIntegration({agentDocs: {append: ['😀'.repeat(240)]}}),
+ ).not.toThrow();
+ expect(reason({agentDocs: {append: ['😀'.repeat(241)]}})).toMatch(
+ /240 Unicode code points/,
+ );
+ });
+
+ it.each([
+ ['', /blank/],
+ [' ', /blank/],
+ [' leading', /surrounding whitespace/],
+ ['trailing ', /surrounding whitespace/],
+ ['two\nlines', /single line|line separators/],
+ ['two\rlines', /control characters|line separators/],
+ ['unicode\u2028separator', /single line/],
+ ['nul\u0000byte', /NUL/],
+ ['control\u0001byte', /control characters/],
+ ['control\u0085byte', /control characters/],
+ ['<!-- ASTRYX:START -->', /managed marker text/],
+ ['XDS:END', /managed marker text/],
+ ])('rejects forbidden agentDocs line %#', (line, message) => {
+ expect(reason({agentDocs: {append: [line]}})).toMatch(message);
+ });
+
+ it('rejects functions and other non-data shapes', () => {
+ expect(reason({agentDocs: () => ({append: ['x']})})).toContain('agentDocs');
+ expect(reason({agentDocs: {append: ['ok', 42]}})).toContain('append');
+ });
});
diff --git a/packages/cli/authoring/integration/schema.mjs b/packages/cli/authoring/integration/schema.mjs
index 4ce0160684..cf10f460b1 100644
--- a/packages/cli/authoring/integration/schema.mjs
+++ b/packages/cli/authoring/integration/schema.mjs
@@ -14,10 +14,66 @@
*/
import {z} from 'zod';
+import {formatZodError} from '../_shared/errors.mjs';
/** @typedef {import('./type').AstryxIntegration} AstryxIntegration */
-// Unknown keys are stripped rather than rejected. `.strict()` made a key from a
+const MAX_AGENT_DOC_LINES = 8;
+const MAX_AGENT_DOC_LINE_CODE_POINTS = 240;
+const MANAGED_MARKER_TEXT = /(?:ASTRYX|XDS):(START|END)/u;
+
+/**
+ * @param {string} value
+ * @returns {string|null}
+ */
+function invalidAgentDocLine(value) {
+ if (value.length === 0 || value.trim().length === 0)
+ return 'must not be blank';
+ if (value !== value.trim()) return 'must not have surrounding whitespace';
+ for (const character of value) {
+ const codePoint = character.codePointAt(0) ?? 0;
+ if (codePoint === 0) return 'must not contain NUL';
+ if (codePoint === 0x2028 || codePoint === 0x2029) {
+ return 'must be a single line';
+ }
+ if (codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f)) {
+ return 'must not contain control characters or line separators';
+ }
+ }
+ if (MANAGED_MARKER_TEXT.test(value))
+ return 'must not contain managed marker text';
+ const codePoints = [...value].length;
+ if (codePoints > MAX_AGENT_DOC_LINE_CODE_POINTS) {
+ return `must contain at most ${MAX_AGENT_DOC_LINE_CODE_POINTS} Unicode code points (received ${codePoints})`;
+ }
+ return null;
+}
+
+const agentDocLineSchema = z.string().superRefine((value, ctx) => {
+ const message = invalidAgentDocLine(value);
+ if (message) ctx.addIssue({code: 'custom', message});
+});
+
+export const agentDocsSchema = z.object({
+ append: z
+ .array(agentDocLineSchema)
+ .max(
+ MAX_AGENT_DOC_LINES,
+ `append may contain at most ${MAX_AGENT_DOC_LINES} lines`,
+ )
+ .readonly()
+ .optional(),
+});
+
+export const integrationBaseSchema = z.object({
+ components: z.string().optional(),
+ templates: z.string().optional(),
+ codemods: z.string().optional(),
+ docs: z.string().optional(),
+ issuesUrl: z.string().url().optional(),
+});
+
+// Unknown top-level keys are stripped rather than rejected. `.strict()` made a key from a
// newer CLI a hard parse failure, and a manifest that fails to parse
// contributes NOTHING — an integration that added one field lost its
// components, templates and codemods too, on every consumer resolving an older
@@ -26,14 +82,35 @@ import {z} from 'zod';
// still loaded and the unknown key is reported as a warning by
// `unknownIntegrationKeys`. Known keys stay strictly typed: a `components: 42`
// IS an authoring mistake and still fails here.
-export const integrationSchema = z.object({
- components: z.string().optional(),
- templates: z.string().optional(),
- codemods: z.string().optional(),
- docs: z.string().optional(),
- issuesUrl: z.string().url().optional(),
+export const integrationSchema = integrationBaseSchema.extend({
+ agentDocs: agentDocsSchema.optional(),
});
+/**
+ * Parse every default-manifest field except the independently isolated
+ * `agentDocs` contribution.
+ * @param {unknown} input
+ * @param {string} label
+ * @returns {Omit<AstryxIntegration, 'agentDocs'>}
+ */
+export function parseIntegrationBase(input, label) {
+ const result = integrationBaseSchema.safeParse(input);
+ if (!result.success) throw new Error(formatZodError(label, result.error));
+ return result.data;
+}
+
+/**
+ * Parse only the optional agent-doc contribution.
+ * @param {unknown} input
+ * @param {string} label
+ * @returns {NonNullable<AstryxIntegration['agentDocs']>}
+ */
+export function parseAgentDocsField(input, label) {
+ const result = agentDocsSchema.safeParse(input);
+ if (!result.success) throw new Error(formatZodError(label, result.error));
+ return result.data;
+}
+
/**
* Compile-time drift-lock: sealed schema must infer exactly {@link AstryxIntegration}.
*
diff --git a/packages/cli/authoring/integration/type.ts b/packages/cli/authoring/integration/type.ts
index ddfaf5bd65..1aacb32ef1 100644
--- a/packages/cli/authoring/integration/type.ts
+++ b/packages/cli/authoring/integration/type.ts
@@ -26,6 +26,10 @@ export interface AstryxIntegration {
* serves from `astryx docs`, alongside the built-in ones. A topic may also
* `replace` or `extend` a built-in topic; see the ReferenceDoc type. */
docs?: string;
+ /** Static package guidance appended to the CLI-owned managed agent block. */
+ agentDocs?: {
+ append?: readonly string[];
+ };
/** Where to file issues/feedback for this integration. */
issuesUrl?: string;
}
diff --git a/packages/cli/clients/cli/commands/init.doc.mjs b/packages/cli/clients/cli/commands/init.doc.mjs
index 041f7b419b..0d0c521f77 100644
--- a/packages/cli/clients/cli/commands/init.doc.mjs
+++ b/packages/cli/clients/cli/commands/init.doc.mjs
@@ -16,8 +16,9 @@ export const doc = {
summary: 'Initialize the design system in your project',
description:
'Non-interactive project setup (no prompts, so it behaves the same for humans, ' +
- 'agents, and CI). By default it installs the AGENTS.md/CLAUDE.md agent-docs and ' +
- 'prints getting-started guidance; features/--all add theme and page-building ' +
+ 'agents, and CI). By default it installs the AGENTS.md/CLAUDE.md agent-docs, ' +
+ 'including guidance from configured integrations, and prints getting-started ' +
+ 'guidance; features/--all add theme and page-building ' +
'guidance and can scaffold a starter template.',
fn: 'init',
options: [
diff --git a/packages/cli/clients/cli/commands/upgrade.config-ordering.test.mjs b/packages/cli/clients/cli/commands/upgrade.config-ordering.test.mjs
index 67a60ff90b..12f0b1200c 100644
--- a/packages/cli/clients/cli/commands/upgrade.config-ordering.test.mjs
+++ b/packages/cli/clients/cli/commands/upgrade.config-ordering.test.mjs
@@ -28,6 +28,8 @@ import * as fs from 'node:fs';
import * as path from 'node:path';
import {Command} from 'commander';
import {registerUpgrade} from './upgrade.mjs';
+import {Project} from '../../../foundation/config/project.mjs';
+import {generateCompressedIndex} from '../../../foundation/agent-docs/agent-docs.mjs';
let tmpDir;
let originalCwd;
@@ -272,4 +274,67 @@ describe('upgrade — core codemods run before config load', () => {
// Completed as a run (the config codemod is a no-op on an already-migrated config).
expect(result.type).toBe('upgrade.run');
});
+
+ it('--apply: legacy config + integration agentDocs.append renders the integration line AFTER config repair', async () => {
+ writePkg();
+ writeInstalledCore('0.1.3');
+ writeConfig(`export default {
+ integrations: ['@acme/widgets'],
+ layout: {
+ components: {
+ KpiCard: '@/components/KpiCard',
+ },
+ },
+};
+`);
+ writeSource();
+
+ const pkgDir = path.join(tmpDir, 'node_modules', '@acme', 'widgets');
+ fs.mkdirSync(pkgDir, {recursive: true});
+ fs.writeFileSync(
+ path.join(pkgDir, 'package.json'),
+ JSON.stringify({name: '@acme/widgets', version: '1.0.0'}),
+ );
+ fs.writeFileSync(
+ path.join(pkgDir, 'astryx.integration.mjs'),
+ `export default {agentDocs: {append: ['Widget integration guidance.']}};\n`,
+ );
+
+ const staleBlock = generateCompressedIndex('0.1.2');
+ fs.writeFileSync(
+ path.join(tmpDir, 'AGENTS.md'),
+ `# Agents\n\n${staleBlock}\n`,
+ );
+
+ // The real CLI debug preflight imports config before dispatch. Cache the
+ // invalid legacy module so the post-codemod load must be explicitly fresh.
+ await expect(Project.load(tmpDir)).rejects.toThrow();
+
+ const result = await runJson([
+ '--json',
+ 'upgrade',
+ '--from',
+ '0.1.2',
+ '--path',
+ 'src',
+ '--apply',
+ ]);
+
+ expect(result).not.toBeNull();
+ expect(result.error).toBeUndefined();
+ expect(exitCode).not.toBe(1);
+ expect(result.type).toBe('upgrade.run');
+ expect(result.data.agentDocs.action).not.toBe('error');
+
+ const agents = fs.readFileSync(path.join(tmpDir, 'AGENTS.md'), 'utf-8');
+ expect(agents).toContain('Widget integration guidance.');
+ expect(agents).toContain('INTEGRATIONS:');
+
+ const onDisk = fs.readFileSync(
+ path.join(tmpDir, 'astryx.config.mjs'),
+ 'utf-8',
+ );
+ expect(onDisk).toContain('experimental');
+ expect(onDisk).not.toMatch(/layout\s*:/);
+ });
});
diff --git a/packages/cli/clients/cli/commands/upgrade.doc.mjs b/packages/cli/clients/cli/commands/upgrade.doc.mjs
index 368d199351..81f7d2c64f 100644
--- a/packages/cli/clients/cli/commands/upgrade.doc.mjs
+++ b/packages/cli/clients/cli/commands/upgrade.doc.mjs
@@ -16,8 +16,9 @@ export const doc = {
summary: 'Run codemods to migrate between versions',
description:
'Migrates project source from a previous Astryx version to the installed one by ' +
- 'running the registered codemods, and refreshes the managed agent-docs block. ' +
- 'Dry-run by default (preview only); pass --apply to write changes to disk.',
+ 'running the registered codemods, and refreshes the fully rendered managed ' +
+ 'agent-docs block when Core or configured integration guidance changes. ' +
+ 'Dry-run by default; --apply writes the block after selected codemods and hooks succeed.',
fn: 'upgrade',
options: [
{
diff --git a/packages/cli/clients/cli/commands/upgrade.integration-policy.test.mjs b/packages/cli/clients/cli/commands/upgrade.integration-policy.test.mjs
index 10fcb55752..21311b6c3d 100644
--- a/packages/cli/clients/cli/commands/upgrade.integration-policy.test.mjs
+++ b/packages/cli/clients/cli/commands/upgrade.integration-policy.test.mjs
@@ -17,6 +17,11 @@ import * as fs from 'node:fs';
import * as path from 'node:path';
import {Command} from 'commander';
import {registerUpgrade} from './upgrade.mjs';
+import {Project} from '../../../foundation/config/project.mjs';
+import {
+ generateCompressedIndex,
+ renderAgentDocsBlock,
+} from '../../../foundation/agent-docs/agent-docs.mjs';
let tmpDir;
let originalCwd;
@@ -64,15 +69,21 @@ function writeSource() {
/**
* Scaffold a consumer + an installed integration package with codemods.
* @param {Object<string,string>} codemodFiles "<version>/<id>.mjs" -> body
+ * @param {{agentDocs?: {append?: string[]}, failingPostCodemodHook?: boolean}} [options]
*/
-function scaffoldIntegration(codemodFiles) {
+function scaffoldIntegration(
+ codemodFiles,
+ {agentDocs, failingPostCodemodHook = false} = {},
+) {
fs.writeFileSync(
path.join(tmpDir, 'package.json'),
JSON.stringify({name: 'consumer'}),
);
fs.writeFileSync(
path.join(tmpDir, 'astryx.config.mjs'),
- `export default { integrations: ['@acme/widgets'] };\n`,
+ failingPostCodemodHook
+ ? `export default {integrations: ['@acme/widgets'], hooks: {postCodemod: [{name: 'fail', buildCommand: () => ({command: process.execPath, args: ['-e', 'process.exit(1)']})}]}};\n`
+ : `export default {integrations: ['@acme/widgets']};\n`,
);
const pkgDir = path.join(tmpDir, 'node_modules', '@acme', 'widgets');
fs.mkdirSync(pkgDir, {recursive: true});
@@ -80,9 +91,13 @@ function scaffoldIntegration(codemodFiles) {
path.join(pkgDir, 'package.json'),
JSON.stringify({name: '@acme/widgets', version: '1.0.0'}),
);
+ const hasCodemods = Object.keys(codemodFiles).length > 0;
fs.writeFileSync(
path.join(pkgDir, 'astryx.integration.mjs'),
- `export default { codemods: './codemods' };\n`,
+ `export default ${JSON.stringify({
+ ...(hasCodemods ? {codemods: './codemods'} : {}),
+ ...(agentDocs ? {agentDocs} : {}),
+ })};\n`,
);
for (const [rel, body] of Object.entries(codemodFiles)) {
const full = path.join(pkgDir, 'codemods', rel);
@@ -119,7 +134,273 @@ async function runJson(args) {
return null;
}
+async function writePreviousAgentBlock(currentLine, previousLine) {
+ const expected = await renderAgentDocsBlock(tmpDir, {
+ installedVersion: '0.2.0',
+ });
+ expect(expected).toContain(currentLine);
+ const previous = expected.replace(currentLine, previousLine);
+ fs.writeFileSync(path.join(tmpDir, 'AGENTS.md'), `# Agents\n\n${previous}\n`);
+ return fs.readFileSync(path.join(tmpDir, 'AGENTS.md'), 'utf-8');
+}
+
describe('upgrade integration error policy (skip + warn)', () => {
+ it('leaves the existing block untouched when project config is invalid', async () => {
+ fs.writeFileSync(
+ path.join(tmpDir, 'package.json'),
+ JSON.stringify({name: 'consumer'}),
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'astryx.config.mjs'),
+ `export default {integrations: [42]};\n`,
+ );
+ writeInstalledCore('0.2.0');
+ const before = `# Agents\n\n${generateCompressedIndex('0.2.0', {
+ agentDocs: [
+ {
+ package: '@acme/widgets',
+ append: ['existing integration line'],
+ },
+ ],
+ })}\n`;
+ fs.writeFileSync(path.join(tmpDir, 'AGENTS.md'), before);
+
+ const result = await runJson([
+ '--json',
+ 'upgrade',
+ '--from',
+ '0.2.0',
+ '--apply',
+ ]);
+
+ expect(result.data.agentDocs.action).toBe('error');
+ expect(fs.readFileSync(path.join(tmpDir, 'AGENTS.md'), 'utf-8')).toBe(before);
+ });
+
+ it('leaves the existing block untouched when integration agentDocs is invalid', async () => {
+ scaffoldIntegration({}, {
+ agentDocs: {append: ['Use the current widget workflow.']},
+ });
+ writeInstalledCore('0.2.0');
+ const before = `# Agents\n\n${generateCompressedIndex('0.2.0', {
+ agentDocs: [
+ {
+ package: '@acme/widgets',
+ append: ['Use the previous widget workflow.'],
+ },
+ ],
+ })}\n`;
+ fs.writeFileSync(path.join(tmpDir, 'AGENTS.md'), before);
+ fs.writeFileSync(
+ path.join(
+ tmpDir,
+ 'node_modules',
+ '@acme',
+ 'widgets',
+ 'astryx.integration.mjs',
+ ),
+ `export default {agentDocs: {append: [' invalid']}};\n`,
+ );
+
+ const result = await runJson([
+ '--json',
+ 'upgrade',
+ '--from',
+ '0.2.0',
+ '--apply',
+ ]);
+
+ expect(result.data.agentDocs.action).toBe('error');
+ expect(fs.readFileSync(path.join(tmpDir, 'AGENTS.md'), 'utf-8')).toBe(
+ before,
+ );
+ });
+
+ it('detects and applies a same-Core manifest guidance change without a codemod', async () => {
+ const currentLine = 'Use the current widget workflow.';
+ const previousLine = 'Use the previous widget workflow.';
+ scaffoldIntegration({}, {agentDocs: {append: [currentLine]}});
+ writeInstalledCore('0.2.0');
+ const before = await writePreviousAgentBlock(currentLine, previousLine);
+
+ const dryRun = await runJson(['--json', 'upgrade', '--from', '0.2.0']);
+ expect(dryRun.data.agentDocs.action).toBe('would-refresh');
+ expect(fs.readFileSync(path.join(tmpDir, 'AGENTS.md'), 'utf-8')).toBe(
+ before,
+ );
+
+ const applied = await runJson([
+ '--json',
+ 'upgrade',
+ '--from',
+ '0.2.0',
+ '--apply',
+ ]);
+ expect(applied.data.agentDocs.action).toBe('refreshed');
+ const after = fs.readFileSync(path.join(tmpDir, 'AGENTS.md'), 'utf-8');
+ expect(after).toContain(currentLine);
+ expect(after).not.toContain(previousLine);
+ });
+
+ it('preserves the prior block when an integration codemod fails', async () => {
+ const currentLine = 'Use the migrated widget workflow.';
+ const previousLine = 'Use the pre-migration widget workflow.';
+ scaffoldIntegration(
+ {
+ '0.2.0/fail.mjs': `export default {type: 'code', title: 'Fail', transform: () => {throw new Error('codemod boom')}};\n`,
+ },
+ {agentDocs: {append: [currentLine]}},
+ );
+ writeInstalledCore('0.2.0');
+ writeSource();
+ const before = await writePreviousAgentBlock(currentLine, previousLine);
+
+ const result = await runJson([
+ '--json',
+ 'upgrade',
+ '--from',
+ '0.1.0',
+ '--path',
+ 'src',
+ '--apply',
+ ]);
+
+ expect(result.code).toBe('ERR_CODEMOD_FAILED');
+ expect(fs.readFileSync(path.join(tmpDir, 'AGENTS.md'), 'utf-8')).toBe(
+ before,
+ );
+ });
+
+ it('preserves the prior block when a post-codemod hook fails', async () => {
+ const currentLine = 'Use the post-migration widget workflow.';
+ const previousLine = 'Use the old widget workflow.';
+ scaffoldIntegration(
+ {
+ '0.2.0/drop-foo.mjs': `export default {type: 'code', title: 'Drop foo', transform: file => file.source.replace(/foo/g, 'bar')};\n`,
+ },
+ {
+ agentDocs: {append: [currentLine]},
+ failingPostCodemodHook: true,
+ },
+ );
+ writeInstalledCore('0.2.0');
+ writeSource();
+ const before = await writePreviousAgentBlock(currentLine, previousLine);
+
+ const result = await runJson([
+ '--json',
+ 'upgrade',
+ '--from',
+ '0.1.0',
+ '--path',
+ 'src',
+ '--apply',
+ ]);
+
+ expect(result.code).toBe('ERR_CODEMOD_FAILED');
+ expect(fs.readFileSync(path.join(tmpDir, 'AGENTS.md'), 'utf-8')).toBe(
+ before,
+ );
+ });
+
+ it('renders post-codemod integration membership and order from the rewritten config', async () => {
+ fs.writeFileSync(
+ path.join(tmpDir, 'package.json'),
+ JSON.stringify({name: 'consumer'}),
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'astryx.config.mjs'),
+ `export default {integrations: ['@acme/migrator', '@acme/old']};\n`,
+ );
+
+ const writeIntegration = (name, line, codemod) => {
+ const packageDir = path.join(tmpDir, 'node_modules', ...name.split('/'));
+ fs.mkdirSync(packageDir, {recursive: true});
+ fs.writeFileSync(
+ path.join(packageDir, 'package.json'),
+ JSON.stringify({name, version: '1.0.0'}),
+ );
+ fs.writeFileSync(
+ path.join(packageDir, 'astryx.integration.mjs'),
+ `export default ${JSON.stringify({
+ ...(codemod ? {codemods: './codemods'} : {}),
+ agentDocs: {append: [line]},
+ })};\n`,
+ );
+ if (codemod) {
+ const codemodPath = path.join(
+ packageDir,
+ 'codemods',
+ '0.2.0',
+ 'replace-integrations.mjs',
+ );
+ fs.mkdirSync(path.dirname(codemodPath), {recursive: true});
+ fs.writeFileSync(codemodPath, codemod);
+ }
+ };
+
+ writeIntegration(
+ '@acme/migrator',
+ 'Migrator guidance.',
+ `export default {
+ type: 'config',
+ title: 'Replace integration order',
+ transform: file => file.source.replace(
+ "['@acme/migrator', '@acme/old']",
+ "['@acme/second', '@acme/first']",
+ ),
+};\n`,
+ );
+ writeIntegration('@acme/old', 'Old guidance.');
+ writeIntegration('@acme/second', 'Second guidance.');
+ writeIntegration('@acme/first', 'First guidance.');
+
+ writeInstalledCore('0.2.0');
+ writeSource();
+ fs.writeFileSync(
+ path.join(tmpDir, 'AGENTS.md'),
+ `# Agents\n\n${generateCompressedIndex('0.2.0', {
+ agentDocs: [{package: '@acme/old', append: ['Old guidance.']}],
+ })}\n`,
+ );
+
+ // The real CLI debug preflight loads Project before dispatch. Cache the old
+ // config here so the upgrade must explicitly reload after the CONFIG codemod.
+ await Project.load(tmpDir);
+
+ const result = await runJson([
+ '--json',
+ 'upgrade',
+ '--from',
+ '0.1.0',
+ '--path',
+ 'src',
+ '--apply',
+ ]);
+
+ expect(result.error).toBeUndefined();
+ expect(result.data.agentDocs.action).toBe('refreshed');
+ const config = fs.readFileSync(
+ path.join(tmpDir, 'astryx.config.mjs'),
+ 'utf-8',
+ );
+ expect(config.indexOf('@acme/second')).toBeLessThan(
+ config.indexOf('@acme/first'),
+ );
+ expect(config).not.toContain('@acme/migrator');
+ expect(config).not.toContain('@acme/old');
+
+ const agentDocs = fs.readFileSync(
+ path.join(tmpDir, 'AGENTS.md'),
+ 'utf-8',
+ );
+ expect(agentDocs.indexOf('Second guidance.')).toBeLessThan(
+ agentDocs.indexOf('First guidance.'),
+ );
+ expect(agentDocs).not.toContain('Migrator guidance.');
+ expect(agentDocs).not.toContain('Old guidance.');
+ });
+
it('SKIPS a broken integration codemod instead of hard-failing the upgrade', async () => {
// A codemod module whose default export is not a valid codemod result —
// a DEFINITION error. The upgrade must NOT abort; it skips the broken
diff --git a/packages/cli/clients/cli/commands/upgrade.test.mjs b/packages/cli/clients/cli/commands/upgrade.test.mjs
index 9783feedd7..3ddfd80e2c 100644
--- a/packages/cli/clients/cli/commands/upgrade.test.mjs
+++ b/packages/cli/clients/cli/commands/upgrade.test.mjs
@@ -6,7 +6,10 @@ import * as path from 'node:path';
import * as os from 'node:os';
import {Command} from 'commander';
import {registerUpgrade} from './upgrade.mjs';
-import {generateCompressedIndex} from '../../../foundation/agent-docs/agent-docs.mjs';
+import {
+ generateCompressedIndex,
+ renderAgentDocsBlock,
+} from '../../../foundation/agent-docs/agent-docs.mjs';
let tmpDir;
let originalCwd;
@@ -270,10 +273,13 @@ describe('upgrade agent-docs refresh (#4168)', () => {
expect(fs.readFileSync(path.join(tmpDir, 'AGENTS.md'), 'utf-8')).toBe(corrupted);
});
- it('stays silent when the block already matches the installed version', async () => {
+ it('stays silent when the block matches the fully rendered project state', async () => {
writePkg();
writeInstalledCore('0.0.15');
- writeAgentBlock('AGENTS.md', '0.0.15');
+ const expected = await renderAgentDocsBlock(tmpDir, {
+ installedVersion: '0.0.15',
+ });
+ fs.writeFileSync(path.join(tmpDir, 'AGENTS.md'), `# Doc\n\n${expected}\n`);
const result = await runJson(['--json', 'upgrade', '--from', '0.0.15', '--apply']);
diff --git a/packages/cli/foundation/agent-docs/agent-docs.mjs b/packages/cli/foundation/agent-docs/agent-docs.mjs
index f1bf28d492..70d84a27c2 100644
--- a/packages/cli/foundation/agent-docs/agent-docs.mjs
+++ b/packages/cli/foundation/agent-docs/agent-docs.mjs
@@ -24,6 +24,7 @@ import {findCoreDir, CLI_ROOT} from '../fs/paths.mjs';
import {assertWithin} from '../fs/path-safety.mjs';
import {getCliInvocation} from '../env/package-manager.mjs';
import {discoverComponents} from '../discovery/component-discovery.mjs';
+import {Project} from '../config/project.mjs';
import {humanLog} from '../response/json.mjs';
import {
AGENTS_MD,
@@ -48,6 +49,31 @@ import {
// clients/cli/index.mjs, tests) keep their `from './agent-docs.mjs'` paths.
export {discoverAgentDocs, isAstryxInitialized};
+const MAX_PROJECT_AGENT_DOC_LINES = 32;
+const MANAGED_MARKER_TEXT = /(?:ASTRYX|XDS):(START|END)/u;
+
+/** @param {unknown} value @returns {string} */
+function validateIntegrationLabel(value) {
+ if (typeof value !== 'string' || value.length === 0 || value !== value.trim()) {
+ throw new Error('Integration package name is not safe to render in agent docs.');
+ }
+ for (const character of value) {
+ const codePoint = character.codePointAt(0) ?? 0;
+ if (
+ codePoint <= 0x1f ||
+ (codePoint >= 0x7f && codePoint <= 0x9f) ||
+ codePoint === 0x2028 ||
+ codePoint === 0x2029
+ ) {
+ throw new Error('Integration package name is not safe to render in agent docs.');
+ }
+ }
+ if (MANAGED_MARKER_TEXT.test(value) || value.includes('`')) {
+ throw new Error('Integration package name is not safe to render in agent docs.');
+ }
+ return value;
+}
+
/**
* Find tool-specific files that import another detected agent doc.
*
@@ -186,6 +212,8 @@ export function parseBlockVersion(content) {
*
* @param {string} targetDir
* @param {string} [installedVersion] Defaults to the installed core version.
+ * @param {string} [expectedBlock] Fully rendered block for this project. When
+ * present, byte differences are stale even if the Core version is unchanged.
* @returns {{
* installedVersion: string,
* status: 'missing' | 'stale' | 'current',
@@ -194,7 +222,7 @@ export function parseBlockVersion(content) {
* blockVersions: string[],
* }}
*/
-export function inspectAgentDocs(targetDir, installedVersion) {
+export function inspectAgentDocs(targetDir, installedVersion, expectedBlock) {
const version = installedVersion ?? getXdsVersion(findCoreDir(targetDir));
/** @type {Array<{path: string, blockVersion: string|null, legacy: boolean, stale: boolean}>} */
const files = [];
@@ -213,7 +241,22 @@ export function inspectAgentDocs(targetDir, installedVersion) {
const legacy = !hasNew && hasLegacy;
const blockVersion = parseBlockVersion(content);
- const stale = legacy || blockVersion == null || blockVersion !== version;
+ let contentMatches = true;
+ if (expectedBlock != null) {
+ try {
+ const block = findManagedBlock(content);
+ contentMatches =
+ block != null &&
+ content.slice(block.start, block.end) === expectedBlock;
+ } catch {
+ contentMatches = false;
+ }
+ }
+ const stale =
+ legacy ||
+ blockVersion == null ||
+ blockVersion !== version ||
+ !contentMatches;
files.push({path: rel, blockVersion, legacy, stale});
}
@@ -327,11 +370,29 @@ export function detectStylingSystem(targetDir) {
* `getting-started` is the one it should reach for first.
*
* @param {string} version
- * @param {{coreDir?: string|null, invocation?: string, stylingSystem?: 'stylex'|'tailwind'|'css', zh?: boolean, lang?: string, topics?: string[]}} [options]
+ * @param {{coreDir?: string|null, invocation?: string, stylingSystem?: 'stylex'|'tailwind'|'css', zh?: boolean, lang?: string, topics?: string[], agentDocs?: Array<{package: string, append: readonly string[]}>}} [options]
* @returns {string}
*/
-export function generateCompressedIndex(version, {coreDir, invocation = getCliInvocation(), stylingSystem = 'css', topics} = {}) {
+export function generateCompressedIndex(
+ version,
+ {
+ coreDir,
+ invocation = getCliInvocation(),
+ stylingSystem = 'css',
+ topics,
+ agentDocs = [],
+ } = {},
+) {
const run = invocation;
+ const totalAgentDocLines = agentDocs.reduce(
+ (count, contribution) => count + contribution.append.length,
+ 0,
+ );
+ if (totalAgentDocLines > MAX_PROJECT_AGENT_DOC_LINES) {
+ throw new Error(
+ `Configured integrations contribute ${totalAgentDocLines} agent-doc lines, exceeding the ${MAX_PROJECT_AGENT_DOC_LINES}-line project limit.`,
+ );
+ }
// Annotated because MARKER_START is now an imported const: its literal type
// survives the module boundary, so the array would infer as that one literal.
/** @type {string[]} */
@@ -352,7 +413,9 @@ export function generateCompressedIndex(version, {coreDir, invocation = getCliIn
// Header — state the CLI prefix once; commands below are shown as `astryx <cmd>`.
lines.push(`Astryx v${version} · ${componentCount} components`);
- lines.push(`CLI: run every command as \`${run} <cmd>\` (shown below as \`astryx ...\`).`);
+ lines.push(
+ `CLI: run every command as \`${run} <cmd>\` (shown below as \`astryx ...\`).`,
+ );
lines.push('');
// Required setup — components ship precompiled CSS; without these imports
@@ -421,12 +484,87 @@ export function generateCompressedIndex(version, {coreDir, invocation = getCliIn
lines.push(` docs <topic> ${resolvedTopics.join(', ')}`);
}
lines.push(' swizzle <Name> eject component source for deep customization');
- lines.push(' upgrade --apply run after any @astryxdesign/core bump');
+ lines.push(' upgrade --apply run after any Astryx or integration dependency bump');
+ const appendCount = agentDocs.reduce(
+ (count, contribution) => count + contribution.append.length,
+ 0,
+ );
+ if (appendCount > 0) {
+ lines.push('');
+ lines.push('INTEGRATIONS:');
+ for (const contribution of agentDocs) {
+ for (const line of contribution.append) {
+ lines.push(`- \`${contribution.package}\`: ${line}`);
+ }
+ }
+ }
lines.push(MARKER_END);
return lines.join('\n');
}
+/**
+ * Resolve the complete expected block for one installed project.
+ *
+ * Config and integration modules load once through the existing Project seam.
+ * The returned bytes are reused for every target file.
+ *
+ * @param {string} targetDir
+ * @param {{installedVersion?: string, fresh?: boolean}} [options]
+ * @returns {Promise<string>}
+ */
+export async function renderAgentDocsBlock(
+ targetDir,
+ {installedVersion, fresh = false} = {},
+) {
+ const coreDir = findCoreDir(targetDir);
+ const version = installedVersion ?? getXdsVersion(coreDir);
+ const project = await Project.load(targetDir, {fresh});
+ const failedIntegration = project.loadedIntegrations.find(
+ integration => integration.__loadError != null,
+ );
+ if (failedIntegration) {
+ const packageLabel = validateIntegrationLabel(
+ failedIntegration.name ?? failedIntegration.__spec,
+ );
+ throw new Error(
+ `Cannot render agent docs because integration ${packageLabel} failed to load: ${failedIntegration.__loadError}`,
+ );
+ }
+ const invalidAgentDocs = project.loadedIntegrations.find(
+ integration => integration.__agentDocsError != null,
+ );
+ if (invalidAgentDocs) {
+ const packageLabel = validateIntegrationLabel(
+ invalidAgentDocs.name ?? invalidAgentDocs.__spec,
+ );
+ throw new Error(
+ `Cannot render agent docs because integration ${packageLabel} has invalid agentDocs: ${invalidAgentDocs.__agentDocsError}`,
+ );
+ }
+ const topics = (await project.docs()).names();
+ const agentDocs = project.loadedIntegrations.flatMap(integration => {
+ const append = integration.agentDocs?.append ?? [];
+ if (append.length === 0) return [];
+ return [
+ {
+ package: validateIntegrationLabel(
+ integration.name ?? integration.__spec,
+ ),
+ append,
+ },
+ ];
+ });
+
+ return generateCompressedIndex(version, {
+ coreDir,
+ invocation: getCliInvocation(targetDir),
+ stylingSystem: detectStylingSystem(targetDir),
+ topics,
+ agentDocs,
+ });
+}
+
/**
* Get Astryx version from core package.
* @param {string|null} coreDir
@@ -607,14 +745,36 @@ export function removeAgentDocs(targetDir) {
* @param {string[]} [options.topics] - Doc topics to list in the block; defaults
* to the CLI's own. Pass the project's catalog (`(await project.docs()).names()`)
* so an integration's topics reach the agent.
+ * @param {string} [options.renderedBlock] - Fully rendered expected block. Init
+ * and upgrade pass one shared block to every target.
* @returns {string[]} List of files written
*/
-export function installAgentDocs(targetDir, {zh = false, lang, agent, paths, onlyReplace = false, topics} = {}) {
+export function installAgentDocs(
+ targetDir,
+ {
+ zh = false,
+ lang,
+ agent,
+ paths,
+ onlyReplace = false,
+ topics,
+ renderedBlock,
+ } = {},
+) {
const coreDir = findCoreDir(targetDir);
const version = getXdsVersion(coreDir);
const invocation = getCliInvocation(targetDir);
const stylingSystem = detectStylingSystem(targetDir);
- const compressedIndex = generateCompressedIndex(version, {coreDir, zh, lang, invocation, stylingSystem, topics});
+ const compressedIndex =
+ renderedBlock ??
+ generateCompressedIndex(version, {
+ coreDir,
+ zh,
+ lang,
+ invocation,
+ stylingSystem,
+ topics,
+ });
/** @type {string[]} */
const written = [];
diff --git a/packages/cli/foundation/agent-docs/agent-docs.test.mjs b/packages/cli/foundation/agent-docs/agent-docs.test.mjs
index 340fd99e94..7906442577 100644
--- a/packages/cli/foundation/agent-docs/agent-docs.test.mjs
+++ b/packages/cli/foundation/agent-docs/agent-docs.test.mjs
@@ -17,6 +17,7 @@ import {
discoverAgentDocs,
resolveAgentPaths,
parseBlockVersion,
+ renderAgentDocsBlock,
inspectAgentDocs,
isAstryxInitialized,
} from './agent-docs.mjs';
@@ -96,7 +97,7 @@ describe('generateCompressedIndex', () => {
it('includes upgrade command and migration rule', () => {
const result = generateCompressedIndex('1.0.0');
expect(result).toContain('upgrade --apply');
- expect(result).toMatch(/after any @astryxdesign\/core bump/);
+ expect(result).toMatch(/after any Astryx or integration dependency bump/);
});
it('states the invocation once in the CLI header (yarn)', () => {
@@ -155,6 +156,175 @@ describe('generateCompressedIndex', () => {
it('omits the line entirely when the project has no topics', () => {
expect(topicLine(generateCompressedIndex('1.0.0', {topics: []}))).toBe('');
});
+
+ it('is byte-identical when integrations contribute no lines', () => {
+ const options = {
+ invocation: 'npx @astryxdesign/cli',
+ stylingSystem: 'css',
+ topics: ['tokens', 'working-with-ai'],
+ };
+ expect(generateCompressedIndex('1.0.0', {...options, agentDocs: []})).toBe(
+ generateCompressedIndex('1.0.0', options),
+ );
+ });
+
+ it('appends package-labeled lines after core guidance in config order', () => {
+ const result = generateCompressedIndex('1.0.0', {
+ topics: [],
+ agentDocs: [
+ {
+ package: '@acme/second',
+ append: ['second one', 'second two'],
+ },
+ {
+ package: '@acme/first',
+ append: ['first one'],
+ },
+ ],
+ });
+
+ expect(result.indexOf('upgrade --apply')).toBeLessThan(
+ result.indexOf('INTEGRATIONS:'),
+ );
+ expect(result.indexOf('INTEGRATIONS:')).toBeLessThan(
+ result.indexOf('<!-- ASTRYX:END -->'),
+ );
+ expect(result).toContain(
+ 'INTEGRATIONS:\n' +
+ '- `@acme/second`: second one\n' +
+ '- `@acme/second`: second two\n' +
+ '- `@acme/first`: first one',
+ );
+ });
+
+ it('caps the configured project at 32 integration lines', () => {
+ const agentDocs = Array.from({length: 5}, (_, packageIndex) => ({
+ package: `@acme/package-${packageIndex}`,
+ append: Array.from(
+ {length: packageIndex === 4 ? 1 : 8},
+ (_, lineIndex) => `line ${lineIndex}`,
+ ),
+ }));
+ expect(() => generateCompressedIndex('1.0.0', {agentDocs})).toThrow(
+ /32-line project limit/,
+ );
+ });
+});
+
+describe('renderAgentDocsBlock', () => {
+ it('produces repeatable target bytes from configured manifests', async () => {
+ const projectDir = fs.mkdtempSync(
+ path.join(process.cwd(), '.astryx-agent-doc-render-'),
+ );
+ try {
+ fs.writeFileSync(
+ path.join(projectDir, 'package.json'),
+ JSON.stringify({name: 'consumer'}),
+ );
+ fs.writeFileSync(
+ path.join(projectDir, 'astryx.config.mjs'),
+ `export default {integrations: ['@acme/second', '@acme/first']};\n`,
+ );
+ const coreDir = path.join(
+ projectDir,
+ 'node_modules',
+ '@astryxdesign',
+ 'core',
+ );
+ fs.mkdirSync(coreDir, {recursive: true});
+ fs.writeFileSync(
+ path.join(coreDir, 'package.json'),
+ JSON.stringify({name: '@astryxdesign/core', version: '1.0.0'}),
+ );
+ for (const [name, agentDocs] of [
+ ['@acme/second', {append: ['second one', 'second two']}],
+ ['@acme/first', {append: ['first one']}],
+ ]) {
+ const packageDir = path.join(
+ projectDir,
+ 'node_modules',
+ ...name.split('/'),
+ );
+ fs.mkdirSync(packageDir, {recursive: true});
+ fs.writeFileSync(
+ path.join(packageDir, 'package.json'),
+ JSON.stringify({name}),
+ );
+ fs.writeFileSync(
+ path.join(packageDir, 'astryx.integration.mjs'),
+ `export default {agentDocs: ${JSON.stringify(agentDocs)}};\n`,
+ );
+ }
+ fs.writeFileSync(path.join(projectDir, 'AGENTS.md'), '# Agents\n');
+ fs.writeFileSync(path.join(projectDir, 'CLAUDE.md'), '# Claude\n');
+
+ const renderedBlock = await renderAgentDocsBlock(projectDir);
+ expect(renderedBlock.indexOf('second one')).toBeLessThan(
+ renderedBlock.indexOf('second two'),
+ );
+ expect(renderedBlock.indexOf('second two')).toBeLessThan(
+ renderedBlock.indexOf('first one'),
+ );
+
+ installAgentDocs(projectDir, {renderedBlock});
+ const firstAgents = fs.readFileSync(
+ path.join(projectDir, 'AGENTS.md'),
+ 'utf-8',
+ );
+ const firstClaude = fs.readFileSync(
+ path.join(projectDir, 'CLAUDE.md'),
+ 'utf-8',
+ );
+ expect(firstAgents).toContain(renderedBlock);
+ expect(firstClaude).toContain(renderedBlock);
+
+ installAgentDocs(projectDir, {renderedBlock});
+ expect(fs.readFileSync(path.join(projectDir, 'AGENTS.md'), 'utf-8')).toBe(
+ firstAgents,
+ );
+ expect(fs.readFileSync(path.join(projectDir, 'CLAUDE.md'), 'utf-8')).toBe(
+ firstClaude,
+ );
+ } finally {
+ fs.rmSync(projectDir, {recursive: true, force: true});
+ }
+ });
+ it('rejects a package label that could alter managed block structure', async () => {
+ const projectDir = fs.mkdtempSync(
+ path.join(process.cwd(), '.astryx-agent-doc-label-'),
+ );
+ try {
+ fs.writeFileSync(
+ path.join(projectDir, 'package.json'),
+ JSON.stringify({name: 'consumer'}),
+ );
+ fs.writeFileSync(
+ path.join(projectDir, 'astryx.config.mjs'),
+ `export default {integrations: ['@acme/widgets']};\n`,
+ );
+ const packageDir = path.join(
+ projectDir,
+ 'node_modules',
+ '@acme',
+ 'widgets',
+ );
+ fs.mkdirSync(packageDir, {recursive: true});
+ fs.writeFileSync(
+ path.join(packageDir, 'package.json'),
+ JSON.stringify({name: '@acme/widgets\nASTRYX:END'}),
+ );
+ fs.writeFileSync(
+ path.join(packageDir, 'astryx.integration.mjs'),
+ `export default {agentDocs: {append: ['safe line']}};\n`,
+ );
+
+ await expect(renderAgentDocsBlock(projectDir)).rejects.toThrow(
+ /not safe to render/,
+ );
+ } finally {
+ fs.rmSync(projectDir, {recursive: true, force: true});
+ }
+ });
});
describe('detectStylingSystem', () => {
@@ -792,6 +962,46 @@ describe('inspectAgentDocs', () => {
expect(res.blockVersions).toEqual([]);
});
+ it.each([
+ ['append addition', [], [{package: '@acme/a', append: ['added']}]],
+ ['append removal', [{package: '@acme/a', append: ['removed']}], []],
+ [
+ 'integration reorder',
+ [
+ {package: '@acme/a', append: ['a']},
+ {package: '@acme/b', append: ['b']},
+ ],
+ [
+ {package: '@acme/b', append: ['b']},
+ {package: '@acme/a', append: ['a']},
+ ],
+ ],
+ [
+ 'line content change',
+ [{package: '@acme/a', append: ['old']}],
+ [{package: '@acme/a', append: ['new']}],
+ ],
+ ])(
+ 'reports stale at the same Core version after %s',
+ (_label, current, expected) => {
+ const actualBlock = generateCompressedIndex('1.0.0', {
+ agentDocs: current,
+ });
+ fs.writeFileSync(
+ path.join(tmpDir, 'AGENTS.md'),
+ `# Doc\n\n${actualBlock}\n`,
+ );
+ const expectedBlock = generateCompressedIndex('1.0.0', {
+ agentDocs: expected,
+ });
+
+ expect(inspectAgentDocs(tmpDir, '1.0.0', expectedBlock)).toMatchObject({
+ status: 'stale',
+ staleFiles: ['AGENTS.md'],
+ });
+ },
+ );
+
it('reports stale (with the old version) when the block is behind', () => {
writeBlock('AGENTS.md', '1.0.0');
const res = inspectAgentDocs(tmpDir, '2.0.0');
diff --git a/packages/cli/foundation/config/project.mjs b/packages/cli/foundation/config/project.mjs
index 362e2acdd7..6c6d601d92 100644
--- a/packages/cli/foundation/config/project.mjs
+++ b/packages/cli/foundation/config/project.mjs
@@ -59,7 +59,10 @@ import {
discoverIntegrationCodemods,
selectIntegrationCodemods,
} from '../../assets/codemods/integration-discovery.mjs';
-import {validateLoadedIntegration} from '../integrations/validate-contributions.mjs';
+import {
+ INVALID_AGENT_DOCS,
+ validateLoadedIntegration,
+} from '../integrations/validate-contributions.mjs';
import {
InMemoryConfigCache,
cacheKey,
@@ -232,11 +235,13 @@ export class Project {
* lazy and memoized on the returned instance.
*
* @param {string} [cwd]
- * @param {{cache?: import('./config-cache.mjs').ConfigCache}} [options]
+ * @param {{cache?: import('./config-cache.mjs').ConfigCache, fresh?: boolean}} [options]
* @returns {Promise<Project>}
*/
- static async load(cwd = process.cwd(), {cache} = {}) {
- const resolvedCache = cache ?? new InMemoryConfigCache();
+ static async load(cwd = process.cwd(), {cache, fresh = false} = {}) {
+ const resolvedCache = fresh
+ ? new InMemoryConfigCache()
+ : (cache ?? new InMemoryConfigCache());
const configPath = findConfigPath(cwd);
const hash = configContentHash(configPath);
@@ -250,11 +255,13 @@ export class Project {
if (configPath) {
config = await loadModuleWithParser(configPath, parseConfig, {
label: 'astryx.config',
+ fresh,
});
const configDir = path.dirname(configPath);
integrations = config.integrations ?? [];
loadedIntegrations = await loadIntegrations(integrations, {
cwd: configDir,
+ fresh,
});
}
@@ -377,6 +384,22 @@ export class Project {
return integration?.name ?? integration?.__spec ?? '(integration)';
}
+ /**
+ * Whether this package has an error that invalidates its regular manifest
+ * contributions. Invalid `agentDocs` blocks agent-doc writes only; it must not
+ * withdraw components, templates, docs, or codemods.
+ * @param {string} pkg
+ * @returns {boolean}
+ */
+ #hasBlockingContributionIssue(pkg) {
+ return this.#issues.some(
+ issue =>
+ issue.package === pkg &&
+ issue.severity === 'error' &&
+ issue.code !== INVALID_AGENT_DOCS,
+ );
+ }
+
/**
* Validate one loaded integration and collect any issues. Marks the
* integration visited so issues() won't redo the work. Best-effort: a
@@ -439,10 +462,7 @@ export class Project {
for (const integration of this.#loadedIntegrations) {
await this.#collectIssues(integration);
const pkg = this.#pkgLabel(integration);
- const hadError = this.#issues.some(
- i => i.package === pkg && i.severity === 'error',
- );
- if (hadError) continue;
+ if (this.#hasBlockingContributionIssue(pkg)) continue;
try {
// discoverOwnedComponents owns the core+integration record shape;
// here we add only this integration's records (core is handled
@@ -495,10 +515,7 @@ export class Project {
for (const integration of this.#loadedIntegrations) {
await this.#collectIssues(integration);
const pkg = this.#pkgLabel(integration);
- const hadError = this.#issues.some(
- i => i.package === pkg && i.severity === 'error',
- );
- if (hadError) continue;
+ if (this.#hasBlockingContributionIssue(pkg)) continue;
try {
const {templates: ts, errors} =
await discoverIntegrationTemplatesForOne(integration);
@@ -546,10 +563,7 @@ export class Project {
for (const integration of this.#loadedIntegrations) {
await this.#collectIssues(integration);
const pkg = this.#pkgLabel(integration);
- const hadError = this.#issues.some(
- i => i.package === pkg && i.severity === 'error',
- );
- if (hadError) continue;
+ if (this.#hasBlockingContributionIssue(pkg)) continue;
if (!integration?.docs) continue;
try {
const {records, errors} = await discoverIntegrationDocs(integration);
@@ -604,10 +618,7 @@ export class Project {
for (const integration of this.#loadedIntegrations) {
await this.#collectIssues(integration);
const pkg = this.#pkgLabel(integration);
- const hadError = this.#issues.some(
- i => i.package === pkg && i.severity === 'error',
- );
- if (hadError) continue;
+ if (this.#hasBlockingContributionIssue(pkg)) continue;
if (!integration?.codemods) continue;
try {
// Validate this integration's codemods discover cleanly in
diff --git a/packages/cli/foundation/config/project.test.mjs b/packages/cli/foundation/config/project.test.mjs
index 9fe2cc85ff..8818cc65ab 100644
--- a/packages/cli/foundation/config/project.test.mjs
+++ b/packages/cli/foundation/config/project.test.mjs
@@ -26,6 +26,7 @@ function scaffold({
brokenCodemod = false,
docs = null,
unknownKeys = null,
+ agentDocs = null,
integrationIssuesUrl = 'https://example.com/widgets/issues',
} = {}) {
fs.writeFileSync(
@@ -51,6 +52,7 @@ function scaffold({
if (withTemplates) manifest.templates = './templates';
if (withCodemods) manifest.codemods = './codemods';
if (docs) manifest.docs = './docs';
+ if (agentDocs != null) manifest.agentDocs = agentDocs;
if (unknownKeys) Object.assign(manifest, unknownKeys);
if (integrationIssuesUrl) manifest.issuesUrl = integrationIssuesUrl;
fs.writeFileSync(
@@ -266,6 +268,37 @@ describe('Project discovery', () => {
expect(issues.some(i => i.code === 'invalid_doc' && i.severity === 'error')).toBe(true);
});
+ it('keeps regular contributions when agentDocs is invalid', async () => {
+ scaffold({
+ agentDocs: {append: [' invalid']},
+ docs: {'deploying.doc.mjs': topicDoc()},
+ });
+ const project = await Project.load(tmpDir);
+
+ expect(
+ (await project.components()).some(c => c.package === '@acme/widgets'),
+ ).toBe(true);
+ expect(
+ (await project.templates()).some(t => t.package === '@acme/widgets'),
+ ).toBe(true);
+ expect((await project.codemods('0.1.0', '0.2.0')).integration).toHaveLength(
+ 1,
+ );
+ expect((await project.docs()).resolve('deploying')?.package).toBe(
+ '@acme/widgets',
+ );
+
+ const issues = await project.issues();
+ expect(
+ issues.some(
+ issue =>
+ issue.package === '@acme/widgets' &&
+ issue.code === 'invalid_agent_docs' &&
+ issue.severity === 'error',
+ ),
+ ).toBe(true);
+ });
+
it('memoizes components() — the second call does not re-walk', async () => {
scaffold();
const project = await Project.load(tmpDir);
diff --git a/packages/cli/foundation/fs/module-loader.mjs b/packages/cli/foundation/fs/module-loader.mjs
index 247f3fecba..4ad95b2512 100644
--- a/packages/cli/foundation/fs/module-loader.mjs
+++ b/packages/cli/foundation/fs/module-loader.mjs
@@ -16,12 +16,15 @@
*/
import * as path from 'node:path';
+import {createRequire} from 'node:module';
import {pathToFileURL} from 'node:url';
import * as fs from 'node:fs';
import {createJiti} from 'jiti';
/** @type {ReturnType<typeof createJiti> | undefined} */
let jitiInstance;
+let freshImportNonce = 0;
+const requireFromHere = createRequire(import.meta.url);
function getJiti() {
if (!jitiInstance) {
jitiInstance = createJiti(import.meta.url);
@@ -30,16 +33,71 @@ function getJiti() {
}
/**
- * Import a user-authored module. `.ts` is loaded via jiti; `.mjs`/`.js` via
- * native dynamic import (file:// URL). Returns the full module namespace.
+ * Node treats `.js` as ESM only inside the nearest package scope whose
+ * package.json declares `"type": "module"`; no package.json defaults to
+ * CommonJS.
+ * @param {string} file
+ * @returns {boolean}
+ */
+function isCommonJsFile(file) {
+ let dir = path.dirname(file);
+ for (;;) {
+ const packageJson = path.join(dir, 'package.json');
+ if (fs.existsSync(packageJson)) {
+ try {
+ return JSON.parse(fs.readFileSync(packageJson, 'utf-8')).type !== 'module';
+ } catch {
+ return true;
+ }
+ }
+ const parent = path.dirname(dir);
+ if (parent === dir) return true;
+ dir = parent;
+ }
+}
+
+/**
+ * Import a user-authored module. `.ts` is loaded via jiti; `.mjs`/`.js` use
+ * native dynamic import for ordinary cached reads. A fresh `.ts` read uses a
+ * no-cache jiti instance. A fresh CommonJS `.js` read evicts and reloads through
+ * `require`; an ESM `.js` or `.mjs` read uses a cache-busted file URL. The
+ * nearest package.json `type` decides `.js`, matching Node's package scopes.
+ * Normal loads retain module caching. `fresh` is an explicit migration-only
+ * escape hatch for rereading files that a codemod changed during this process.
+ *
* @param {string} file absolute path
+ * @param {{fresh?: boolean}} [options]
* @returns {Promise<Record<string, unknown>>}
*/
-export async function importUserModule(file) {
+export async function importUserModule(file, {fresh = false} = {}) {
+ if (fresh && file.endsWith('.ts')) {
+ return await createJiti(import.meta.url, {moduleCache: false}).import(file);
+ }
+ if (fresh && file.endsWith('.js') && isCommonJsFile(file)) {
+ const resolved = requireFromHere.resolve(file);
+ delete requireFromHere.cache[resolved];
+ const value = requireFromHere(file);
+ if (
+ value != null &&
+ typeof value === 'object' &&
+ value.__esModule === true &&
+ Object.prototype.hasOwnProperty.call(value, 'default')
+ ) {
+ return value;
+ }
+ return {
+ ...(value != null && typeof value === 'object' ? value : {}),
+ default: value,
+ };
+ }
if (file.endsWith('.ts')) {
return await getJiti().import(file);
}
- return await import(pathToFileURL(file).href);
+ const url = pathToFileURL(file);
+ if (fresh) {
+ url.searchParams.set('astryx-fresh', String(++freshImportNonce));
+ }
+ return await import(url.href);
}
/**
@@ -67,10 +125,15 @@ export function findPresentFiles(dir, basenames) {
* @param {string} file absolute path
* @param {(input: unknown, label?: string) => T} parse an authoring parser
* (parseConfig, parseIntegration, parseCodemod, parseTemplate)
- * @param {{label?: string}} [opts] label used in error messages
+ * @param {{label?: string, fresh?: boolean}} [opts] label used in error messages;
+ * `fresh` bypasses the module cache after an in-process codemod write
* @returns {Promise<T>} parsed + typed value
*/
-export async function loadModuleWithParser(file, parse, {label} = {}) {
- const mod = await importUserModule(file);
+export async function loadModuleWithParser(
+ file,
+ parse,
+ {label, fresh = false} = {},
+) {
+ const mod = await importUserModule(file, {fresh});
return parse(mod?.default, label ?? file);
}
diff --git a/packages/cli/foundation/fs/module-loader.test.mjs b/packages/cli/foundation/fs/module-loader.test.mjs
index 2c7a3ff8e5..c5ee156da2 100644
--- a/packages/cli/foundation/fs/module-loader.test.mjs
+++ b/packages/cli/foundation/fs/module-loader.test.mjs
@@ -2,7 +2,10 @@
import {afterEach, beforeEach, describe, expect, it} from 'vitest';
import * as fs from 'node:fs';
+import * as os from 'node:os';
import * as path from 'node:path';
+import {execFileSync} from 'node:child_process';
+import {pathToFileURL} from 'node:url';
import {z} from 'zod';
import {
findPresentFiles,
@@ -61,6 +64,95 @@ describe('importUserModule', () => {
expect(mod.default).toEqual({answer: 42});
expect(mod.named).toBe('hi');
});
+
+ it.each(['mjs', 'js', 'ts'])(
+ 'freshly reloads a changed .%s module while normal loading stays cached',
+ async extension => {
+ const file = path.join(tmpDir, `fresh.${extension}`);
+ fs.writeFileSync(file, `export default {answer: 1};\n`);
+ const first = await importUserModule(file);
+ expect(first.default).toEqual({answer: 1});
+
+ fs.writeFileSync(file, `export default {answer: 2};\n`);
+ const fresh = await importUserModule(file, {fresh: true});
+ expect(fresh.default).toEqual({answer: 2});
+ },
+ );
+
+ const probeFreshJavaScript = (dir, firstSource, secondSource) => {
+ const file = path.join(dir, 'fresh.js');
+ fs.writeFileSync(file, firstSource);
+ const loaderUrl = pathToFileURL(
+ path.join(process.cwd(), 'packages/cli/foundation/fs/module-loader.mjs'),
+ ).href;
+ const output = execFileSync(
+ process.execPath,
+ [
+ '--input-type=module',
+ '-e',
+ `import fs from 'node:fs';
+import {importUserModule} from ${JSON.stringify(loaderUrl)};
+const first = await importUserModule(process.env.TEST_MODULE);
+fs.writeFileSync(process.env.TEST_MODULE, ${JSON.stringify(secondSource)});
+const fresh = await importUserModule(process.env.TEST_MODULE, {fresh: true});
+process.stdout.write(JSON.stringify({first: first.default?.answer, fresh: fresh.default?.answer}));`,
+ ],
+ {
+ encoding: 'utf-8',
+ env: {...process.env, TEST_MODULE: file},
+ },
+ );
+ return JSON.parse(output);
+ };
+
+ it('freshly reloads a changed CommonJS .js module in a real Node process', () => {
+ const commonjsDir = path.join(tmpDir, 'commonjs');
+ fs.mkdirSync(commonjsDir);
+ fs.writeFileSync(
+ path.join(commonjsDir, 'package.json'),
+ JSON.stringify({type: 'commonjs'}),
+ );
+ expect(
+ probeFreshJavaScript(
+ commonjsDir,
+ `module.exports = {answer: 1};\n`,
+ `module.exports = {answer: 2};\n`,
+ ),
+ ).toEqual({first: 1, fresh: 2});
+ });
+
+ it('freshly reloads a changed ESM .js module in a real Node process', () => {
+ const esmDir = path.join(tmpDir, 'esm');
+ fs.mkdirSync(esmDir);
+ fs.writeFileSync(
+ path.join(esmDir, 'package.json'),
+ JSON.stringify({type: 'module'}),
+ );
+ expect(
+ probeFreshJavaScript(
+ esmDir,
+ `export default {answer: 1};\n`,
+ `export default {answer: 2};\n`,
+ ),
+ ).toEqual({first: 1, fresh: 2});
+ });
+
+ it('defaults .js to CommonJS when no package.json exists', () => {
+ const noPackageDir = fs.mkdtempSync(
+ path.join(os.tmpdir(), 'astryx-commonjs-no-package-'),
+ );
+ try {
+ expect(
+ probeFreshJavaScript(
+ noPackageDir,
+ `module.exports = {answer: 1};\n`,
+ `module.exports = {answer: 2};\n`,
+ ),
+ ).toEqual({first: 1, fresh: 2});
+ } finally {
+ fs.rmSync(noPackageDir, {recursive: true, force: true});
+ }
+ });
});
describe('loadModuleWithParser', () => {
diff --git a/packages/cli/foundation/integrations/integrations.mjs b/packages/cli/foundation/integrations/integrations.mjs
index 3f4c8dc111..356244632a 100644
--- a/packages/cli/foundation/integrations/integrations.mjs
+++ b/packages/cli/foundation/integrations/integrations.mjs
@@ -13,10 +13,14 @@
import * as fs from 'node:fs';
import * as path from 'node:path';
import {assertWithin} from '../fs/path-safety.mjs';
-import {parseIntegration} from '../../authoring/integration/parse.mjs';
-// The key census is internal to the schema module on purpose: it is derived
-// from the schema so it cannot drift, and it is not public API.
-import {unknownIntegrationKeys} from '../../authoring/integration/schema.mjs';
+// The key census and contribution parsers are internal to the schema module on
+// purpose: the public parser still validates the complete authored type, while
+// the loader can isolate an invalid optional contribution from valid roots.
+import {
+ parseAgentDocsField,
+ parseIntegrationBase,
+ unknownIntegrationKeys,
+} from '../../authoring/integration/schema.mjs';
import {importUserModule, findPresentFiles} from '../fs/module-loader.mjs';
/**
@@ -32,6 +36,9 @@ import {importUserModule, findPresentFiles} from '../fs/module-loader.mjs';
* @property {string} [codemods]
* @property {string} [docs]
* @property {string} [issuesUrl]
+ * @property {{append?: readonly string[]}} [agentDocs]
+ * @property {string} [__agentDocsError] contribution-specific validation
+ * failure; other manifest contributions remain available
* @property {string} __spec
* @property {string} __packageDir
* @property {string} __manifestFile
@@ -63,32 +70,56 @@ export function findManifestPaths(dir) {
}
/**
- * Load and validate a manifest module's default export against the integration
- * schema, and report the keys this CLI does not know. Default export only —
- * `.ts` is loaded via jiti; `.mjs`/`.js` via dynamic import. Throws if the
- * default export is missing or invalid.
+ * Load and validate a manifest module's default export, while isolating the
+ * optional `agentDocs` contribution from the manifest's other fields.
*
- * The raw default export is inspected before it is parsed, because parsing
- * strips the unknown keys: after `parseIntegration` there is nothing left to
- * report. Exposed for validate-integration.
+ * The base manifest still fails as one unit when a root or `issuesUrl` is
+ * invalid. `agentDocs` is parsed separately: a bad contribution is returned as
+ * `agentDocsError`, while valid components/templates/docs/codemods stay loaded.
+ * The raw object is also inspected before parsing so unknown-key warnings retain
+ * forward compatibility.
*
- * `debug` comes back separately because it is a NAMED export, not a manifest
- * key. A key would have to survive the manifest schema of every CLI version
- * already installed against this integration, and older ones reject an unknown
- * key outright — losing that integration's components, templates and codemods
- * with it (#5119). A named export is simply not read by a CLI that does not
- * know about it, so an integration can start contributing one without a
- * coordinated upgrade.
+ * `debug` comes back separately because it is a named export, not a manifest
+ * key. A CLI that does not know it simply does not read it.
*
* @param {string} file absolute manifest path
* @param {string} [label] used in error messages
- * @returns {Promise<{manifest: import('../../authoring/integration/type').AstryxIntegration, unknownKeys: string[], debug?: import('../../authoring/debug/type').DebugEventHandler}>}
+ * @param {{fresh?: boolean}} [options]
+ * @returns {Promise<{manifest: import('../../authoring/integration/type').AstryxIntegration, unknownKeys: string[], debug?: import('../../authoring/debug/type').DebugEventHandler, agentDocsError?: string}>}
*/
-export async function loadManifest(file, label = 'integration manifest') {
- const mod = await importUserModule(file);
+export async function loadManifest(
+ file,
+ label = 'integration manifest',
+ {fresh = false} = {},
+) {
+ const mod = await importUserModule(file, {fresh});
const raw = mod?.default;
+ const baseManifest = parseIntegrationBase(raw, label);
+ const hasAgentDocs =
+ raw != null &&
+ typeof raw === 'object' &&
+ !Array.isArray(raw) &&
+ Object.prototype.hasOwnProperty.call(raw, 'agentDocs');
+ const rawAgentDocs = hasAgentDocs
+ ? /** @type {{agentDocs?: unknown}} */ (raw).agentDocs
+ : undefined;
+ /** @type {import('../../authoring/integration/type').AstryxIntegration['agentDocs']} */
+ let agentDocs;
+ /** @type {string | undefined} */
+ let agentDocsError;
+ if (hasAgentDocs && rawAgentDocs !== undefined) {
+ try {
+ agentDocs = parseAgentDocsField(
+ rawAgentDocs,
+ `${label} field "agentDocs"`,
+ );
+ } catch (err) {
+ agentDocsError = err instanceof Error ? err.message : String(err);
+ }
+ }
+
return {
- manifest: parseIntegration(raw, label),
+ manifest: agentDocs == null ? baseManifest : {...baseManifest, agentDocs},
unknownKeys: unknownIntegrationKeys(raw),
debug:
typeof mod?.debug === 'function'
@@ -96,6 +127,7 @@ export async function loadManifest(file, label = 'integration manifest') {
mod.debug
)
: undefined,
+ agentDocsError,
};
}
@@ -105,10 +137,15 @@ export async function loadManifest(file, label = 'integration manifest') {
* validate-integration.
* @param {string} file absolute manifest path
* @param {string} [label] used in error messages
+ * @param {{fresh?: boolean}} [options]
* @returns {Promise<import('../../authoring/integration/type').AstryxIntegration>}
*/
-export async function loadManifestObject(file, label = 'integration manifest') {
- return (await loadManifest(file, label)).manifest;
+export async function loadManifestObject(
+ file,
+ label = 'integration manifest',
+ options,
+) {
+ return (await loadManifest(file, label, options)).manifest;
}
/**
@@ -168,10 +205,13 @@ function resolveManifestPath(packageDir, spec) {
* Load configured integrations.
*
* @param {string[]} [specs] package names
- * @param {{cwd?: string}} [options]
+ * @param {{cwd?: string, fresh?: boolean}} [options]
* @returns {Promise<LoadedIntegration[]>}
*/
-export async function loadIntegrations(specs = [], {cwd = process.cwd()} = {}) {
+export async function loadIntegrations(
+ specs = [],
+ {cwd = process.cwd(), fresh = false} = {},
+) {
/** @type {LoadedIntegration[]} */
const integrations = [];
const seen = new Set();
@@ -197,12 +237,15 @@ export async function loadIntegrations(specs = [], {cwd = process.cwd()} = {}) {
let unknownKeys;
/** @type {import('../../authoring/debug/type').DebugEventHandler | undefined} */
let debugHandler;
+ /** @type {string | undefined} */
+ let agentDocsError;
try {
({
manifest,
unknownKeys,
debug: debugHandler,
- } = await loadManifest(manifestFile, `Integration ${spec}`));
+ agentDocsError,
+ } = await loadManifest(manifestFile, `Integration ${spec}`, {fresh}));
} catch (err) {
// A manifest that throws on import or fails schema validation must NOT take
// down every command (component/docs/theme don't need this integration).
@@ -238,6 +281,8 @@ export async function loadIntegrations(specs = [], {cwd = process.cwd()} = {}) {
codemods: resolveRoot(manifest.codemods),
docs: resolveRoot(manifest.docs),
issuesUrl: manifest.issuesUrl,
+ agentDocs: manifest.agentDocs,
+ __agentDocsError: agentDocsError,
__unknownKeys: unknownKeys,
__debug: debugHandler,
__spec: spec,
diff --git a/packages/cli/foundation/integrations/integrations.test.mjs b/packages/cli/foundation/integrations/integrations.test.mjs
index dab0c8df78..2d35ebe3cd 100644
--- a/packages/cli/foundation/integrations/integrations.test.mjs
+++ b/packages/cli/foundation/integrations/integrations.test.mjs
@@ -102,6 +102,66 @@ describe('configured integrations', () => {
]);
});
+ it('loads agentDocs from the default manifest in authored order', async () => {
+ const pkgDir = writeManifestPackage(tmpDir, {
+ body: `export default {
+ agentDocs: {
+ append: ['after one', 'after two'],
+ },
+ };\n`,
+ });
+
+ const [loaded] = await loadIntegrations(['@acme/widgets'], {cwd: tmpDir});
+ expect(loaded.agentDocs).toEqual({
+ append: ['after one', 'after two'],
+ });
+ expect(loaded.__unknownKeys).toEqual([]);
+
+ fs.writeFileSync(
+ path.join(pkgDir, 'astryx.integration.mjs'),
+ `export default {agentDocs: {append: ['after rewrite']}};\n`,
+ );
+ const [fresh] = await loadIntegrations(['@acme/widgets'], {
+ cwd: tmpDir,
+ fresh: true,
+ });
+ expect(fresh.agentDocs).toEqual({append: ['after rewrite']});
+ });
+
+ it('ignores an agentDocs named export; the contract is the default manifest field', async () => {
+ writeManifestPackage(tmpDir, {
+ body: `export const agentDocs = {append: ['wrong place']};\nexport default {};\n`,
+ });
+
+ const [loaded] = await loadIntegrations(['@acme/widgets'], {cwd: tmpDir});
+ expect(loaded.agentDocs).toBeUndefined();
+ });
+
+ it.each([
+ ['wrong outer shape', []],
+ ['wrong append shape', {append: 'not-an-array'}],
+ ['non-string entry', {append: ['ok', 42]}],
+ ['too many lines', {append: Array.from({length: 9}, (_, i) => `line ${i}`)}],
+ ['too many code points', {append: ['😀'.repeat(241)]}],
+ ['control character', {append: ['bad\u0001line']}],
+ ['managed marker', {append: ['ASTRYX:START']}],
+ ])('isolates invalid agentDocs (%s) from valid roots', async (_label, agentDocs) => {
+ const pkgDir = writeManifestPackage(tmpDir, {
+ body: `export default ${JSON.stringify({
+ components: './components',
+ agentDocs,
+ })};\n`,
+ });
+ fs.mkdirSync(path.join(pkgDir, 'components'));
+
+ const [loaded] = await loadIntegrations(['@acme/widgets'], {cwd: tmpDir});
+
+ expect(loaded.__loadError).toBeUndefined();
+ expect(loaded.components).toBe(path.join(pkgDir, 'components'));
+ expect(loaded.agentDocs).toBeUndefined();
+ expect(loaded.__agentDocsError).toMatch(/agentDocs/i);
+ });
+
it('errors when the package has no conventional root manifest', async () => {
const pkgDir = path.join(tmpDir, 'node_modules', '@acme', 'widgets');
fs.mkdirSync(pkgDir, {recursive: true});
diff --git a/packages/cli/foundation/integrations/validate-contributions.mjs b/packages/cli/foundation/integrations/validate-contributions.mjs
index 417bb94d79..09e17e9585 100644
--- a/packages/cli/foundation/integrations/validate-contributions.mjs
+++ b/packages/cli/foundation/integrations/validate-contributions.mjs
@@ -9,10 +9,12 @@
* and `integration-warnings` nudges about them on ordinary commands. Keeping
* them here means those callers no longer reach up into `api/`.
*
- * The manifest schema is NOT re-validated here — `loadIntegrations` already did
- * that and throws otherwise. What is re-checked is the on-disk contributions
- * (roots + codemods/templates/components), because those regress independently
- * of the manifest: a deleted directory, a template that lost its source file.
+ * The base manifest schema is not re-validated here — `loadIntegrations` already
+ * did that. Optional contributions such as `agentDocs` carry their own error
+ * marker so a bad contribution is reported without withdrawing valid roots.
+ * What is re-checked is the on-disk contributions (roots +
+ * codemods/templates/components), because those regress independently of the
+ * manifest: a deleted directory, a template that lost its source file.
*
* @input a loaded-integration-shaped object (absolute contribution roots + identity)
* @output AstryxIntegrationIssue[]
@@ -30,6 +32,9 @@ import {discoverIntegrationDocs} from '../discovery/docs-discovery.mjs';
* @typedef {import('./integrations.mjs').LoadedIntegration} LoadedIntegration
*/
+/** Stable issue code for an invalid optional agent-doc contribution. */
+export const INVALID_AGENT_DOCS = 'invalid_agent_docs';
+
/** @param {string} code @param {string} message @returns {Issue} */
export function issueError(code, message) {
return {code, severity: 'error', message};
@@ -218,6 +223,9 @@ export async function validateLoadedIntegration(loaded) {
return [issueError('integration_error', loaded.__loadError)];
}
checkUnknownKeys(loaded, issues);
+ if (loaded.__agentDocsError) {
+ issues.push(issueError(INVALID_AGENT_DOCS, loaded.__agentDocsError));
+ }
checkRoots(
{
components: loaded.components,