Skip to content

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

TypeScript

fix(cli): refresh the managed agent-docs block on every `upgrade` path (#4213)

Joeyd91c8517ef80
diff --git a/.changeset/upgrade-refresh-agent-docs.md b/.changeset/upgrade-refresh-agent-docs.md
new file mode 100644
index 0000000000..208db85726
--- /dev/null
+++ b/.changeset/upgrade-refresh-agent-docs.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[fix] `astryx upgrade` now keeps the managed agent-docs block (`<!-- ASTRYX:START --> … <!-- ASTRYX:END -->`) in sync with the installed version on **every** path — including the up-to-date and no-codemods short-circuits that previously returned before any refresh, leaving AI agents reading a stale component index and superseded rules. The block documents the installed library, so it's now refreshed up front (independent of codemods) and reported in the `--json` receipt as `agentDocs`. One detection pass covers three cases: a stale block is rewritten (`--apply`) or reported as a pending change (dry-run, which no longer writes); a project with core installed but no managed block is nudged to run `astryx init --features agents`; an already-current block stays silent. (#4168, #4169)
+
+@josephfarina
diff --git a/packages/cli/src/commands/agent-docs.mjs b/packages/cli/src/commands/agent-docs.mjs
index 36f5451151..257078ec9a 100644
--- a/packages/cli/src/commands/agent-docs.mjs
+++ b/packages/cli/src/commands/agent-docs.mjs
@@ -104,6 +104,78 @@ export function isAstryxInitialized(targetDir = process.cwd()) {
return false;
}
+/**
+ * Parse the Astryx version a managed block was generated for, from its header
+ * line ("Astryx v1.2.3 · N components"). Returns null when the block predates
+ * the versioned header (e.g. a legacy XDS block) or has no header at all.
+ *
+ * @param {string} content File contents, or just the block text.
+ * @returns {string|null}
+ */
+export function parseBlockVersion(content) {
+ const match = /Astryx v(\d+\.\d+\.\d+[^\s·]*)/.exec(content ?? '');
+ return match ? match[1] : null;
+}
+
+/**
+ * Read-only staleness assessment of the managed agent-docs block(s) against the
+ * installed core version. This is the detection half of the `astryx upgrade`
+ * agent-docs refresh: it never writes, so `upgrade` can run it on EVERY path —
+ * including the up-to-date / no-codemods short-circuits — and decide whether to
+ * rewrite a stale block, nudge an uninitialized repo, or stay silent.
+ *
+ * A managed block is:
+ * - `stale` — it carries a legacy XDS marker, has no parseable version, or
+ * records a version other than the installed one.
+ * - `current` — every managed block already matches the installed version.
+ * And the project is `missing` when no managed block exists anywhere (the repo
+ * has agent-doc files without our markers, or none at all — i.e. never `init`ed).
+ *
+ * @param {string} targetDir
+ * @param {string} [installedVersion] Defaults to the installed core version.
+ * @returns {{
+ * installedVersion: string,
+ * status: 'missing' | 'stale' | 'current',
+ * files: Array<{path: string, blockVersion: string|null, legacy: boolean, stale: boolean}>,
+ * staleFiles: string[],
+ * blockVersions: string[],
+ * }}
+ */
+export function inspectAgentDocs(targetDir, installedVersion) {
+ const version = installedVersion ?? getXdsVersion(findCoreDir(targetDir));
+ const files = [];
+
+ for (const rel of discoverAgentDocs(targetDir)) {
+ let content;
+ try {
+ content = fs.readFileSync(path.join(targetDir, rel), 'utf-8');
+ } catch {
+ continue; // Unreadable — treat as absent.
+ }
+ const hasNew = content.includes(MARKER_START);
+ const hasLegacy = content.includes(LEGACY_MARKER_START);
+ if (!hasNew && !hasLegacy) continue; // Not a block we manage.
+
+ const legacy = !hasNew && hasLegacy;
+ const blockVersion = parseBlockVersion(content);
+ const stale = legacy || blockVersion == null || blockVersion !== version;
+ files.push({path: rel, blockVersion, legacy, stale});
+ }
+
+ const staleEntries = files.filter(f => f.stale);
+ const staleFiles = staleEntries.map(f => f.path);
+ const blockVersions = [
+ ...new Set(staleEntries.map(f => f.blockVersion).filter(Boolean)),
+ ];
+
+ let status;
+ if (files.length === 0) status = 'missing';
+ else if (staleFiles.length > 0) status = 'stale';
+ else status = 'current';
+
+ return {installedVersion: version, status, files, staleFiles, blockVersions};
+}
+
/**
* Resolve which file(s) to write for a given agent tool preset.
* Searches for existing files first, falls back to default creation path.
diff --git a/packages/cli/src/commands/agent-docs.test.mjs b/packages/cli/src/commands/agent-docs.test.mjs
index beb2543fcf..da254035ca 100644
--- a/packages/cli/src/commands/agent-docs.test.mjs
+++ b/packages/cli/src/commands/agent-docs.test.mjs
@@ -16,6 +16,8 @@ import {
removeXdsBlock,
discoverAgentDocs,
resolveAgentPaths,
+ parseBlockVersion,
+ inspectAgentDocs,
} from './agent-docs.mjs';
let tmpDir;
@@ -609,3 +611,87 @@ describe('resolveAgentPaths', () => {
expect(result).toEqual({inject: [], create: ['.claude/CLAUDE.md']});
});
});
+
+describe('parseBlockVersion', () => {
+ it('reads the version from the header of a generated block', () => {
+ expect(parseBlockVersion(generateCompressedIndex('1.2.3'))).toBe('1.2.3');
+ });
+
+ it('reads prerelease versions', () => {
+ expect(parseBlockVersion('Astryx v1.2.3-beta.4 · 10 components')).toBe(
+ '1.2.3-beta.4',
+ );
+ });
+
+ it('returns null when no versioned header is present', () => {
+ expect(parseBlockVersion('<!-- XDS:START -->\nold\n<!-- XDS:END -->')).toBeNull();
+ expect(parseBlockVersion('')).toBeNull();
+ expect(parseBlockVersion(undefined)).toBeNull();
+ });
+});
+
+describe('inspectAgentDocs', () => {
+ function writeBlock(rel, version) {
+ const filePath = path.join(tmpDir, rel);
+ fs.mkdirSync(path.dirname(filePath), {recursive: true});
+ fs.writeFileSync(filePath, `# Doc\n\n${generateCompressedIndex(version)}\n`);
+ }
+
+ it('reports missing when no agent docs exist at all', () => {
+ const res = inspectAgentDocs(tmpDir, '1.0.0');
+ expect(res.status).toBe('missing');
+ expect(res.files).toEqual([]);
+ expect(res.staleFiles).toEqual([]);
+ });
+
+ it('reports missing when agent files exist but carry no Astryx marker', () => {
+ fs.writeFileSync(path.join(tmpDir, 'AGENTS.md'), '# Agents\n\nHand-written notes.\n');
+ expect(inspectAgentDocs(tmpDir, '1.0.0').status).toBe('missing');
+ });
+
+ it('reports current when the only block matches the installed version', () => {
+ writeBlock('AGENTS.md', '1.0.0');
+ const res = inspectAgentDocs(tmpDir, '1.0.0');
+ expect(res.status).toBe('current');
+ expect(res.staleFiles).toEqual([]);
+ expect(res.blockVersions).toEqual([]);
+ });
+
+ 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');
+ expect(res.status).toBe('stale');
+ expect(res.staleFiles).toEqual(['AGENTS.md']);
+ expect(res.blockVersions).toEqual(['1.0.0']);
+ expect(res.installedVersion).toBe('2.0.0');
+ });
+
+ it('treats a legacy XDS block as stale even with no parseable version', () => {
+ fs.writeFileSync(
+ path.join(tmpDir, 'CLAUDE.md'),
+ '# Claude\n\n<!-- XDS:START -->\nlegacy index\n<!-- XDS:END -->\n',
+ );
+ const res = inspectAgentDocs(tmpDir, '1.0.0');
+ expect(res.status).toBe('stale');
+ expect(res.files[0].legacy).toBe(true);
+ expect(res.blockVersions).toEqual([]);
+ });
+
+ it('is stale if ANY marked file is behind (mixed current + stale)', () => {
+ writeBlock('AGENTS.md', '2.0.0');
+ writeBlock('CLAUDE.md', '1.0.0');
+ const res = inspectAgentDocs(tmpDir, '2.0.0');
+ expect(res.status).toBe('stale');
+ expect(res.staleFiles).toEqual(['CLAUDE.md']);
+ });
+
+ it('defaults the installed version to the core package when omitted', () => {
+ const coreDir = path.join(tmpDir, 'node_modules', '@astryxdesign', 'core');
+ fs.mkdirSync(coreDir, {recursive: true});
+ fs.writeFileSync(path.join(coreDir, 'package.json'), JSON.stringify({version: '3.0.0'}));
+ writeBlock('AGENTS.md', '3.0.0');
+ const res = inspectAgentDocs(tmpDir);
+ expect(res.installedVersion).toBe('3.0.0');
+ expect(res.status).toBe('current');
+ });
+});
diff --git a/packages/cli/src/commands/upgrade.mjs b/packages/cli/src/commands/upgrade.mjs
index 2213adc5ef..31487e8267 100644
--- a/packages/cli/src/commands/upgrade.mjs
+++ b/packages/cli/src/commands/upgrade.mjs
@@ -11,8 +11,11 @@
*
* Pipeline (--apply):
* 1. Read installed @astryxdesign/core (or legacy @xds/core) version
- * 2. Run codemods for --from → installed version
- * 3. Refresh agent docs (AGENTS.md / CLAUDE.md) if present
+ * 2. Refresh the managed agent-docs block (AGENTS.md / CLAUDE.md) to the
+ * installed version — runs on EVERY path (including the up-to-date /
+ * no-codemods short-circuits), because the block documents the installed
+ * library, not the codemod outcome. Dry-run reports without writing.
+ * 3. Run codemods for --from → installed version
*
* Options:
* --from <version> Previous version before the dependency upgrade
@@ -46,7 +49,7 @@ import {
selectIntegrationCodemods,
} from '../codemods/integration-discovery.mjs';
import {runIntegrationCodemods} from '../codemods/integration-runner.mjs';
-import {installAgentDocs, discoverAgentDocs} from './agent-docs.mjs';
+import {installAgentDocs, inspectAgentDocs} from './agent-docs.mjs';
import {getCliInvocation, formatCliCommand} from '../utils/package-manager.mjs';
import {isValidSemver, semverGte} from '../utils/semver.mjs';
import {jsonOut, jsonError} from '../lib/json.mjs';
@@ -135,6 +138,103 @@ async function runPostCodemodHooks(hooks, context, silent) {
}
}
+/**
+ * Refresh (or, in dry-run, report) the managed agent-docs block after a version
+ * bump. The block (`<!-- ASTRYX:START --> … <!-- ASTRYX:END -->`) documents the
+ * INSTALLED library — its version, component index, and agent rules — so it must
+ * be re-synced on EVERY upgrade path, including the up-to-date / no-codemods
+ * short-circuits where no source file changes. That was the gap in #4168: an
+ * agent reading a stale index queries missing components and follows superseded
+ * rules. Three cases, one detection pass:
+ *
+ * - `stale` — a managed block records an older version (or a legacy XDS
+ * marker). `--apply` rewrites it; dry-run reports the pending
+ * refresh as a loud next step and writes nothing.
+ * - `missing` — core is installed but no managed block exists anywhere (the repo
+ * never ran `init`, or its agent docs were never marked). We never
+ * silently create docs mid-upgrade; we nudge to run `init`.
+ * - `current` — every block already matches the installed version: stay silent.
+ *
+ * @param {{cwd: string, installedVersion: string, apply: boolean, json: boolean}} ctx
+ * @returns {import('../types/upgrade').AgentDocsSummary}
+ */
+export function refreshAgentDocs({cwd, installedVersion, apply, json}) {
+ const inspection = inspectAgentDocs(cwd, installedVersion);
+ /** @type {import('../types/upgrade').AgentDocsSummary} */
+ const summary = {
+ status: inspection.status,
+ installedVersion,
+ fromVersions: inspection.blockVersions,
+ files: [],
+ refreshed: false,
+ action: 'none',
+ };
+
+ // Never initialized — don't silently create docs during an upgrade; nudge.
+ if (inspection.status === 'missing') {
+ summary.action = 'nudge-init';
+ if (!json) {
+ p.log.warn(
+ `No Astryx agent-docs block found — AI agents have no component index. Run \`${formatCliCommand('astryx init --features agents')}\` to install it.`,
+ );
+ }
+ return summary;
+ }
+
+ if (inspection.status === 'current') return summary;
+
+ // Stale.
+ summary.files = inspection.staleFiles;
+ const fromLabel = summary.fromVersions.length
+ ? `v${summary.fromVersions.join(', v')}`
+ : 'an unknown version';
+
+ if (!apply) {
+ // Dry-run: report the pending change, never write.
+ summary.action = 'would-refresh';
+ if (!json) {
+ p.log.warn(
+ `Agent docs are stale: block is at ${fromLabel}, installed is v${installedVersion}. Re-run with --apply to refresh (${summary.files.join(', ')}).`,
+ );
+ }
+ return summary;
+ }
+
+ // Apply: rewrite only files that already carry a marker (onlyReplace).
+ try {
+ const written = installAgentDocs(cwd, {onlyReplace: true});
+ summary.refreshed = written.length > 0;
+ summary.files = written;
+ if (summary.refreshed) {
+ summary.action = 'refreshed';
+ if (!json) {
+ p.log.success(
+ `Agent docs refreshed → v${installedVersion} (from ${fromLabel}): ${written.join(', ')}`,
+ );
+ }
+ } else {
+ // We detected a stale marked block but rewrote nothing, and
+ // installAgentDocs did not throw — the block markers are malformed (e.g. a
+ // START with no matching END, so the writer can't safely splice it). Don't
+ // fail silently: the block is exactly the artifact agents rely on.
+ summary.action = 'error';
+ if (!json) {
+ p.log.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.`,
+ );
+ }
+ }
+ } catch {
+ summary.action = 'error';
+ if (!json) {
+ p.log.warn(
+ `Could not refresh agent docs. Run \`${formatCliCommand('astryx init --features agents')}\` to update them manually.`,
+ );
+ }
+ }
+ return summary;
+}
+
/**
* Register the `upgrade` command (codemod-driven version migration).
*/
@@ -254,6 +354,19 @@ export function registerUpgrade(program) {
);
}
+ // Sync the managed agent-docs block to the installed version FIRST. It
+ // documents the installed library (version + component index + rules),
+ // independent of any source codemods, so it must be refreshed on every
+ // path below — including the up-to-date / no-codemods short-circuits that
+ // return before codemods ever run (issue #4168). Dry-run reports without
+ // writing. Folded into every terminal payload as `agentDocs`.
+ const agentDocs = refreshAgentDocs({
+ cwd: process.cwd(),
+ installedVersion: targetVersion,
+ apply: options.apply,
+ json,
+ });
+
// ───────────────────────────────────────────────────────────────────
// PIPELINE ORDERING
//
@@ -275,6 +388,7 @@ export function registerUpgrade(program) {
status: 'up_to_date',
from: currentVersion,
to: targetVersion,
+ agentDocs,
});
}
p.log.success('Already up to date — no codemods to run.');
@@ -409,6 +523,7 @@ export function registerUpgrade(program) {
suggestedCommand,
message: guidance,
note: 'Integrations are skipped in this preview; they will be processed on the --apply run.',
+ agentDocs,
});
}
p.log.warn(guidance);
@@ -420,11 +535,12 @@ export function registerUpgrade(program) {
return;
}
// Genuine config error (apply mode, OR dry-run with no pending core
- // config codemod that would fix it): abort as before.
+ // config codemod that would fix it): abort as before. The agent-docs
+ // refresh already ran (it's independent of config), so surface it.
if (json)
return jsonError(
err.message,
- undefined,
+ {agentDocs},
ERROR_CODES.ERR_INVALID_ARGUMENT,
);
p.log.error(err.message);
@@ -502,6 +618,7 @@ export function registerUpgrade(program) {
status: 'no_codemods',
from: currentVersion,
to: targetVersion,
+ agentDocs,
});
}
p.log.success('No codemods available for this version range.');
@@ -513,7 +630,7 @@ export function registerUpgrade(program) {
if (totalTransforms === 0 && totalOptional === 0) {
const msg = `Codemod "${options.codemod}" not found. Use --list to see available codemods.`;
if (json)
- return jsonError(msg, undefined, ERROR_CODES.ERR_UNKNOWN_CODEMOD);
+ return jsonError(msg, {agentDocs}, ERROR_CODES.ERR_UNKNOWN_CODEMOD);
p.log.error(msg);
p.outro('Aborted');
process.exitCode = 1;
@@ -535,7 +652,10 @@ export function registerUpgrade(program) {
to: targetVersion,
codemods: totalTransforms,
integrations: integrations.map(i => i.name ?? i.__spec),
- agentDocsRefreshed: false,
+ // Refreshed up front (before the gates above), so the receipt just
+ // reports what happened. `agentDocsRefreshed` kept for back-compat.
+ agentDocsRefreshed: agentDocs.refreshed,
+ agentDocs,
};
// Run file-based integration codemods alongside the core registry
@@ -607,26 +727,9 @@ export function registerUpgrade(program) {
}
}
- // Refresh agent docs if any exist (AGENTS.md, CLAUDE.md, .claude/CLAUDE.md, etc.)
- // Always update after --apply; also update during dry-run if files exist,
- // since the index reflects the installed CLI version, not the codemods.
- const existingDocs = discoverAgentDocs(process.cwd());
- if (existingDocs.length > 0) {
- try {
- // onlyReplace: only update files that already have Astryx markers.
- // Don't inject into files that never had Astryx content.
- const written = installAgentDocs(process.cwd(), {onlyReplace: true});
- receipt.agentDocsRefreshed = written.length > 0;
- if (!json && written.length > 0)
- p.log.success(`Agent docs updated: ${written.join(', ')}`);
- } catch {
- if (!json) {
- p.log.warn(
- `Could not update agent docs. Run \`${getCliInvocation()} init --features agents\` to update manually.`,
- );
- }
- }
- }
+ // NOTE: the managed agent-docs block was already refreshed up front (see
+ // refreshAgentDocs after installed-version detection), so it stays in sync
+ // even on the short-circuit paths that return before this point.
receipt.filesChanged = mergedFilesChanged;
receipt.transformsApplied = mergedTransformsApplied;
diff --git a/packages/cli/src/commands/upgrade.test.mjs b/packages/cli/src/commands/upgrade.test.mjs
index d5c134e55a..7ff38b2348 100644
--- a/packages/cli/src/commands/upgrade.test.mjs
+++ b/packages/cli/src/commands/upgrade.test.mjs
@@ -6,6 +6,7 @@ import * as path from 'node:path';
import * as os from 'node:os';
import {Command} from 'commander';
import {registerUpgrade} from './upgrade.mjs';
+import {generateCompressedIndex} from './agent-docs.mjs';
let tmpDir;
let originalCwd;
@@ -158,3 +159,156 @@ describe('upgrade --list dedup', () => {
expect(names.length).toBe(unique.size);
});
});
+
+// Issue #4168 — `upgrade` must refresh the managed agent-docs block after a
+// version bump, on EVERY path (the block documents the installed library, not
+// the codemod outcome), and must NOT write during a dry run.
+describe('upgrade agent-docs refresh (#4168)', () => {
+ /** Write an agent-doc file with a managed block generated for `version`. */
+ function writeAgentBlock(rel, version) {
+ const filePath = path.join(tmpDir, rel);
+ fs.mkdirSync(path.dirname(filePath), {recursive: true});
+ fs.writeFileSync(filePath, `# Doc\n\n${generateCompressedIndex(version)}\n`);
+ }
+
+ it('refreshes a stale block with --apply, even when there are no codemods (up-to-date path)', async () => {
+ writePkg();
+ writeInstalledCore('0.0.15');
+ writeAgentBlock('AGENTS.md', '0.0.1');
+
+ // --from == installed → up-to-date short-circuit: no codemods run, yet the
+ // stale block must still be brought current. This is the exact gap in #4168.
+ const result = await runJson(['--json', 'upgrade', '--from', '0.0.15', '--apply']);
+
+ expect(result.type).toBe('upgrade.status');
+ expect(result.data.status).toBe('up_to_date');
+ expect(result.data.agentDocs.status).toBe('stale');
+ expect(result.data.agentDocs.action).toBe('refreshed');
+ expect(result.data.agentDocs.refreshed).toBe(true);
+ expect(result.data.agentDocs.fromVersions).toEqual(['0.0.1']);
+ expect(result.data.agentDocs.files).toContain('AGENTS.md');
+
+ const content = fs.readFileSync(path.join(tmpDir, 'AGENTS.md'), 'utf-8');
+ expect(content).toMatch(/Astryx v0\.0\.15 ·/);
+ expect(content).not.toMatch(/Astryx v0\.0\.1 ·/);
+ });
+
+ it('reports a stale block on a dry run WITHOUT writing', async () => {
+ writePkg();
+ writeInstalledCore('0.0.15');
+ writeAgentBlock('AGENTS.md', '0.0.1');
+ const before = fs.readFileSync(path.join(tmpDir, 'AGENTS.md'), 'utf-8');
+
+ const result = await runJson(['--json', 'upgrade', '--from', '0.0.15']); // no --apply
+
+ expect(result.data.agentDocs.status).toBe('stale');
+ expect(result.data.agentDocs.action).toBe('would-refresh');
+ expect(result.data.agentDocs.refreshed).toBe(false);
+ // The file must be untouched by a dry run.
+ expect(fs.readFileSync(path.join(tmpDir, 'AGENTS.md'), 'utf-8')).toBe(before);
+ });
+
+ it('refreshes a stale block on the no-codemods path (--apply)', async () => {
+ writePkg();
+ writeInstalledCore('0.0.11'); // (0.0.10, 0.0.11] has no registered codemods
+ writeSourceFile();
+ writeAgentBlock('CLAUDE.md', '0.0.1');
+
+ const result = await runJson(['--json', 'upgrade', '--from', '0.0.10', '--apply', '--path', 'src']);
+
+ expect(result.type).toBe('upgrade.status');
+ expect(result.data.status).toBe('no_codemods');
+ expect(result.data.agentDocs.refreshed).toBe(true);
+ expect(fs.readFileSync(path.join(tmpDir, 'CLAUDE.md'), 'utf-8')).toMatch(/Astryx v0\.0\.11 ·/);
+ });
+
+ it('nudges to run init when core is installed but no managed block exists', async () => {
+ writePkg();
+ writeInstalledCore('0.0.15');
+ // No agent-doc files at all.
+
+ const result = await runJson(['--json', 'upgrade', '--from', '0.0.15', '--apply']);
+
+ expect(result.data.agentDocs.status).toBe('missing');
+ expect(result.data.agentDocs.action).toBe('nudge-init');
+ expect(result.data.agentDocs.refreshed).toBe(false);
+ // Must NOT silently create docs during an upgrade.
+ expect(fs.existsSync(path.join(tmpDir, 'AGENTS.md'))).toBe(false);
+ expect(fs.existsSync(path.join(tmpDir, '.claude', 'CLAUDE.md'))).toBe(false);
+ });
+
+ it('treats an agent file without our markers as "never initialized" (missing)', async () => {
+ writePkg();
+ writeInstalledCore('0.0.15');
+ fs.writeFileSync(path.join(tmpDir, 'AGENTS.md'), '# Agents\n\nHand-written, no astryx block.\n');
+ const before = fs.readFileSync(path.join(tmpDir, 'AGENTS.md'), 'utf-8');
+
+ const result = await runJson(['--json', 'upgrade', '--from', '0.0.15', '--apply']);
+
+ expect(result.data.agentDocs.status).toBe('missing');
+ expect(result.data.agentDocs.action).toBe('nudge-init');
+ // An unmarked file is left exactly as-is.
+ expect(fs.readFileSync(path.join(tmpDir, 'AGENTS.md'), 'utf-8')).toBe(before);
+ });
+
+ it('does not silently no-op a stale block with malformed markers (START without END)', async () => {
+ writePkg();
+ writeInstalledCore('0.0.15');
+ // A corrupted block: START + version header but no matching END marker, so
+ // the writer can't safely splice it. This must not crash, corrupt the file,
+ // or falsely claim success — it should surface an error and nudge re-init.
+ const corrupted =
+ '# A\n\n<!-- ASTRYX:START -->\nAstryx v0.0.1 · 9 components\nguidance, but no end marker\n';
+ fs.writeFileSync(path.join(tmpDir, 'AGENTS.md'), corrupted);
+
+ const result = await runJson(['--json', 'upgrade', '--from', '0.0.15', '--apply']);
+
+ expect(result.data.agentDocs.status).toBe('stale');
+ expect(result.data.agentDocs.action).toBe('error');
+ expect(result.data.agentDocs.refreshed).toBe(false);
+ // File left byte-for-byte intact — never corrupted.
+ expect(fs.readFileSync(path.join(tmpDir, 'AGENTS.md'), 'utf-8')).toBe(corrupted);
+ });
+
+ it('stays silent when the block already matches the installed version', async () => {
+ writePkg();
+ writeInstalledCore('0.0.15');
+ writeAgentBlock('AGENTS.md', '0.0.15');
+
+ const result = await runJson(['--json', 'upgrade', '--from', '0.0.15', '--apply']);
+
+ expect(result.data.agentDocs.status).toBe('current');
+ expect(result.data.agentDocs.action).toBe('none');
+ expect(result.data.agentDocs.refreshed).toBe(false);
+ });
+
+ it('migrates a legacy XDS block to the current Astryx block (--apply)', async () => {
+ writePkg();
+ writeInstalledCore('0.0.15');
+ fs.writeFileSync(
+ path.join(tmpDir, 'CLAUDE.md'),
+ '# Claude\n\n<!-- XDS:START -->\nlegacy index\n<!-- XDS:END -->\n\nMore rules.\n',
+ );
+
+ const result = await runJson(['--json', 'upgrade', '--from', '0.0.15', '--apply']);
+
+ expect(result.data.agentDocs.status).toBe('stale');
+ expect(result.data.agentDocs.refreshed).toBe(true);
+ const content = fs.readFileSync(path.join(tmpDir, 'CLAUDE.md'), 'utf-8');
+ expect(content).toContain('<!-- ASTRYX:START -->');
+ expect(content).toMatch(/Astryx v0\.0\.15 ·/);
+ expect(content).not.toContain('legacy index');
+ expect(content).toContain('More rules.');
+ });
+
+ it('surfaces agentDocs in the human output on the up-to-date path', async () => {
+ writePkg();
+ writeInstalledCore('0.0.15');
+ writeAgentBlock('AGENTS.md', '0.0.1');
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'astryx', 'upgrade', '--from', '0.0.15', '--apply']);
+ const output = stdoutCalls.join('') + logCalls.join('\n');
+ expect(output).toMatch(/Agent docs refreshed/i);
+ });
+});
diff --git a/packages/cli/src/types/upgrade.d.ts b/packages/cli/src/types/upgrade.d.ts
index 1f910756c0..9c4802d6b3 100644
--- a/packages/cli/src/types/upgrade.d.ts
+++ b/packages/cli/src/types/upgrade.d.ts
@@ -23,6 +23,31 @@ export interface UpgradeListEntry {
version: string;
}
+/**
+ * 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.
+ *
+ * - `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).
+ */
+export interface AgentDocsSummary {
+ status: 'missing' | 'stale' | 'current';
+ /** Installed core version the block should reflect. */
+ installedVersion: string;
+ /** Distinct stale block versions found (the "from" side of the refresh). */
+ fromVersions: string[];
+ /** Files rewritten (apply) or that would be rewritten (dry-run). */
+ files: string[];
+ /** True only when a block was actually rewritten (apply mode). */
+ refreshed: boolean;
+ action: 'refreshed' | 'would-refresh' | 'nudge-init' | 'error' | 'none';
+}
+
/** xds --json upgrade [--apply] */
export interface UpgradeRunResponse {
type: 'upgrade.run';
@@ -32,6 +57,7 @@ export interface UpgradeRunResponse {
codemods: number;
depsUpdated: string[];
agentDocsRefreshed: boolean;
+ agentDocs: AgentDocsSummary;
};
}
@@ -49,8 +75,18 @@ export interface UpgradeRunResponse {
export interface UpgradeStatusResponse {
type: 'upgrade.status';
data:
- | {status: 'up_to_date'; from: string; to: string}
- | {status: 'no_codemods'; from: string; to: string}
+ | {
+ status: 'up_to_date';
+ from: string;
+ to: string;
+ agentDocs: AgentDocsSummary;
+ }
+ | {
+ status: 'no_codemods';
+ from: string;
+ to: string;
+ agentDocs: AgentDocsSummary;
+ }
| {
status: 'config_fixable';
from: string;
@@ -60,5 +96,6 @@ export interface UpgradeStatusResponse {
suggestedCommand: string;
message: string;
note: string;
+ agentDocs: AgentDocsSummary;
};
}