Skip to content

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

TypeScript

refactor(cli,core): one dep-free source for the astryx-init setup check (#4162)

Joey715718710bf4
diff --git a/.changeset/cli-core-one-setup-contract.md b/.changeset/cli-core-one-setup-contract.md
new file mode 100644
index 0000000000..5a3bdae863
--- /dev/null
+++ b/.changeset/cli-core-one-setup-contract.md
@@ -0,0 +1,11 @@
+---
+'@astryxdesign/cli': patch
+'@astryxdesign/core': patch
+---
+
+[refactor] Core's postinstall no longer hand-mirrors the setup contract. `packages/core/scripts/agent-doc-state.mjs` is now GENERATED byte-for-byte from the CLI's dependency-free leaf `packages/cli/foundation/agent-docs/agent-doc-state.mjs`, and `pnpm check:setup-contract` — wired into `check:repo` — fails the build when the two differ.
+
+The previous guard compared two hand-edited constant lists. That caught a new agent-doc path or a new marker, and nothing else: the predicate itself, and the `shouldNudge` decision matrix duplicated in both postinstall scripts, could still drift and leave layer 1 and layer 2 disagreeing about "is this project set up?" with the test green. `shouldNudge` and the nudge string move into the contract as well, so all four things — paths, markers, predicate, decision — now have one definition and one place to edit.
+
+Behavior is unchanged, and verified rather than assumed: the nudge text is byte-identical, legacy `<!-- XDS:START -->` blocks still count as set up, all six agent-doc locations are still detected, and both scripts still exit 0 on every path including failure. Core loads its copy with a dynamic import, so a packaging mistake degrades to "no nudge" instead of throwing out of module evaluation and failing a consumer's install. `check:setup-contract` also fails if core stops listing the generated file in `files`, so it cannot go missing in the first place.
+@josephfarina
diff --git a/package.json b/package.json
index c9e46f3aee..4b2fd82d72 100644
--- a/package.json
+++ b/package.json
@@ -11,13 +11,15 @@
"test:watch": "vitest",
"test:coverage": "vitest --coverage",
"check:package-boundaries": "node scripts/check-package-boundaries.js",
- "check:repo": "pnpm check:sync && pnpm check:knowledge && pnpm check:package-boundaries && pnpm check:changesets && pnpm check:demo-media && pnpm check:executable-bits && pnpm check:cli-structure && pnpm check:use-client && pnpm check:portable-scripts && pnpm check:i18n-catalog && pnpm check:cldr-weekdays && pnpm check:fixtures",
+ "check:repo": "pnpm check:sync && pnpm check:knowledge && pnpm check:package-boundaries && pnpm check:changesets && pnpm check:demo-media && pnpm check:executable-bits && pnpm check:cli-structure && pnpm check:use-client && pnpm check:portable-scripts && pnpm check:i18n-catalog && pnpm check:cldr-weekdays && pnpm check:fixtures && pnpm check:setup-contract",
"check:fixtures": "node internal/vibe-tests/scripts/fixture-suite.mjs verify",
"generate:cldr-weekdays": "node scripts/generate-cldr-weekdays.mjs",
"check:cldr-weekdays": "node scripts/generate-cldr-weekdays.mjs --check",
"check:changesets": "node scripts/check-changesets.mjs",
"check:portable-scripts": "node scripts/check-portable-scripts.mjs",
"check:cli-structure": "node scripts/check-cli-structure.mjs",
+ "check:setup-contract": "node scripts/generate-setup-contract.mjs --check",
+ "generate:setup-contract": "node scripts/generate-setup-contract.mjs",
"check:executable-bits": "node scripts/check-executable-bits.mjs",
"check:demo-media": "node scripts/check-demo-media.mjs",
"check:i18n-catalog": "node scripts/check-i18n-catalog.mjs",
diff --git a/packages/cli/foundation/agent-docs/agent-doc-state.mjs b/packages/cli/foundation/agent-docs/agent-doc-state.mjs
new file mode 100644
index 0000000000..632422477e
--- /dev/null
+++ b/packages/cli/foundation/agent-docs/agent-doc-state.mjs
@@ -0,0 +1,127 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file agent-doc-state — the canonical, dependency-free contract for "where
+ * Astryx writes its agent block" and "has this project run init yet?".
+ *
+ * Deliberately a LEAF module: it imports only node builtins (`fs`, `path`), so
+ * it is safe to load in constrained contexts — most importantly the CLI's
+ * `postinstall` script, which runs at `npm install` time, before the rest of the
+ * CLI's module graph is guaranteed importable. Its sibling `agent-docs.mjs`
+ * reaches component discovery, package-manager detection, and the response
+ * layer, so the pure setup-check lives HERE and `agent-docs.mjs` re-exports it.
+ *
+ * SINGLE SOURCE OF TRUTH for every "is Astryx set up?" enforcement layer:
+ * - layer 3 — the per-command setup nudge (`clients/cli/index.mjs`),
+ * - layer 2 — the CLI postinstall nudge (`scripts/postinstall.mjs`),
+ * - the `init` / `upgrade` / `agent-docs` commands (via `agent-docs.mjs`).
+ * Core's postinstall (layer 1) is a separate published package and cannot import
+ * the CLI, so it ships a package-local copy at
+ * `packages/core/scripts/agent-doc-state.mjs`. That copy is GENERATED from this
+ * file, byte for byte, by `scripts/generate-setup-contract.mjs`, and
+ * `pnpm check:setup-contract` (part of `check:repo`) fails the build when the
+ * two differ. Edit the contract HERE and nowhere else.
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+
+export const AGENTS_MD = 'AGENTS.md';
+export const CLAUDE_MD = 'CLAUDE.md';
+export const CLAUDE_DIR_MD = '.claude/CLAUDE.md'; // cross-platform literal
+export const CURSOR_RULES = '.cursorrules';
+export const HERMES_DOT_MD = '.hermes.md';
+export const HERMES_MD = 'HERMES.md';
+
+export const MARKER_START = '<!-- ASTRYX:START -->';
+export const MARKER_END = '<!-- ASTRYX:END -->';
+// Legacy markers — read during migration so the script finds existing XDS blocks
+export const LEGACY_MARKER_START = '<!-- XDS:START -->';
+export const LEGACY_MARKER_END = '<!-- XDS:END -->';
+
+/**
+ * The canonical set of EVERY location an --agent preset (or the default) can
+ * write the Astryx block. SINGLE SOURCE OF TRUTH: discovery, removal, and the
+ * `isAstryxInitialized` predicate all derive from this list, so "where init
+ * writes" and "where we look" can never drift. (Explicit --agent-docs-path
+ * targets are user-chosen and not enumerable here.)
+ */
+export const AGENT_DOC_PATHS = [
+ AGENTS_MD, // Codex / ChatGPT / generic
+ CLAUDE_MD, // Claude Code (root)
+ CLAUDE_DIR_MD, // Claude Code (.claude/CLAUDE.md)
+ CURSOR_RULES, // Cursor
+ HERMES_DOT_MD, // Hermes
+ HERMES_MD, // Hermes
+];
+
+/**
+ * Markers whose presence means an Astryx block has been installed — the current
+ * marker plus the legacy XDS one, so pre-rename projects still count as set up.
+ */
+export const INIT_MARKERS = [MARKER_START, LEGACY_MARKER_START];
+
+/**
+ * Find all existing agent doc files in a directory, across EVERY location any
+ * preset can write (see {@link AGENT_DOC_PATHS}: AGENTS.md, CLAUDE.md,
+ * .claude/CLAUDE.md, .cursorrules, .hermes.md, HERMES.md).
+ * @param {string} targetDir
+ * @returns {string[]} Relative paths of existing agent doc files
+ */
+export function discoverAgentDocs(targetDir) {
+ return AGENT_DOC_PATHS.filter(p => fs.existsSync(path.join(targetDir, p)));
+}
+
+/**
+ * Single source of truth for "is Astryx set up in this project?" — true when any
+ * agent-doc file already carries the Astryx marker, i.e. `init` / `agent-docs`
+ * has run. Reused by the init & upgrade commands, the per-command setup nudge
+ * (enforcement layer 3), and the cli postinstall nudge (layer 2). Core's
+ * postinstall (separate package, layer 1) mirrors the same marker contract.
+ *
+ * @param {string} [targetDir=process.cwd()]
+ * @returns {boolean}
+ */
+export function isAstryxInitialized(targetDir = process.cwd()) {
+ for (const rel of discoverAgentDocs(targetDir)) {
+ try {
+ const content = fs.readFileSync(path.join(targetDir, rel), 'utf-8');
+ if (INIT_MARKERS.some(m => content.includes(m))) {
+ return true;
+ }
+ } catch {
+ // Unreadable file — ignore and keep checking the others.
+ }
+ }
+ return false;
+}
+
+/**
+ * The one-line next-step both postinstall nudges print. Kept here so layer 1
+ * (core) and layer 2 (cli) can never word it differently.
+ *
+ * Scoped package form (`@astryxdesign/cli`) — always resolves to us, even before
+ * the CLI is installed. Bare `npx astryx` would fetch an unrelated look-alike
+ * package (see PR #4151).
+ */
+export const SETUP_NUDGE =
+ '\nNext step: run `npx @astryxdesign/cli init` to finish setup and install the Astryx agent prompt.\n\n';
+
+/**
+ * Pure decision: should a postinstall print the setup nudge? Shared by BOTH
+ * postinstall layers, so the matrix cannot drift between them, and unit-testable
+ * without an actual npm install.
+ *
+ * @param {object} [opts]
+ * @param {string} [opts.scriptPath] - Absolute path of the calling script
+ * (location tells us dependency vs monorepo vs npx-cache).
+ * @param {string} [opts.npmCommand] - process.env.npm_command ('install', 'exec', …).
+ * @param {boolean} [opts.isSetUp] - Whether the project already ran init.
+ * @returns {boolean}
+ */
+export function shouldNudge({scriptPath, npmCommand, isSetUp} = {}) {
+ if (!scriptPath || !scriptPath.includes('node_modules')) return false; // monorepo/source build
+ if (scriptPath.includes('_npx') || npmCommand === 'exec') return false; // npx transient — init runs next
+ if (isSetUp) return false; // already set up — stay quiet
+ return true;
+}
diff --git a/packages/cli/foundation/agent-docs/agent-docs.mjs b/packages/cli/foundation/agent-docs/agent-docs.mjs
index dcf394269f..c0b466f4d4 100644
--- a/packages/cli/foundation/agent-docs/agent-docs.mjs
+++ b/packages/cli/foundation/agent-docs/agent-docs.mjs
@@ -25,20 +25,28 @@ import {assertWithin} from '../fs/path-safety.mjs';
import {getCliInvocation} from '../env/package-manager.mjs';
import {discoverComponents} from '../discovery/component-discovery.mjs';
import {humanLog} from '../response/json.mjs';
-
-const AGENTS_MD = 'AGENTS.md';
-const CLAUDE_MD = 'CLAUDE.md';
-const CLAUDE_DIR_MD = '.claude/CLAUDE.md'; // cross-platform literal
-const CURSOR_RULES = '.cursorrules';
-const HERMES_DOT_MD = '.hermes.md';
-const HERMES_MD = 'HERMES.md';
-
-
-const MARKER_START = '<!-- ASTRYX:START -->';
-const MARKER_END = '<!-- ASTRYX:END -->';
-// Legacy markers — read during migration so the script finds existing XDS blocks
-const LEGACY_MARKER_START = '<!-- XDS:START -->';
-const LEGACY_MARKER_END = '<!-- XDS:END -->';
+import {
+ AGENTS_MD,
+ CLAUDE_MD,
+ CLAUDE_DIR_MD,
+ CURSOR_RULES,
+ HERMES_DOT_MD,
+ HERMES_MD,
+ MARKER_START,
+ MARKER_END,
+ LEGACY_MARKER_START,
+ LEGACY_MARKER_END,
+ discoverAgentDocs,
+ isAstryxInitialized,
+} from './agent-doc-state.mjs';
+
+// The agent-doc locations, markers, and the setup-state predicates
+// (discoverAgentDocs, isAstryxInitialized) are the ONE canonical contract. They
+// live in the dependency-free leaf ./agent-doc-state.mjs so the postinstall
+// nudge (enforcement layer 2) can load them safely at install time. Re-exported
+// here so existing importers (init/upgrade commands, the layer-3 nudge in
+// clients/cli/index.mjs, tests) keep their `from './agent-docs.mjs'` paths.
+export {discoverAgentDocs, isAstryxInitialized};
/**
* Locate the single well-formed managed block in `content`.
@@ -90,57 +98,6 @@ const AGENT_PRESETS = {
hermes: [HERMES_DOT_MD, HERMES_MD, AGENTS_MD],
};
-/**
- * The canonical set of EVERY location an --agent preset (or the default) can
- * write the Astryx block. SINGLE SOURCE OF TRUTH: discovery, removal, and the
- * `isAstryxInitialized` predicate all derive from this list, so "where init
- * writes" and "where we look" can never drift. (Explicit --agent-docs-path
- * targets are user-chosen and not enumerable here.)
- */
-const AGENT_DOC_PATHS = [
- AGENTS_MD, // Codex / ChatGPT / generic
- CLAUDE_MD, // Claude Code (root)
- CLAUDE_DIR_MD, // Claude Code (.claude/CLAUDE.md)
- CURSOR_RULES, // Cursor
- HERMES_DOT_MD, // Hermes
- HERMES_MD, // Hermes
-];
-
-/**
- * Find all existing agent doc files in a directory, across EVERY location any
- * preset can write (see {@link AGENT_DOC_PATHS}: AGENTS.md, CLAUDE.md,
- * .claude/CLAUDE.md, .cursorrules, .hermes.md, HERMES.md).
- * @param {string} targetDir
- * @returns {string[]} Relative paths of existing agent doc files
- */
-export function discoverAgentDocs(targetDir) {
- return AGENT_DOC_PATHS.filter(p => fs.existsSync(path.join(targetDir, p)));
-}
-
-/**
- * Single source of truth for "is Astryx set up in this project?" — true when any
- * agent-doc file already carries the Astryx marker, i.e. `init` / `agent-docs`
- * has run. Reused by the init & upgrade commands, the per-command setup nudge
- * (enforcement layer 3), and the cli postinstall nudge (layer 2). Core's
- * postinstall (separate package, layer 1) mirrors the same marker contract.
- *
- * @param {string} [targetDir=process.cwd()]
- * @returns {boolean}
- */
-export function isAstryxInitialized(targetDir = process.cwd()) {
- for (const rel of discoverAgentDocs(targetDir)) {
- try {
- const content = fs.readFileSync(path.join(targetDir, rel), 'utf-8');
- if (content.includes(MARKER_START) || content.includes(LEGACY_MARKER_START)) {
- return true;
- }
- } catch {
- // Unreadable file — ignore and keep checking the others.
- }
- }
- 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
@@ -316,6 +273,9 @@ export function detectStylingSystem(targetDir) {
*/
export function generateCompressedIndex(version, {coreDir, invocation = getCliInvocation(), stylingSystem = 'css', topics} = {}) {
const run = invocation;
+ // 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[]} */
const lines = [MARKER_START];
// Component count from live discovery
diff --git a/packages/cli/scripts/postinstall.mjs b/packages/cli/scripts/postinstall.mjs
index e61ec720c6..3ce12fd235 100644
--- a/packages/cli/scripts/postinstall.mjs
+++ b/packages/cli/scripts/postinstall.mjs
@@ -7,9 +7,11 @@
* installed as a project dependency and the project hasn't run init yet, print a
* one-line next-step so agents/humans discover it.
*
- * Reuses the ONE setup check (isAstryxInitialized from agent-docs.mjs — a
- * dep-free import chain, safe at install time). Non-interactive, never fails the
- * install, and stays quiet:
+ * Reuses the ONE setup check (isAstryxInitialized) from the dependency-free leaf
+ * ../foundation/agent-docs/agent-doc-state.mjs — node builtins only, so it is
+ * genuinely safe to load at install time (importing agent-docs.mjs would drag in
+ * the full CLI module graph). Non-interactive, never fails the install, and
+ * stays quiet:
* - in the monorepo/source build (not under node_modules),
* - during npx's transient fetch (npx runs the bin — likely `init` — right
* after, so nudging here would double up), and
@@ -17,31 +19,31 @@
*/
import {fileURLToPath, pathToFileURL} from 'node:url';
+// The ONE setup contract, shared with core's postinstall (which ships a
+// generated byte-for-byte copy). Node builtins only, and in this package, so it
+// is safe to load at install time.
+import {
+ shouldNudge,
+ SETUP_NUDGE,
+} from '../foundation/agent-docs/agent-doc-state.mjs';
const HERE = fileURLToPath(import.meta.url);
/**
- * Pure decision: should the postinstall print the setup nudge? Split out so the
- * matrix is unit-testable without an actual npm install.
- *
- * @param {object} [opts]
- * @param {string} [opts.scriptPath] - Absolute path of this script (location tells
- * us dependency vs monorepo vs npx-cache).
- * @param {string} [opts.npmCommand] - process.env.npm_command ('install', 'exec', …).
- * @param {boolean} [opts.isSetUp] - Whether the project already ran init.
- * @returns {boolean}
+ * Re-exported so this layer's tests, and anything already importing it from
+ * here, keep working. The implementation lives in the shared contract.
*/
-export function shouldNudge({scriptPath, npmCommand, isSetUp} = {}) {
- if (!scriptPath || !scriptPath.includes('node_modules')) return false; // monorepo/source build
- if (scriptPath.includes('_npx') || npmCommand === 'exec') return false; // npx transient — init runs next
- if (isSetUp) return false; // already set up — stay quiet
- return true;
-}
+export {shouldNudge};
/** @param {string} root @returns {Promise<boolean>} */
async function projectIsSetUp(root) {
try {
- const {isAstryxInitialized} = await import('../foundation/agent-docs/agent-docs.mjs');
+ // Dep-free leaf (node builtins only) — safe to load mid-install. NOT
+ // agent-docs.mjs, whose static graph (component discovery, package-manager
+ // detection, …) isn't guaranteed importable yet during this postinstall.
+ const {isAstryxInitialized} = await import(
+ '../foundation/agent-docs/agent-doc-state.mjs'
+ );
return isAstryxInitialized(root);
} catch {
return false; // best-effort — if the check can't load, fall through and nudge
@@ -56,12 +58,7 @@ async function main() {
isSetUp: await projectIsSetUp(root),
});
if (nudge) {
- // Scoped package form (`@astryxdesign/cli`) — always resolves to us. Bare
- // `npx astryx` would fetch an unrelated look-alike package (see PR #4151).
- // After that lands, switch this to its getCliInvocation() single source of truth.
- process.stdout.write(
- '\nNext step: run `npx @astryxdesign/cli init` to finish setup and install the Astryx agent prompt.\n\n',
- );
+ process.stdout.write(SETUP_NUDGE);
}
}
diff --git a/packages/core/package.json b/packages/core/package.json
index 33e63655a7..6d41eefbea 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -654,6 +654,7 @@
"dist",
"src",
"scripts/postinstall.mjs",
+ "scripts/agent-doc-state.mjs",
"locales",
"docs.mjs",
"groups.doc.mjs",
diff --git a/packages/core/scripts/agent-doc-state.mjs b/packages/core/scripts/agent-doc-state.mjs
new file mode 100644
index 0000000000..d16dd30b66
--- /dev/null
+++ b/packages/core/scripts/agent-doc-state.mjs
@@ -0,0 +1,137 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+// GENERATED FILE — DO NOT EDIT.
+// Source: packages/cli/foundation/agent-docs/agent-doc-state.mjs
+// Regenerate: pnpm generate:setup-contract
+//
+// @astryxdesign/core cannot import @astryxdesign/cli (the CLI peer-depends on
+// core, so the import would be a cycle), but core's postinstall must answer
+// "is Astryx set up?" exactly as the CLI does. The CLI's dependency-free leaf is
+// therefore copied here verbatim and pinned by `pnpm check:setup-contract`,
+// which runs inside `pnpm check:repo`.
+
+/**
+ * @file agent-doc-state — the canonical, dependency-free contract for "where
+ * Astryx writes its agent block" and "has this project run init yet?".
+ *
+ * Deliberately a LEAF module: it imports only node builtins (`fs`, `path`), so
+ * it is safe to load in constrained contexts — most importantly the CLI's
+ * `postinstall` script, which runs at `npm install` time, before the rest of the
+ * CLI's module graph is guaranteed importable. Its sibling `agent-docs.mjs`
+ * reaches component discovery, package-manager detection, and the response
+ * layer, so the pure setup-check lives HERE and `agent-docs.mjs` re-exports it.
+ *
+ * SINGLE SOURCE OF TRUTH for every "is Astryx set up?" enforcement layer:
+ * - layer 3 — the per-command setup nudge (`clients/cli/index.mjs`),
+ * - layer 2 — the CLI postinstall nudge (`scripts/postinstall.mjs`),
+ * - the `init` / `upgrade` / `agent-docs` commands (via `agent-docs.mjs`).
+ * Core's postinstall (layer 1) is a separate published package and cannot import
+ * the CLI, so it ships a package-local copy at
+ * `packages/core/scripts/agent-doc-state.mjs`. That copy is GENERATED from this
+ * file, byte for byte, by `scripts/generate-setup-contract.mjs`, and
+ * `pnpm check:setup-contract` (part of `check:repo`) fails the build when the
+ * two differ. Edit the contract HERE and nowhere else.
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+
+export const AGENTS_MD = 'AGENTS.md';
+export const CLAUDE_MD = 'CLAUDE.md';
+export const CLAUDE_DIR_MD = '.claude/CLAUDE.md'; // cross-platform literal
+export const CURSOR_RULES = '.cursorrules';
+export const HERMES_DOT_MD = '.hermes.md';
+export const HERMES_MD = 'HERMES.md';
+
+export const MARKER_START = '<!-- ASTRYX:START -->';
+export const MARKER_END = '<!-- ASTRYX:END -->';
+// Legacy markers — read during migration so the script finds existing XDS blocks
+export const LEGACY_MARKER_START = '<!-- XDS:START -->';
+export const LEGACY_MARKER_END = '<!-- XDS:END -->';
+
+/**
+ * The canonical set of EVERY location an --agent preset (or the default) can
+ * write the Astryx block. SINGLE SOURCE OF TRUTH: discovery, removal, and the
+ * `isAstryxInitialized` predicate all derive from this list, so "where init
+ * writes" and "where we look" can never drift. (Explicit --agent-docs-path
+ * targets are user-chosen and not enumerable here.)
+ */
+export const AGENT_DOC_PATHS = [
+ AGENTS_MD, // Codex / ChatGPT / generic
+ CLAUDE_MD, // Claude Code (root)
+ CLAUDE_DIR_MD, // Claude Code (.claude/CLAUDE.md)
+ CURSOR_RULES, // Cursor
+ HERMES_DOT_MD, // Hermes
+ HERMES_MD, // Hermes
+];
+
+/**
+ * Markers whose presence means an Astryx block has been installed — the current
+ * marker plus the legacy XDS one, so pre-rename projects still count as set up.
+ */
+export const INIT_MARKERS = [MARKER_START, LEGACY_MARKER_START];
+
+/**
+ * Find all existing agent doc files in a directory, across EVERY location any
+ * preset can write (see {@link AGENT_DOC_PATHS}: AGENTS.md, CLAUDE.md,
+ * .claude/CLAUDE.md, .cursorrules, .hermes.md, HERMES.md).
+ * @param {string} targetDir
+ * @returns {string[]} Relative paths of existing agent doc files
+ */
+export function discoverAgentDocs(targetDir) {
+ return AGENT_DOC_PATHS.filter(p => fs.existsSync(path.join(targetDir, p)));
+}
+
+/**
+ * Single source of truth for "is Astryx set up in this project?" — true when any
+ * agent-doc file already carries the Astryx marker, i.e. `init` / `agent-docs`
+ * has run. Reused by the init & upgrade commands, the per-command setup nudge
+ * (enforcement layer 3), and the cli postinstall nudge (layer 2). Core's
+ * postinstall (separate package, layer 1) mirrors the same marker contract.
+ *
+ * @param {string} [targetDir=process.cwd()]
+ * @returns {boolean}
+ */
+export function isAstryxInitialized(targetDir = process.cwd()) {
+ for (const rel of discoverAgentDocs(targetDir)) {
+ try {
+ const content = fs.readFileSync(path.join(targetDir, rel), 'utf-8');
+ if (INIT_MARKERS.some(m => content.includes(m))) {
+ return true;
+ }
+ } catch {
+ // Unreadable file — ignore and keep checking the others.
+ }
+ }
+ return false;
+}
+
+/**
+ * The one-line next-step both postinstall nudges print. Kept here so layer 1
+ * (core) and layer 2 (cli) can never word it differently.
+ *
+ * Scoped package form (`@astryxdesign/cli`) — always resolves to us, even before
+ * the CLI is installed. Bare `npx astryx` would fetch an unrelated look-alike
+ * package (see PR #4151).
+ */
+export const SETUP_NUDGE =
+ '\nNext step: run `npx @astryxdesign/cli init` to finish setup and install the Astryx agent prompt.\n\n';
+
+/**
+ * Pure decision: should a postinstall print the setup nudge? Shared by BOTH
+ * postinstall layers, so the matrix cannot drift between them, and unit-testable
+ * without an actual npm install.
+ *
+ * @param {object} [opts]
+ * @param {string} [opts.scriptPath] - Absolute path of the calling script
+ * (location tells us dependency vs monorepo vs npx-cache).
+ * @param {string} [opts.npmCommand] - process.env.npm_command ('install', 'exec', …).
+ * @param {boolean} [opts.isSetUp] - Whether the project already ran init.
+ * @returns {boolean}
+ */
+export function shouldNudge({scriptPath, npmCommand, isSetUp} = {}) {
+ if (!scriptPath || !scriptPath.includes('node_modules')) return false; // monorepo/source build
+ if (scriptPath.includes('_npx') || npmCommand === 'exec') return false; // npx transient — init runs next
+ if (isSetUp) return false; // already set up — stay quiet
+ return true;
+}
diff --git a/packages/core/scripts/postinstall.mjs b/packages/core/scripts/postinstall.mjs
index 9f42321195..c913e23671 100644
--- a/packages/core/scripts/postinstall.mjs
+++ b/packages/core/scripts/postinstall.mjs
@@ -7,87 +7,55 @@
* is installed and the project hasn't run init yet, print a one-line next-step
* so agents/humans discover it (this is the most common fresh-install entry).
*
- * Self-contained: core is a separate package and cannot import the CLI, so the
- * agent-doc locations + marker below intentionally DUPLICATE the CLI's agent-doc
- * discovery in packages/cli/src/commands/agent-docs.mjs — keep them aligned with
- * that file. The .hermes.md / HERMES.md entries are an intentional superset (the
- * CLI writes those via `--agent hermes`). Non-interactive, never fails the
- * install, and quiet in the monorepo build, during npx's fetch, and once set up.
+ * ONE authoritative source. Core is a separate package and cannot import the CLI
+ * (the CLI peer-depends on core, so importing it would be a cycle), so it ships
+ * ./agent-doc-state.mjs — a GENERATED, byte-for-byte copy of the CLI's
+ * dependency-free leaf packages/cli/foundation/agent-docs/agent-doc-state.mjs.
+ * `pnpm check:setup-contract` (inside `pnpm check:repo`) fails the build if the
+ * two differ, and also fails if core stops publishing the copy. The paths,
+ * markers, predicate and nudge decision therefore cannot drift between layers.
+ *
+ * Non-interactive, never fails the install, and quiet in the monorepo build,
+ * during npx's fetch, and once set up.
*/
-import fs from 'node:fs';
-import path from 'node:path';
import {fileURLToPath, pathToFileURL} from 'node:url';
const HERE = fileURLToPath(import.meta.url);
-// Duplicates the CLI's agent-doc locations + markers — keep aligned with
-// packages/cli/src/commands/agent-docs.mjs. Hermes files are an intentional superset.
-const AGENT_DOC_PATHS = [
- 'AGENTS.md',
- 'CLAUDE.md',
- '.claude/CLAUDE.md',
- '.cursorrules',
- '.hermes.md',
- 'HERMES.md',
-];
-const MARKERS = ['<!-- ASTRYX:START -->', '<!-- XDS:START -->'];
-
/**
- * True when the project already has the Astryx agent prompt installed (an Astryx
- * marker is present in any agent-doc file) — the same check the CLI performs.
- * @param {string} root @returns {boolean}
+ * Load the generated contract copy. Dynamic, not static, so a packaging mistake
+ * degrades to "no nudge" instead of throwing out of module evaluation and
+ * failing a consumer's install — the one thing this script must never do.
+ * @returns {Promise<object|null>}
*/
-export function isAstryxInitialized(root) {
- for (const rel of AGENT_DOC_PATHS) {
- try {
- const content = fs.readFileSync(path.join(root, rel), 'utf-8');
- if (MARKERS.some(m => content.includes(m))) return true;
- } catch {
- // Unreadable/missing — keep checking the others.
- }
+async function loadContract() {
+ try {
+ return await import('./agent-doc-state.mjs');
+ } catch {
+ return null;
}
- return false;
}
-/**
- * Pure decision: should the postinstall print the setup nudge? Unit-testable
- * without an actual npm install.
- * @returns {boolean}
- */
-export function shouldNudge({scriptPath, npmCommand, isSetUp} = {}) {
- if (!scriptPath || !scriptPath.includes('node_modules')) return false; // monorepo/source build
- if (scriptPath.includes('_npx') || npmCommand === 'exec') return false; // npx transient
- if (isSetUp) return false; // already set up — stay quiet
- return true;
-}
-
-function main() {
+async function main() {
+ const contract = await loadContract();
+ if (!contract) return;
const root = process.env.INIT_CWD || process.cwd();
if (
- shouldNudge({
+ contract.shouldNudge({
scriptPath: HERE,
npmCommand: process.env.npm_command,
- isSetUp: isAstryxInitialized(root),
+ isSetUp: contract.isAstryxInitialized(root),
})
) {
- // Scoped package form (`@astryxdesign/cli`) — always resolves to us, even
- // before the CLI is installed. Bare `npx astryx` would fetch an unrelated
- // look-alike package (see PR #4151). After that lands, switch this to its
- // getCliInvocation() single source of truth.
- process.stdout.write(
- '\nNext step: run `npx @astryxdesign/cli init` to finish setup and install the Astryx agent prompt.\n\n',
- );
+ process.stdout.write(contract.SETUP_NUDGE);
}
}
// Run only when executed directly (`node scripts/postinstall.mjs`), never when
// imported by tests.
if (import.meta.url === pathToFileURL(process.argv[1] || '').href) {
- try {
- main();
- } catch {
- // never break an install
- }
- process.exit(0);
+ main()
+ .catch(() => {}) // never break an install
+ .finally(() => process.exit(0));
}
diff --git a/packages/core/src/postinstall.test.mjs b/packages/core/src/postinstall.test.mjs
index e087e8ca89..536468ae34 100644
--- a/packages/core/src/postinstall.test.mjs
+++ b/packages/core/src/postinstall.test.mjs
@@ -3,16 +3,35 @@
/**
* @file Guardrail tests for the @astryxdesign/core postinstall nudge (layer 1).
*
- * The marker check mirrors the CLI's single source of truth (core can't import
- * the CLI). Tests that it detects the marker across EVERY agent-doc location
- * (incl. Hermes) + legacy markers, and that the nudge decision matrix is correct.
+ * Core cannot import the CLI, so it ships scripts/agent-doc-state.mjs — a
+ * GENERATED, byte-for-byte copy of the CLI's dependency-free leaf. These tests
+ * cover the behaviour core depends on (marker detection across EVERY agent-doc
+ * location, legacy markers, the nudge decision matrix) and pin the copy to its
+ * source by BYTES, so semantic drift is impossible rather than merely unlikely.
*/
import {describe, it, expect, beforeEach, afterEach} from 'vitest';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
-import {isAstryxInitialized, shouldNudge} from '../scripts/postinstall.mjs';
+// Core's own package-local contract copy — what actually runs at install time.
+import {
+ isAstryxInitialized,
+ shouldNudge,
+ AGENT_DOC_PATHS,
+ INIT_MARKERS,
+ SETUP_NUDGE,
+} from '../scripts/agent-doc-state.mjs';
+// Dev-only, monorepo-relative: core must not depend on the CLI at runtime (the
+// CLI peer-depends on core), but the test can read the source and the generator.
+import * as cliLeaf from '../../cli/foundation/agent-docs/agent-doc-state.mjs';
+import {
+ renderCoreCopy,
+ checkCorePackaging,
+ CORE_TARGET,
+ CORE_TARGET_REL,
+ CLI_SOURCE_REL,
+} from '../../../scripts/generate-setup-contract.mjs';
const MARKER = '<!-- ASTRYX:START -->';
@@ -29,7 +48,7 @@ function write(rel, body) {
fs.writeFileSync(p, body);
}
-describe('core postinstall — isAstryxInitialized (mirrors CLI contract)', () => {
+describe('core postinstall — isAstryxInitialized (shared contract)', () => {
it('is false in an empty project', () => {
expect(isAstryxInitialized(tmp)).toBe(false);
});
@@ -48,6 +67,39 @@ describe('core postinstall — isAstryxInitialized (mirrors CLI contract)', () =
});
});
+describe('core postinstall — one authoritative source, no drift', () => {
+ // The previous guard compared two hand-edited constant lists, so a change to
+ // the PREDICATE (or to shouldNudge) could still make the two layers disagree
+ // about "is this project set up?" while the test stayed green. Core's copy is
+ // now generated from the CLI leaf, so the guard is byte equality: nothing in
+ // the contract — paths, markers, predicate or nudge decision — can diverge.
+ it('is byte-identical to what the generator produces from the CLI leaf', () => {
+ expect(fs.readFileSync(CORE_TARGET, 'utf-8')).toBe(renderCoreCopy());
+ });
+
+ it('names its source, so an editor of the copy is sent to the right file', () => {
+ const copy = fs.readFileSync(CORE_TARGET, 'utf-8');
+ expect(copy).toContain('GENERATED FILE');
+ expect(copy).toContain(CLI_SOURCE_REL);
+ });
+
+ it(`publishes ${CORE_TARGET_REL} in core's tarball`, () => {
+ // A copy core does not ship is a copy core's postinstall cannot import.
+ expect(checkCorePackaging()).toBeNull();
+ });
+
+ it('exposes the same contract values as the CLI leaf', () => {
+ expect(AGENT_DOC_PATHS).toEqual(cliLeaf.AGENT_DOC_PATHS);
+ expect(INIT_MARKERS).toEqual(cliLeaf.INIT_MARKERS);
+ expect(SETUP_NUDGE).toBe(cliLeaf.SETUP_NUDGE);
+ });
+
+ it('agrees with the CLI leaf on a real project', () => {
+ write('AGENTS.md', `# doc\n${MARKER}\nbody`);
+ expect(isAstryxInitialized(tmp)).toBe(cliLeaf.isAstryxInitialized(tmp));
+ });
+});
+
describe('core postinstall — shouldNudge', () => {
const DEP = '/proj/node_modules/@astryxdesign/core/scripts/postinstall.mjs';
const NPX = '/Users/x/.npm/_npx/a1/node_modules/@astryxdesign/core/scripts/postinstall.mjs';
@@ -68,4 +120,18 @@ describe('core postinstall — shouldNudge', () => {
it('quiet once set up', () => {
expect(shouldNudge({scriptPath: DEP, npmCommand: 'install', isSetUp: true})).toBe(false);
});
+ it('quiet with no arguments at all', () => {
+ expect(shouldNudge({})).toBe(false);
+ });
+ it('is the same decision the CLI layer makes', () => {
+ for (const scriptPath of [DEP, NPX, REPO]) {
+ for (const npmCommand of ['install', 'exec']) {
+ for (const isSetUp of [true, false]) {
+ expect(shouldNudge({scriptPath, npmCommand, isSetUp})).toBe(
+ cliLeaf.shouldNudge({scriptPath, npmCommand, isSetUp}),
+ );
+ }
+ }
+ }
+ });
});
diff --git a/scripts/generate-setup-contract.mjs b/scripts/generate-setup-contract.mjs
new file mode 100644
index 0000000000..72343364eb
--- /dev/null
+++ b/scripts/generate-setup-contract.mjs
@@ -0,0 +1,122 @@
+#!/usr/bin/env node
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Generate (and verify) core's package-local copy of the agent-doc setup
+ * contract.
+ *
+ * ONE authoritative source, two published packages. `@astryxdesign/core` cannot
+ * import `@astryxdesign/cli` — the CLI peer-depends on core, so the import would
+ * be a cycle — yet core's postinstall (enforcement layer 1) must answer
+ * "is Astryx set up?" exactly as the CLI does (layers 2 and 3). Hand-mirroring
+ * the paths, markers and predicate is what let the two drift.
+ *
+ * So the CLI's dependency-free leaf is copied here VERBATIM, with a generated
+ * banner, into a file core ships in its own tarball:
+ *
+ * source -> packages/cli/foundation/agent-docs/agent-doc-state.mjs
+ * target -> packages/core/scripts/agent-doc-state.mjs
+ *
+ * Because the copy is byte-for-byte, drift is not "checked" heuristically, it is
+ * impossible: `--check` compares bytes and fails the build.
+ *
+ * Usage:
+ * node scripts/generate-setup-contract.mjs # write the copy
+ * node scripts/generate-setup-contract.mjs --check # verify, exit 1 on drift
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {fileURLToPath, pathToFileURL} from 'node:url';
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+
+export const CLI_SOURCE_REL =
+ 'packages/cli/foundation/agent-docs/agent-doc-state.mjs';
+export const CORE_TARGET_REL = 'packages/core/scripts/agent-doc-state.mjs';
+
+export const CLI_SOURCE = path.join(ROOT, CLI_SOURCE_REL);
+export const CORE_TARGET = path.join(ROOT, CORE_TARGET_REL);
+
+const COPYRIGHT = '// Copyright (c) Meta Platforms, Inc. and affiliates.\n';
+
+const BANNER = `
+// GENERATED FILE — DO NOT EDIT.
+// Source: ${CLI_SOURCE_REL}
+// Regenerate: pnpm generate:setup-contract
+//
+// @astryxdesign/core cannot import @astryxdesign/cli (the CLI peer-depends on
+// core, so the import would be a cycle), but core's postinstall must answer
+// "is Astryx set up?" exactly as the CLI does. The CLI's dependency-free leaf is
+// therefore copied here verbatim and pinned by \`pnpm check:setup-contract\`,
+// which runs inside \`pnpm check:repo\`.
+`;
+
+/**
+ * The exact bytes core's copy must contain.
+ * @returns {string}
+ */
+export function renderCoreCopy() {
+ const source = fs.readFileSync(CLI_SOURCE, 'utf-8');
+ if (!source.startsWith(COPYRIGHT)) {
+ throw new Error(
+ `${CLI_SOURCE_REL} must start with the copyright header so the generated copy keeps it first.`,
+ );
+ }
+ return COPYRIGHT + BANNER + source.slice(COPYRIGHT.length);
+}
+
+/**
+ * core must PUBLISH the generated copy, or its postinstall silently loses the
+ * setup check in every consumer install. Cheap to assert, expensive to miss.
+ * @returns {string|null} An error message, or null when the packaging is right.
+ */
+export function checkCorePackaging() {
+ const pkgPath = path.join(ROOT, 'packages/core/package.json');
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
+ const needed = CORE_TARGET_REL.replace('packages/core/', '');
+ const files = pkg.files || [];
+ return files.includes(needed)
+ ? null
+ : `packages/core/package.json "files" must list "${needed}" so the generated copy ships in the tarball.`;
+}
+
+function main() {
+ const check = process.argv.includes('--check');
+ const expected = renderCoreCopy();
+
+ if (!check) {
+ fs.mkdirSync(path.dirname(CORE_TARGET), {recursive: true});
+ fs.writeFileSync(CORE_TARGET, expected);
+ process.stdout.write(`Wrote ${CORE_TARGET_REL}\n`);
+ return 0;
+ }
+
+ const actual = fs.existsSync(CORE_TARGET)
+ ? fs.readFileSync(CORE_TARGET, 'utf-8')
+ : null;
+
+ if (actual !== expected) {
+ process.stderr.write(
+ `\nSetup contract out of sync.\n` +
+ ` source: ${CLI_SOURCE_REL}\n` +
+ ` target: ${CORE_TARGET_REL}\n` +
+ (actual === null ? ' target is missing.\n' : ' target differs.\n') +
+ `Edit ONLY the source, then run: pnpm generate:setup-contract\n\n`,
+ );
+ return 1;
+ }
+
+ const packagingError = checkCorePackaging();
+ if (packagingError) {
+ process.stderr.write(`\n${packagingError}\n\n`);
+ return 1;
+ }
+
+ process.stdout.write('Setup contract in sync.\n');
+ return 0;
+}
+
+if (import.meta.url === pathToFileURL(process.argv[1] || '').href) {
+ process.exit(main());
+}