An open source design system that's fully customizable and agent ready
TypeScript
fix(cli): the setup reminder, the swizzle StyleX note, and a doctor line say only what is true (#7262)
Joey2bb6c744737b
diff --git a/.changeset/cli-notes-say-what-is-true.md b/.changeset/cli-notes-say-what-is-true.mdnew file mode 100644index 0000000000..ddf7866823--- /dev/null+++ b/.changeset/cli-notes-say-what-is-true.md@@ -0,0 +1,13 @@+---+'@astryxdesign/cli': patch+'@astryxdesign/core': patch+---++[fix] The setup reminder, the swizzle StyleX note, and one doctor line say only what is true+@josephfarina++- The "run init to finish setup" reminder no longer prints where agents already have the Astryx prompt. In a git repository it looks for init's block in the agent docs from the project up to the repository root, because coding agents read every agent doc in between, so a package in a monorepo that ran `init` at its root stays quiet. This holds for every command and for the reminder printed when `@astryxdesign/core` or `@astryxdesign/cli` is installed. Running the CLI from its own source checkout, inside that checkout, prints no reminder. A project with no block in reach still gets it, and `--json` never prints it.+- `astryx swizzle` no longer says StyleX components "render unstyled (no error)" without a StyleX compiler. Importing them throws StyleX's "Unexpected 'stylex.create' call at runtime" error and the page does not render, and the note now says so.+- In an integration package, where the package's own manifest loads, `astryx doctor`'s implicit-integrations line no longer says that "every loaded integration is named in astryx.config". It names the package's own manifest: as the only loaded integration, or beside the integrations astryx.config names.++Classification: contract-restoring. Only message text changes: JSON keys, check ids, statuses, and exit codes are unchanged. The doctor line's new text also appears in its `--json` `message`.diff --git a/packages/cli/api/doctor/doctor.mjs b/packages/cli/api/doctor/doctor.mjsindex 599bb78b7d..a6630141b3 100644--- a/packages/cli/api/doctor/doctor.mjs+++ b/packages/cli/api/doctor/doctor.mjs@@ -351,6 +351,26 @@ export async function checkConfig(ctx) {}}+/**+ * Why no integration is implicitly linked, from what actually loaded. A+ * configured integration is named in astryx.config; the package's own manifest+ * loads as itself (`__local`). Only the first may be described as named in+ * astryx.config: a package with no config that loads its own manifest has no+ * config file to name it.+ *+ * @param {Array<{name?: string, __local?: boolean}>} integrations loaded, none+ * autolinked and none that failed to load+ * @returns {string}+ */+function describeNoImplicit(integrations) {+ const own = integrations.filter(integration => integration.__local);+ const configured = integrations.length - own.length;+ const ownNames = own.map(integration => integration.name ?? 'this package').join(', ');+ if (own.length === 0) return 'None — every loaded integration is named in astryx.config.';+ if (configured === 0) return `None — the only loaded integration is this package's own manifest (${ownNames}).`;+ return `None — every loaded integration is named in astryx.config or is this package's own manifest (${ownNames}).`;+}+/*** Check 6 — integrations that are loaded without an astryx.config entry.*@@ -395,14 +415,18 @@ export function checkImplicitIntegrations(ctx) {const unreadable = describeUnreadableManifests(ctx.autolinkFailures ?? []);if (implicit.length === 0) {+ // A record that carries `__loadError` (the package's own manifest, or a+ // configured one, that failed to load) loaded nothing, so it is not named+ // as loaded beside the line reporting that it could not be loaded.+ const loaded = ctx.integrations.filter(integration => !integration.__loadError);return {id,label,status: 'info',message:- (ctx.integrations.length > 0- ? 'None — every loaded integration is named in astryx.config.'- : unreadable+ (loaded.length > 0+ ? describeNoImplicit(loaded)+ : ctx.integrations.length > 0 || unreadable? 'None loaded.': 'None — no installed dependency ships an astryx.integration.* manifest.') +unreadable,diff --git a/packages/cli/api/doctor/doctor.test.mjs b/packages/cli/api/doctor/doctor.test.mjsindex ef63acb3b0..0747109577 100644--- a/packages/cli/api/doctor/doctor.test.mjs+++ b/packages/cli/api/doctor/doctor.test.mjs@@ -353,6 +353,49 @@ describe('checkImplicitIntegrations', () => {expect(c.message).toContain('named in astryx.config');});+ // A package with no astryx.config that loads its own manifest: there is no+ // config file, so the message must not say anything is named in one.+ it("names the package's own manifest instead of a config that does not exist", () => {+ const c = checkImplicitIntegrations({+ integrations: [autolinked({__autolinked: false, __local: true, name: '@acme/kit'})],+ });+ expect(c.status).toBe('info');+ expect(c.message).toBe(+ "None — the only loaded integration is this package's own manifest (@acme/kit).",+ );+ expect(c.message).not.toContain('astryx.config');+ });++ // An own manifest that failed to load keeps a `__local` record carrying+ // `__loadError`; it loaded nothing, so it is never named as loaded.+ it("does not name the package's own manifest as loaded when it failed to load", () => {+ const failed = autolinked({+ __autolinked: false,+ __local: true,+ name: '@acme/kit',+ __loadError: 'astryx.integration.mjs threw: boom',+ });+ const alone = checkImplicitIntegrations({integrations: [failed]});+ expect(alone.status).toBe('info');+ expect(alone.message).toBe('None loaded.');+ const beside = checkImplicitIntegrations({+ integrations: [autolinked({__autolinked: false}), failed],+ });+ expect(beside.message).toBe('None — every loaded integration is named in astryx.config.');+ });++ it('names both when configured integrations load beside the own manifest', () => {+ const c = checkImplicitIntegrations({+ integrations: [+ autolinked({__autolinked: false}),+ autolinked({__autolinked: false, __local: true, name: '@acme/kit'}),+ ],+ });+ expect(c.message).toBe(+ "None — every loaded integration is named in astryx.config or is this package's own manifest (@acme/kit).",+ );+ });+it('names the package, the field, and what it contributes', () => {// Roots count only when they exist, so this one gives them real folders.const root = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-implicit-'));diff --git a/packages/cli/clients/cli/commands/cli-postinstall.test.mjs b/packages/cli/clients/cli/commands/cli-postinstall.test.mjsindex 75d2f8b369..1b80a9e9a0 100644--- a/packages/cli/clients/cli/commands/cli-postinstall.test.mjs+++ b/packages/cli/clients/cli/commands/cli-postinstall.test.mjs@@ -8,9 +8,16 @@* transient fetch (path _npx or npm_command=exec), and once set up.*/-import {describe, it, expect} from 'vitest';+import {describe, it, expect, beforeEach, afterEach} from 'vitest';+import {spawnSync} from 'node:child_process';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {fileURLToPath} from 'node:url';import {shouldNudge} from '../../../scripts/postinstall.mjs';+const CLI = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../..');+const DEP = '/proj/node_modules/@astryxdesign/cli/scripts/postinstall.mjs'; // real dep installconst NPX = '/Users/x/.npm/_npx/a1b2/node_modules/@astryxdesign/cli/scripts/postinstall.mjs';const REPO = '/repo/packages/cli/scripts/postinstall.mjs'; // monorepo/source@@ -40,3 +47,44 @@ describe('cli postinstall — shouldNudge', () => {expect(shouldNudge({})).toBe(false);});});++// Install time, end to end: the real script and the leaf it loads, installed+// under a monorepo's node_modules, run the way npm runs them for a package.+describe('cli postinstall — inside a monorepo package', () => {+ let repo;+ beforeEach(() => {+ repo = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-cli-postinstall-'));+ fs.mkdirSync(path.join(repo, '.git'));+ fs.mkdirSync(path.join(repo, 'packages/app'), {recursive: true});+ fs.writeFileSync(path.join(repo, 'packages/app/package.json'), '{"name":"app"}');+ const installed = path.join(repo, 'node_modules/@astryxdesign/cli');+ for (const rel of ['scripts/postinstall.mjs', 'foundation/agent-docs/agent-doc-state.mjs']) {+ fs.mkdirSync(path.dirname(path.join(installed, rel)), {recursive: true});+ fs.copyFileSync(path.join(CLI, rel), path.join(installed, rel));+ }+ });+ afterEach(() => fs.rmSync(repo, {recursive: true, force: true}));++ const install = () =>+ spawnSync(+ process.execPath,+ [path.join(repo, 'node_modules/@astryxdesign/cli/scripts/postinstall.mjs')],+ {+ env: {...process.env, INIT_CWD: path.join(repo, 'packages/app'), npm_command: 'install'},+ encoding: 'utf8',+ },+ );++ it('stays quiet when init ran at the repository root', () => {+ fs.writeFileSync(path.join(repo, 'AGENTS.md'), '<!-- ASTRYX:START -->\n');+ const r = install();+ expect(r.status).toBe(0);+ expect(r.stdout).toBe('');+ });++ it('still nudges when no folder up to the repository root ran init', () => {+ const r = install();+ expect(r.status).toBe(0);+ expect(r.stdout).toMatch(/finish setup and install the Astryx agent prompt/);+ });+});diff --git a/packages/cli/clients/cli/commands/setup-nudge.test.mjs b/packages/cli/clients/cli/commands/setup-nudge.test.mjsindex 29b9f86862..1ed509022c 100644--- a/packages/cli/clients/cli/commands/setup-nudge.test.mjs+++ b/packages/cli/clients/cli/commands/setup-nudge.test.mjs@@ -16,9 +16,24 @@ import {describe, it, expect, beforeEach, afterEach} from 'vitest';import * as fs from 'node:fs';import * as path from 'node:path';import * as os from 'node:os';-import {isAstryxInitialized} from '../../../foundation/agent-docs/agent-docs.mjs';+import {fileURLToPath} from 'node:url';+import {+ isAstryxInitialized,+ isAstryxPromptInReach,+} from '../../../foundation/agent-docs/agent-docs.mjs';import {runCli} from '../../../test-utils/run-cli.mjs';+/** This source checkout: the tests run the CLI from it. */+const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../../..');++/** Is `dir` inside a git repository? The temp folder normally is not. */+function insideRepository(dir) {+ for (let d = path.resolve(dir); ; d = path.dirname(d)) {+ if (fs.existsSync(path.join(d, '.git'))) return true;+ if (path.dirname(d) === d) return false;+ }+}+const MARKER = '<!-- ASTRYX:START -->';const NUDGE = /finish setup and install the Astryx agent prompt/;@@ -61,6 +76,41 @@ describe('isAstryxInitialized — centralized setup check (one place)', () => {});});+// Agents read the agent docs between the repository root and the folder they+// work in, so a monorepo initialized at its root is set up in every package.+describe('isAstryxPromptInReach — up to the repository root', () => {+ it('finds init\'s block at the repository root from a workspace package', () => {+ fs.mkdirSync(path.join(tmp, '.git'));+ write('AGENTS.md', MARKER);+ write('packages/app/package.json', '{"name":"app"}');+ expect(isAstryxPromptInReach(path.join(tmp, 'packages/app'))).toBe(true);+ });++ it('treats a worktree .git file as the repository root', () => {+ write('.git', 'gitdir: /elsewhere\n');+ write('CLAUDE.md', MARKER);+ write('packages/app/package.json', '{"name":"app"}');+ expect(isAstryxPromptInReach(path.join(tmp, 'packages/app'))).toBe(true);+ });++ it('does not look above the repository root', () => {+ write('AGENTS.md', MARKER);+ fs.mkdirSync(path.join(tmp, 'repo/.git'), {recursive: true});+ write('repo/pkg/package.json', '{"name":"pkg"}');+ expect(isAstryxPromptInReach(path.join(tmp, 'repo/pkg'))).toBe(false);+ });++ it.skipIf(insideRepository(os.tmpdir()))(+ 'checks only the folder itself outside a repository',+ () => {+ write('AGENTS.md', MARKER);+ write('pkg/package.json', '{"name":"pkg"}');+ expect(isAstryxPromptInReach(tmp)).toBe(true);+ expect(isAstryxPromptInReach(path.join(tmp, 'pkg'))).toBe(false);+ },+ );+});+describe('enforcement layer 3 — per-command setup nudge', () => {const asProject = () => write('package.json', '{"name":"t"}');@@ -99,4 +149,32 @@ describe('enforcement layer 3 — per-command setup nudge', () => {asProject();expect((await runCli(['init'], tmp)).stderr).not.toMatch(NUDGE);});++ it('is quiet in a workspace package when init\'s block is at the repository root', async () => {+ fs.mkdirSync(path.join(tmp, '.git'));+ write('AGENTS.md', MARKER);+ write('packages/app/package.json', '{"name":"app"}');+ const r = await runCli(['docs', 'tokens'], path.join(tmp, 'packages/app'));+ expect(r.stderr).not.toMatch(NUDGE);+ });++ it('still nudges in a workspace package with no block up to the repository root', async () => {+ fs.mkdirSync(path.join(tmp, '.git'));+ write('AGENTS.md', 'project notes, no astryx block');+ write('packages/app/package.json', '{"name":"app"}');+ const r = await runCli(['docs', 'tokens'], path.join(tmp, 'packages/app'));+ expect(r.stderr).toMatch(NUDGE);+ });++ // The tests run the CLI from this checkout, so a project inside it is the+ // contributor flow. The same project in the temp folder nudges (above).+ it('is quiet inside the source checkout the CLI runs from', async () => {+ const inside = fs.mkdtempSync(path.join(REPO, '.astryx-setup-nudge-'));+ try {+ fs.writeFileSync(path.join(inside, 'package.json'), '{"name":"t"}');+ expect((await runCli(['docs', 'tokens'], inside)).stderr).not.toMatch(NUDGE);+ } finally {+ fs.rmSync(inside, {recursive: true, force: true});+ }+ });});diff --git a/packages/cli/clients/cli/commands/swizzle.mjs b/packages/cli/clients/cli/commands/swizzle.mjsindex c83b4ae945..0cd19c0bf1 100644--- a/packages/cli/clients/cli/commands/swizzle.mjs+++ b/packages/cli/clients/cli/commands/swizzle.mjs@@ -91,14 +91,16 @@ export function registerSwizzle(program) {),];- // StyleX build requirement — swizzled StyleX source renders unstyled with- // no error unless the consumer's build runs a StyleX compiler.+ // StyleX build requirement — swizzled StyleX source throws on import+ // ("Unexpected 'stylex.create' call at runtime") unless the consumer's+ // build runs a StyleX compiler, so the page does not render at all.if (usesStyleX) {out.push(text([`${WARN} These components use StyleX and require a StyleX compiler in your build.`,- ' Without one they render unstyled (no error). See setup per framework:',+ ` Without one, importing them throws "Unexpected 'stylex.create' call at runtime"`,+ ' and the page does not render. See setup per framework:',` ${run} docs styling`,' Next.js note: the StyleX Babel plugin disables SWC and breaks next/font -',' use an SWC-based StyleX transform instead (covered in the guide).',diff --git a/packages/cli/clients/cli/commands/swizzle.routing.test.mjs b/packages/cli/clients/cli/commands/swizzle.routing.test.mjsindex ec246be890..8b267f37e4 100644--- a/packages/cli/clients/cli/commands/swizzle.routing.test.mjs+++ b/packages/cli/clients/cli/commands/swizzle.routing.test.mjs@@ -15,8 +15,16 @@ import {describe, it, expect, beforeEach, afterEach} from 'vitest';import * as fs from 'node:fs';import * as path from 'node:path';import * as os from 'node:os';+import {createRequire} from 'node:module';+import {fileURLToPath} from 'node:url';import {runCli} from '../../../test-utils/run-cli.mjs';+/** The StyleX runtime that Core ships with, resolved the way Core resolves it. */+const CORE_PACKAGE = path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ '../../../../core/package.json',+);+/*** Build a fake @astryxdesign/core under <project>/node_modules with a single* swizzleable Button component (bare `Button.tsx`, no doc).@@ -303,12 +311,21 @@ describe('swizzle — StyleX build setup note (#3373)', () => {const humanResult = await runCli(['swizzle', 'Styled', '-f'], project);expect(humanResult.code).toBe(0);expect(humanResult.stdout).toMatch(/StyleX compiler/i);- expect(humanResult.stdout).toMatch(/unstyled/i);+ expect(humanResult.stdout).toMatch(/importing them throws "Unexpected 'stylex\.create' call at runtime"/);+ expect(humanResult.stdout).not.toMatch(/unstyled/i);expect(humanResult.stdout).toMatch(/next\/font/i);// The fixture has no `astryx` bin installed, so the note names the scoped package.expect(humanResult.stdout).toMatch(/@astryxdesign\/cli docs styling/);});+ // The note quotes what StyleX does without a compiler; this keeps it true.+ it('matches what the StyleX runtime does when styles are not compiled', () => {+ const stylex = createRequire(CORE_PACKAGE)('@stylexjs/stylex');+ expect(() => stylex.create({root: {color: 'red'}})).toThrow(+ /Unexpected 'stylex\.create' call at runtime/,+ );+ });+it('does not print the StyleX note for components without StyleX', async () => {buildStyleXCore(project);writeProjectPackageJson(project);diff --git a/packages/cli/clients/cli/index.mjs b/packages/cli/clients/cli/index.mjsindex 5058391a34..579b27fcc3 100644--- a/packages/cli/clients/cli/index.mjs+++ b/packages/cli/clients/cli/index.mjs@@ -26,7 +26,8 @@ import {levenshteinDistance} from '../../foundation/text/string-utils.mjs';import {installJsonShim} from './lib/json-shim.mjs';import {addDocHelp, markReportsResult} from './lib/define-command.mjs';import {doc as manifestDoc} from './commands/manifest.doc.mjs';-import {isAstryxInitialized} from '../../foundation/agent-docs/agent-docs.mjs';+import {isAstryxInitialized, isAstryxPromptInReach} from '../../foundation/agent-docs/agent-docs.mjs';+import {CLI_ROOT} from '../../foundation/fs/paths.mjs';import * as debug from '../../foundation/debug/index.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));@@ -277,6 +278,26 @@ const commands = [];const SETUP_NUDGE_EXEMPT = new Set(['init', 'agent-docs']);++/**+ * Is `cwd` inside the CLI's own source checkout while the CLI runs from it?+ * An installed CLI always lives under `node_modules`; a CLI running from source+ * does not, and its checkout is the pnpm workspace that holds it. Developing+ * Astryx is not an app to set up, so the setup nudge stays quiet there.+ * @param {string} cwd+ * @returns {boolean}+ */+function inOwnSourceCheckout(cwd) {+ if (CLI_ROOT.split(path.sep).includes('node_modules')) return false;+ let checkout = CLI_ROOT;+ while (!fs.existsSync(path.join(checkout, 'pnpm-workspace.yaml'))) {+ const parent = path.dirname(checkout);+ if (parent === checkout) return false;+ checkout = parent;+ }+ const rel = path.relative(checkout, path.resolve(cwd));+ return rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel);+}/** An integration package's manifest: the package is not an app to set up. */const INTEGRATION_MANIFEST_FILES = ['astryx.integration.ts',@@ -528,8 +549,9 @@ export async function createProgram() {/*** Enforcement layer 3 — setup nudge. If this project hasn't run `astryx init`- * yet (no Astryx marker in any agent-doc file — see isAstryxInitialized), remind- * the user/agent that setup is missing.+ * yet (no Astryx marker in any agent-doc file between the project and its+ * repository root — see isAstryxPromptInReach), remind the user/agent that+ * setup is missing.** Uses `preAction` (not postAction) so it fires for EVERY valid command — even* ones whose action errors or calls process.exit (postAction is skipped then).@@ -539,7 +561,8 @@ export async function createProgram() {* consumers parse stdout, not stderr — a stderr nudge would not reach them anyway.* The core/cli postinstall layers already nudge at install time regardless of* --json; a machine-readable nudge could later be an envelope field. Also skipped- * for the installer commands themselves and outside a project (no package.json).+ * for the installer commands themselves, outside a project (no package.json),+ * and inside the CLI's own source checkout when it runs from there.*/program.hook('preAction', (thisCommand, actionCommand) => {try {@@ -549,7 +572,8 @@ export async function createProgram() {if (!fs.existsSync(path.join(cwd, 'package.json'))) return; // not a project// An integration package is not an app: `init` is not its next step.if (INTEGRATION_MANIFEST_FILES.some(file => fs.existsSync(path.join(cwd, file)))) return;- if (isAstryxInitialized(cwd)) return; // already set up — stay quiet+ if (inOwnSourceCheckout(cwd)) return; // developing Astryx itself, not an app+ if (isAstryxPromptInReach(cwd)) return; // already set up — stay quiet// Same wording as the core/cli postinstall nudges. #4151's getCliInvocation()// renders the correct form for THIS project — scoped `npx @astryxdesign/cli`// one-off, or `<pm> astryx` when installed — never the bare `npx astryx` footgun.diff --git a/packages/cli/foundation/agent-docs/agent-doc-state.mjs b/packages/cli/foundation/agent-docs/agent-doc-state.mjsindex 5d1c178541..476fc8c690 100644--- a/packages/cli/foundation/agent-docs/agent-doc-state.mjs+++ b/packages/cli/foundation/agent-docs/agent-doc-state.mjs@@ -96,6 +96,44 @@ export function isAstryxInitialized(targetDir = process.cwd()) {return false;}+/**+ * Does an agent working in `startDir` already have the Astryx prompt in reach?+ *+ * Coding agents read the agent docs between the repository root and the folder+ * they work in. So inside a git repository, init's block in any folder from+ * `startDir` up to the repository root counts: a workspace package of a+ * monorepo initialized at its root is set up. Outside a repository only+ * `startDir` itself is checked, as {@link isAstryxInitialized} does. Both the+ * per-command nudge and the postinstall nudges ask this.+ *+ * @param {string} [startDir=process.cwd()]+ * @returns {boolean}+ */+export function isAstryxPromptInReach(startDir = process.cwd()) {+ const start = path.resolve(startDir);+ const repositoryRoot = findRepositoryRoot(start);+ if (!repositoryRoot) return isAstryxInitialized(start);+ for (let dir = start; ; dir = path.dirname(dir)) {+ if (isAstryxInitialized(dir)) return true;+ if (dir === repositoryRoot) return false;+ }+}++/**+ * The nearest folder at or above `start` that holds `.git` (a folder, or the+ * file a worktree uses), or null outside a repository.+ * @param {string} start+ * @returns {string | null}+ */+function findRepositoryRoot(start) {+ for (let dir = start; ; ) {+ if (fs.existsSync(path.join(dir, '.git'))) return dir;+ const parent = path.dirname(dir);+ if (parent === dir) return null;+ dir = parent;+ }+}+/*** The one-line next-step both postinstall nudges print. Kept here so layer 1* (core) and layer 2 (cli) can never word it differently.diff --git a/packages/cli/foundation/agent-docs/agent-docs.mjs b/packages/cli/foundation/agent-docs/agent-docs.mjsindex 52a889fcb7..fb657cefb9 100644--- a/packages/cli/foundation/agent-docs/agent-docs.mjs+++ b/packages/cli/foundation/agent-docs/agent-docs.mjs@@ -42,15 +42,17 @@ import {LEGACY_MARKER_END,discoverAgentDocs,isAstryxInitialized,+ isAstryxPromptInReach,} 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};+// (discoverAgentDocs, isAstryxInitialized, isAstryxPromptInReach) 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, isAstryxPromptInReach};const MAX_PROJECT_AGENT_DOC_LINES = 32;const MANAGED_MARKER_TEXT = /(?:ASTRYX|XDS):(START|END)/u;diff --git a/packages/cli/scripts/postinstall.mjs b/packages/cli/scripts/postinstall.mjsindex 3ce12fd235..c5eca8b1a9 100644--- a/packages/cli/scripts/postinstall.mjs+++ b/packages/cli/scripts/postinstall.mjs@@ -7,7 +7,7 @@* 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 the dependency-free leaf+ * Reuses the ONE setup check (isAstryxPromptInReach) 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@@ -41,10 +41,10 @@ async function projectIsSetUp(root) {// 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(+ const {isAstryxPromptInReach} = await import('../foundation/agent-docs/agent-doc-state.mjs');- return isAstryxInitialized(root);+ return isAstryxPromptInReach(root);} catch {return false; // best-effort — if the check can't load, fall through and nudge}diff --git a/packages/core/scripts/agent-doc-state.mjs b/packages/core/scripts/agent-doc-state.mjsindex 0e0682fa92..4290ab5cdb 100644--- a/packages/core/scripts/agent-doc-state.mjs+++ b/packages/core/scripts/agent-doc-state.mjs@@ -106,6 +106,44 @@ export function isAstryxInitialized(targetDir = process.cwd()) {return false;}+/**+ * Does an agent working in `startDir` already have the Astryx prompt in reach?+ *+ * Coding agents read the agent docs between the repository root and the folder+ * they work in. So inside a git repository, init's block in any folder from+ * `startDir` up to the repository root counts: a workspace package of a+ * monorepo initialized at its root is set up. Outside a repository only+ * `startDir` itself is checked, as {@link isAstryxInitialized} does. Both the+ * per-command nudge and the postinstall nudges ask this.+ *+ * @param {string} [startDir=process.cwd()]+ * @returns {boolean}+ */+export function isAstryxPromptInReach(startDir = process.cwd()) {+ const start = path.resolve(startDir);+ const repositoryRoot = findRepositoryRoot(start);+ if (!repositoryRoot) return isAstryxInitialized(start);+ for (let dir = start; ; dir = path.dirname(dir)) {+ if (isAstryxInitialized(dir)) return true;+ if (dir === repositoryRoot) return false;+ }+}++/**+ * The nearest folder at or above `start` that holds `.git` (a folder, or the+ * file a worktree uses), or null outside a repository.+ * @param {string} start+ * @returns {string | null}+ */+function findRepositoryRoot(start) {+ for (let dir = start; ; ) {+ if (fs.existsSync(path.join(dir, '.git'))) return dir;+ const parent = path.dirname(dir);+ if (parent === dir) return null;+ dir = parent;+ }+}+/*** The one-line next-step both postinstall nudges print. Kept here so layer 1* (core) and layer 2 (cli) can never word it differently.diff --git a/packages/core/scripts/postinstall.mjs b/packages/core/scripts/postinstall.mjsindex c913e23671..f3a98496f6 100644--- a/packages/core/scripts/postinstall.mjs+++ b/packages/core/scripts/postinstall.mjs@@ -45,7 +45,7 @@ async function main() {contract.shouldNudge({scriptPath: HERE,npmCommand: process.env.npm_command,- isSetUp: contract.isAstryxInitialized(root),+ isSetUp: contract.isAstryxPromptInReach(root),})) {process.stdout.write(contract.SETUP_NUDGE);diff --git a/packages/core/src/postinstall.test.mjs b/packages/core/src/postinstall.test.mjsindex 536468ae34..657dff5ccf 100644--- a/packages/core/src/postinstall.test.mjs+++ b/packages/core/src/postinstall.test.mjs@@ -11,12 +11,15 @@*/import {describe, it, expect, beforeEach, afterEach} from 'vitest';+import {spawnSync} from 'node:child_process';import * as fs from 'node:fs';import * as os from 'node:os';import * as path from 'node:path';+import {fileURLToPath} from 'node:url';// Core's own package-local contract copy — what actually runs at install time.import {isAstryxInitialized,+ isAstryxPromptInReach,shouldNudge,AGENT_DOC_PATHS,INIT_MARKERS,@@ -98,6 +101,49 @@ describe('core postinstall — one authoritative source, no drift', () => {write('AGENTS.md', `# doc\n${MARKER}\nbody`);expect(isAstryxInitialized(tmp)).toBe(cliLeaf.isAstryxInitialized(tmp));});++ it('agrees with the CLI leaf on a monorepo package', () => {+ fs.mkdirSync(path.join(tmp, '.git'));+ write('AGENTS.md', MARKER);+ write('packages/app/package.json', '{"name":"app"}');+ const app = path.join(tmp, 'packages/app');+ expect(isAstryxPromptInReach(app)).toBe(true);+ expect(isAstryxPromptInReach(app)).toBe(cliLeaf.isAstryxPromptInReach(app));+ });+});++// Install time, end to end: core's real script and its contract copy, installed+// under a monorepo's node_modules, run the way npm runs them for a package.+describe('core postinstall — inside a monorepo package', () => {+ const CORE = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+ const install = () => {+ const installed = path.join(tmp, 'node_modules/@astryxdesign/core/scripts');+ fs.mkdirSync(installed, {recursive: true});+ for (const file of ['postinstall.mjs', 'agent-doc-state.mjs']) {+ fs.copyFileSync(path.join(CORE, 'scripts', file), path.join(installed, file));+ }+ return spawnSync(process.execPath, [path.join(installed, 'postinstall.mjs')], {+ env: {...process.env, INIT_CWD: path.join(tmp, 'packages/app'), npm_command: 'install'},+ encoding: 'utf8',+ });+ };+ beforeEach(() => {+ fs.mkdirSync(path.join(tmp, '.git'));+ write('packages/app/package.json', '{"name":"app"}');+ });++ it('stays quiet when init ran at the repository root', () => {+ write('AGENTS.md', MARKER);+ const r = install();+ expect(r.status).toBe(0);+ expect(r.stdout).toBe('');+ });++ it('still nudges when no folder up to the repository root ran init', () => {+ const r = install();+ expect(r.status).toBe(0);+ expect(r.stdout).toMatch(/finish setup and install the Astryx agent prompt/);+ });});describe('core postinstall — shouldNudge', () => {