An open source design system that's fully customizable and agent ready
TypeScript
feat(cli): nudge to run init on any command until setup is done (#4153)
Joey9764a3da46ec
diff --git a/packages/cli/src/commands/agent-docs.mjs b/packages/cli/src/commands/agent-docs.mjsindex 5535efcc2e..36f5451151 100644--- a/packages/cli/src/commands/agent-docs.mjs+++ b/packages/cli/src/commands/agent-docs.mjs@@ -31,6 +31,9 @@ import {ERROR_CODES} from '../lib/error-codes.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 -->';@@ -45,20 +48,60 @@ const LEGACY_MARKER_END = '<!-- XDS:END -->';*/const AGENT_PRESETS = {claude: [CLAUDE_MD, CLAUDE_DIR_MD],- cursor: ['.cursorrules', AGENTS_MD],+ cursor: [CURSOR_RULES, AGENTS_MD],codex: [AGENTS_MD],- hermes: ['.hermes.md', 'HERMES.md', AGENTS_MD],+ hermes: [HERMES_DOT_MD, HERMES_MD, AGENTS_MD],};/**- * Find all existing agent doc files in a directory.- * Searches all known locations (AGENTS.md, CLAUDE.md, .claude/CLAUDE.md, .cursorrules).+ * 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) {- const allPaths = [AGENTS_MD, CLAUDE_MD, CLAUDE_DIR_MD, '.cursorrules'];- return allPaths.filter(p => fs.existsSync(path.join(targetDir, p)));+ 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;}/**diff --git a/packages/cli/src/commands/setup-nudge.test.mjs b/packages/cli/src/commands/setup-nudge.test.mjsnew file mode 100644index 0000000000..514f343cd7--- /dev/null+++ b/packages/cli/src/commands/setup-nudge.test.mjs@@ -0,0 +1,108 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Guardrail tests — the centralized setup check + enforcement layer 3.+ *+ * Unit: isAstryxInitialized() detects the Astryx marker across EVERY agent-doc+ * location (including the previously-missed Hermes files) and legacy XDS blocks.+ *+ * Integration: the CLI nudges (stderr) before a command when the project hasn't+ * run init — INCLUDING in --json mode (agents pass --json, and stderr never+ * corrupts the stdout JSON envelope). Quiet once set up, outside a project, and+ * for the installer command itself.+ */++import {describe, it, expect, beforeEach, afterEach} from 'vitest';+import {spawnSync} from 'node:child_process';+import * as fs from 'node:fs';+import * as path from 'node:path';+import * as os from 'node:os';+import {fileURLToPath} from 'node:url';+import {isAstryxInitialized} from './agent-docs.mjs';++const __dirname = path.dirname(fileURLToPath(import.meta.url));+const CLI = path.resolve(__dirname, '..', '..', 'bin', 'astryx.mjs');+const MARKER = '<!-- ASTRYX:START -->';+const NUDGE = /finish setup and install the Astryx agent prompt/;++let tmp;+beforeEach(() => {+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-setup-nudge-'));+});+afterEach(() => {+ fs.rmSync(tmp, {recursive: true, force: true});+});++function write(rel, body) {+ const p = path.join(tmp, rel);+ fs.mkdirSync(path.dirname(p), {recursive: true});+ fs.writeFileSync(p, body);+}++function run(args, cwd = tmp) {+ return spawnSync(process.execPath, [CLI, ...args], {+ cwd,+ encoding: 'utf8',+ timeout: 30_000,+ env: {...process.env, FORCE_COLOR: '0'},+ });+}++describe('isAstryxInitialized — centralized setup check (one place)', () => {+ it('is false in an empty project', () => {+ expect(isAstryxInitialized(tmp)).toBe(false);+ });++ // Covers EVERY location a preset can write — .hermes.md/HERMES.md were the gap.+ it.each(['AGENTS.md', 'CLAUDE.md', '.claude/CLAUDE.md', '.cursorrules', '.hermes.md', 'HERMES.md'])(+ 'detects the marker in %s',+ file => {+ write(file, `# doc\n${MARKER}\nbody`);+ expect(isAstryxInitialized(tmp)).toBe(true);+ },+ );++ it('detects the legacy XDS marker for back-compat', () => {+ write('AGENTS.md', '<!-- XDS:START -->');+ expect(isAstryxInitialized(tmp)).toBe(true);+ });++ it('is false when a doc file exists WITHOUT the marker', () => {+ write('AGENTS.md', 'project notes, no astryx block');+ expect(isAstryxInitialized(tmp)).toBe(false);+ });+});++describe('enforcement layer 3 — per-command setup nudge', () => {+ const asProject = () => write('package.json', '{"name":"t"}');++ it('nudges on stderr after a command when not set up', () => {+ asProject();+ const r = run(['docs', 'tokens']);+ expect(r.stderr).toMatch(NUDGE);+ });++ it('is suppressed in --json (machine mode stays clean), stdout valid JSON', () => {+ asProject();+ const r = run(['--json', 'docs', 'tokens']);+ // --json is machine output with a clean stdout+stderr contract; the human+ // nudge must NOT leak into it (json-shim: error envelopes have empty stderr).+ expect(r.stderr).not.toMatch(NUDGE);+ expect(() => JSON.parse(r.stdout)).not.toThrow();+ });++ it('is quiet once set up (marker present)', () => {+ asProject();+ write('AGENTS.md', MARKER);+ expect(run(['docs', 'tokens']).stderr).not.toMatch(NUDGE);+ });++ it('is quiet outside a project (no package.json)', () => {+ expect(run(['docs', 'tokens']).stderr).not.toMatch(NUDGE);+ });++ it('does not nudge for the installer command itself', () => {+ asProject();+ expect(run(['init']).stderr).not.toMatch(NUDGE);+ });+});diff --git a/packages/cli/src/index.mjs b/packages/cli/src/index.mjsindex 7b7d5a7e69..7349505a4d 100644--- a/packages/cli/src/index.mjs+++ b/packages/cli/src/index.mjs@@ -19,6 +19,7 @@ import {cliError} from './lib/cli-error.mjs';import {ERROR_CODES} from './lib/error-codes.mjs';import {levenshteinDistance} from './lib/string-utils.mjs';import {installJsonShim} from './lib/json-shim.mjs';+import {isAstryxInitialized} from './commands/agent-docs.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));@@ -237,6 +238,40 @@ program.hook('postAction', (thisCommand, actionCommand) => {}});+/**+ * 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.+ *+ * Uses `preAction` (not postAction) so it fires for EVERY valid command — even+ * ones whose action errors or calls process.exit (postAction is skipped then).+ *+ * Suppressed in --json: that is machine output with a strict clean stdout+stderr+ * contract (json-shim.test: "error envelopes have empty stderr"), and --json+ * 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).+ */+const SETUP_NUDGE_EXEMPT = new Set(['init', 'agent-docs']);+program.hook('preAction', (thisCommand, actionCommand) => {+ try {+ if (program.opts().json) return; // machine mode — keep --json output clean+ if (SETUP_NUDGE_EXEMPT.has(actionCommand.name())) return;+ const cwd = process.cwd();+ if (!fs.existsSync(path.join(cwd, 'package.json'))) return; // not a project+ if (isAstryxInitialized(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.+ console.error(+ `\nNext step: run \`${getCliInvocation(cwd)} init\` to finish setup and install the Astryx agent prompt.`,+ );+ } catch {+ // Never let the nudge break a command.+ }+});+/*** Command registry — each command is lazy-loaded so a broken command* doesn't take down the entire CLI.