An open source design system that's fully customizable and agent ready
TypeScript
feat(cli): install once, run anywhere — every copy hands a project's run to the release its Core matches (#7649)
Joeya44ebd55ab45
diff --git a/.changeset/cli-computer-agent-text.md b/.changeset/cli-computer-agent-text.mdnew file mode 100644index 0000000000..84d6892883--- /dev/null+++ b/.changeset/cli-computer-agent-text.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[feat] The CLI installed for the computer keeps one short Astryx skill for every agent on the computer: `~/.agents/skills/astryx/SKILL.md`, which most coding agents read, linked into the skill folder of each agent that reads only its own (`~/.claude/skills` always; Kiro, Windsurf, Letta, Xcode's coding assistant, and `~/.config/agents/skills` when that folder exists) with a folder link and a relative target, a junction on Windows, or a copy where no link can be made. Continue, whose scanner skips links, gets a managed copy. The text tells agents that Astryx is on the computer, when it is relevant (building or changing UI), to start with `astryx search`, and to read docs with `astryx docs`; it names no version and only commands every release keeps. It is written on the global copy's first run and after each upgrade, in the background; package install scripts never write it. `astryx init --user` writes it now, in any folder, and `astryx init --user --remove-agents` removes the file, every link Astryx made, and the copy, and turns it off. The setting and the links Astryx made are kept in `astryx/settings.json` in the per-user configuration folder. The file records a hash of its text, so a file a person edited is never overwritten or removed, and nothing Astryx did not create at a link folder is replaced. `init --user` warns, while still writing, when no `astryx` command on the computer runs the Astryx CLI, and its `init.user` receipt lists each path and what happened to it. Outside a project, `astryx doctor` adds a `computer-agent-text` check (info only) that says whether the text is present, current, edited, or turned off, where it is linked, and any link folder it skipped or whose skill folder is missing. A cache or configuration folder set through `XDG_CACHE_HOME`, `XDG_CONFIG_HOME`, `LOCALAPPDATA`, or `APPDATA` is used only when it is an absolute path.++@josephfarinadiff --git a/.changeset/cli-computer-integrations.md b/.changeset/cli-computer-integrations.mdnew file mode 100644index 0000000000..569fa4a478--- /dev/null+++ b/.changeset/cli-computer-integrations.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[feat] Integrations installed for the computer. An integration package installed in the same place as the CLI installed for the computer (`npm i -g`, `pnpm add -g`, `yarn global add`, or `bun add -g` beside `@astryxdesign/cli`), or installed with the CLI in one package set by a tool that runs it, is a computer-level integration. Outside a project, it loads the way a project's integrations do: its components, templates, docs, themes, discover source, and `cliCommand` apply, with the same validation, and one whose `@astryxdesign/core` or `@astryxdesign/cli` peer range excludes the CLI's release is skipped. pnpm 11 and later, which give each global package a folder of its own, count every one of those folders. Inside a project, only the project's own integrations load: a computer-level one adds nothing there, and `astryx discover` lists it under `meta.available` with source `installed for this computer` and the project's install command in `install`, when its peer range admits the project's release and it loads. A project that installs the same integration uses only its own copy. `astryx doctor` adds a `computer-integrations` check: outside a project, each one it uses, each the folder replaces with its own copy, and a warning for each it skips or cannot load; inside one, the ones the project could add.++@josephfarinadiff --git a/.changeset/cli-global-docs.md b/.changeset/cli-global-docs.mdnew file mode 100644index 0000000000..92eb138cdf--- /dev/null+++ b/.changeset/cli-global-docs.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[docs] Global mode docs: `astryx docs global` is a top-level docs section (and one docsite page, under Guide, which Getting Started introduces and links) explaining what global mode is, the one install command, what you get, and which version runs where. Its pages, each answering one question: project, global, or both (both is recommended; `global/project-global-or-both`), install (`global/install-once`, with what to do about `EACCES`), which version runs and why (`global/who-answers`), updates and notices (`global/updates`), the agent guide on your computer (`global/computer-agent-guide`), integrations installed globally (`global/computer-integrations`), monorepos and nested folders (`global/monorepos`), CI and containers (`global/ci-and-containers`), troubleshooting every line global mode prints (`global/problems`), uninstall and reset (`global/uninstall`), and a reference of paths, environment variables, JSON fields, and error codes (`global/reference`). `astryx docs global` and its pages are answered by the copy you start, even inside a project whose version predates them. Integration authors get a checklist with the commands to try a package globally (`cli/integrations/global-integrations`). Every command that does something else outside a project says exactly what in its "In global mode" note, checked against the command run in an empty folder, and every terminal line the global-mode pages show is checked against the CLI's own strings. A project's update notice now installs the CLI beside Core, so a project that installed only Core gets its own CLI too.++@josephfarinadiff --git a/.changeset/cli-global-local-fixes.md b/.changeset/cli-global-local-fixes.mdnew file mode 100644index 0000000000..5aa7da3848--- /dev/null+++ b/.changeset/cli-global-local-fixes.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[fix] Global and project copies of the CLI meet more predictably. A repository that builds the CLI itself, with `packages/cli` beside `packages/core`, answers with that CLI instead of failing with `ERR_VERSIONS_UNAVAILABLE`. On a cache folder shared between computers, a release install renews its lock every 10 seconds, and a lock from another computer that goes a minute without renewal is taken over, instead of blocking runs for 20 minutes. Folder names are compared without letter case on macOS and Windows, a Yarn 1 global install on Windows is recognized as a global install, and the shims npm, pnpm (including pnpm 12's), and PowerShell write are read when doctor and the reminders look for the `astryx` commands on the search path.++@josephfarinadiff --git a/.changeset/cli-global-mode.md b/.changeset/cli-global-mode.mdnew file mode 100644index 0000000000..55e773403f--- /dev/null+++ b/.changeset/cli-global-mode.md@@ -0,0 +1,9 @@+---+'@astryxdesign/cli': patch+---++[feat] Install the CLI once for your computer (`npm i -g @astryxdesign/cli`) and run `astryx` in any folder. In a project, the project's own CLI answers, whatever its version, as before: a copy started anywhere else (the global install, `npx`, a typed version) hands the run to it. A project with no CLI of its own (only `@astryxdesign/core`, or a fresh clone) is answered by the copy you started, as before; when that copy is not the Core's release, one hint after the command, at most once a day per project, names the command that adds the CLI at Core's version, and JSON reports `meta.answeredBy.copy: "starting"`. Only a project whose own CLI cannot start is answered by the CLI release equal to its Core, installed once into a per-user cache (from the installed Core, else the lockfile, else the declared range). `astryx doctor` warns when a project's CLI and Core are different releases, or when a project has no CLI and the copy that answered differs from its Core, and prints the command that aligns them. `astryx --help` and the manifest's new `globalMode` field point to `astryx docs global`. The hand-off keeps the arguments, folder, standard streams, and exit status. Outside a project, the copy installed for your computer answers with its own release; commands that read Core use the Core of that release there: the global copy downloads it into the cache in a background step it starts as a run ends (never in CI, and not on Windows, where a background process would hold the caller's pipes and the first component command downloads it instead), so component reads work offline after one online run. Nothing that worked before breaks: when that release cannot be obtained (offline, a registry without it, an unwritable cache), the copy you started answers, as before global mode, with one warning line on standard error (`astryx: could not get Astryx <version> to match this project's Core (<reason>); answering with CLI <version> instead`) and `meta.answeredBy.copy: "fallback"` in JSON. A copy counts as installed for the computer only in npm's global folder or in a global folder a package manager's own settings name (Bun's `BUN_INSTALL` or `globalDir`, Yarn's `global-folder`, pnpm's `PNPM_HOME` or `global-dir`, or their defaults), never by a folder's layout alone, so an app made with `yarn add` is never mistaken for one; a moved Bun or Yarn global folder counts, and its notice reinstalls there. A failed install is remembered in the cache, so offline runs do not start npm again each time: it is retried after 2 minutes, then after 10 once it fails again, and a success forgets it. A stale install lock ends the process it records only when that process is exactly this CLI's install of that release (npm, or node running npm-cli.js, installing `@astryxdesign/cli@<version>`, started after the lock); otherwise the lock is simply taken over. The new `ERR_VERSIONS_UNAVAILABLE` is kept for runs nothing can answer, such as a command that needs Core outside a project that cannot install it. The CLI starts npm from npm's own entry file with the running Node, never through a shell, and reads a project's declared Core range only when it is a plain version range.++Every successful `--json` result now carries `meta.answeredBy` (`cli`, `core`, `copy`: `project`, `starting`, `matched`, `carried`, or `fallback`), typed in `CLIResponse` and described in the output envelope docs. In text mode, a run answered by anything other than the project's own CLI prints one `astryx: answered by …` line on standard error. Printed commands start with a name that reaches the same release: the project's runner when its own CLI answers, `astryx` outside a project for the copy installed for the computer, and otherwise the CLI package pinned to the answering version (`npx @astryxdesign/[email protected]`). The new `ERR_PROJECT_REQUIRED` code names a command that needs a project. See `astryx docs global/install-once`.++@josephfarinadiff --git a/.changeset/cli-integration-command-name.md b/.changeset/cli-integration-command-name.mdnew file mode 100644index 0000000000..1f35a4b6b5--- /dev/null+++ b/.changeset/cli-integration-command-name.md@@ -0,0 +1,10 @@+---+'@astryxdesign/cli': patch+'@astryxdesign/core': patch+---++[feat] An integration can set the command its users run the CLI with: a new `cliCommand` field in `astryx.integration.*`, such as `cliCommand: 'acme astryx'`. In a project that loads that integration, every command the CLI prints starts with it instead of the package-manager prefix (`npx astryx`, `pnpm exec astryx`): next-step hints, errors, suggestions, Doctor fixes, `--help`, the setup reminder, the agent-docs block, and doc text. If two loaded integrations set different commands, neither is used, and the new `cli-command` check in `astryx doctor` warns. An invalid `cliCommand` is ignored with an `invalid_cli_command` warning; the rest of the manifest still loads.++Docs, including an integration's, are now written with bare `astryx ...` commands, and `astryx docs` prefixes them for the project when it prints them. JSON output keeps every command bare, as before. The install-time setup reminder from `@astryxdesign/core` and `@astryxdesign/cli` names the command the project's package manager runs, instead of always `npx @astryxdesign/cli`.++@josephfarinadiff --git a/.changeset/cli-npm-prefix-upgrade.md b/.changeset/cli-npm-prefix-upgrade.mdnew file mode 100644index 0000000000..8d78b515de--- /dev/null+++ b/.changeset/cli-npm-prefix-upgrade.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[fix] A CLI installed with npm under a prefix of its own (`npm i -g --prefix ~/.local`, `NPM_CONFIG_PREFIX`, or `prefix=` in an `.npmrc`) is now upgraded into that same prefix: the update notice and `astryx doctor` print `npm i -g --prefix <prefix> @astryxdesign/cli@latest`, with `~` for the home folder. npm's default prefixes (Node's own, `/usr/local`, `/usr`, and `%APPDATA%\npm` on Windows) keep the plain command.++@josephfarinadiff --git a/.changeset/cli-update-reminders.md b/.changeset/cli-update-reminders.mdnew file mode 100644index 0000000000..d068f168a5--- /dev/null+++ b/.changeset/cli-update-reminders.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[feat] Update notices, the way `gh` and the Vercel CLI do them. Once a day, never in the first day after its first run, the CLI installed for the computer checks the registry's `latest` release in the background without delaying the command; it never installs a release by itself. When a newer release exists, a command that finishes successfully prints two lines on standard error, at most once a day: `A new release of Astryx is available: <current> → <newest>` and `To upgrade, run: <command>`, with the command of the package manager that installed the CLI (`npm i -g`, `pnpm add -g`, `yarn global add`, `bun add -g`, or `volta install`), after the Node the release needs when the computer runs an older one. Inside a project the notice names the project's install and `upgrade` commands instead, and an `astryx` first on the search path from before the hand-off gets a notice naming its upgrade. No notice prints with `--json`, after a failed command, or when `CI` or `NO_UPDATE_NOTIFIER` is set, and neither variable lets the check run; unlike `gh`, a notice prints when standard error is not a terminal, because agents run the CLI without one. What the check found lives in `astryx/state.json` in the per-user configuration folder. `astryx doctor` reports the same: the `newest-release` check names the upgrade commands, and a new `cli-on-path` check lists every `astryx` command on the search path.++@josephfarinadiff --git a/.github/scripts/cli-global-mode-smoke.mjs b/.github/scripts/cli-global-mode-smoke.mjsnew file mode 100644index 0000000000..10bbdefd0b--- /dev/null+++ b/.github/scripts/cli-global-mode-smoke.mjs@@ -0,0 +1,1053 @@+#!/usr/bin/env node+// Copyright (c) Meta Platforms, Inc. and affiliates.++// Global-mode smoke test for the Astryx CLI: one Node script, no dependencies, runs on macOS, Windows and Linux.+//+// node .github/scripts/cli-global-mode-smoke.mjs --packs <dir with astryxdesign-cli-*.tgz and astryxdesign-core-*.tgz> [--out results.json]+//+// It starts small local package registries in this process (they forward to the public registry and add the+// packed branch packages), installs the packed CLI globally with npm into a throwaway prefix, and checks, in+// throwaway folders with a throwaway home folder:+// - which release answers in a project with its own CLI, a project with Core only, a fresh clone and an empty+// folder; the one-line "answered by" notice; --json output that is clean JSON with nothing on stderr;+// - that a fresh clone gets nothing written into it;+// - the daily update check and its notice when the registry's latest tag names a newer release (it+// installs nothing, and the installed release keeps answering);+// - offline: a project with only Core is answered by the starting copy (copy "starting"); a project whose own+// CLI cannot start and whose release is not cached is answered by the starting copy, with one warning line+// and meta.answeredBy.copy "fallback", and the failed install is not retried on the next run;+// - stopping a run in the middle of a release install (Ctrl-C, and killing the CLI process alone): which+// package-manager processes are left, and whether the next run recovers;+// - `astryx init --user` / `--remove-agents` (files under the home folder, valid frontmatter, nothing in the project);+// - the commands the CLI prints, pasted into PowerShell and cmd (Windows) or sh (macOS, Linux);+// - the rows of AST-081's global and project table that depend on the operating system's own file+// system: G25, a folder typed in another letter case (macOS, Windows), and G26, Windows paths and+// installs (a lower-case drive letter, the npm shim on the search path, the cache under LOCALAPPDATA).+// Started by hand from the workflow (.github/workflows/cli-global-mode-smoke.yml); the in-repo table+// tests (packages/cli/test/global-local.test.mjs) cover the path rules on every pull request.+// Exit status 1 when any check fails. Results are written as JSON, and as Markdown to $GITHUB_STEP_SUMMARY when set.++import {spawn, execFileSync} from 'node:child_process';+import crypto from 'node:crypto';+import fs from 'node:fs';+import http from 'node:http';+import os from 'node:os';+import path from 'node:path';+import zlib from 'node:zlib';++const args = Object.fromEntries(+ process.argv+ .slice(2)+ .reduce(+ (acc, a, i, all) =>+ a.startsWith('--')+ ? [+ ...acc,+ [+ a.slice(2),+ all[i + 1]?.startsWith('--') ? true : (all[i + 1] ?? true),+ ],+ ]+ : acc,+ [],+ ),+);+const WIN = process.platform === 'win32';+const MAC = process.platform === 'darwin';+const UPSTREAM = args.upstream || 'https://registry.npmjs.org';+const OUT = args.out || 'global-mode-smoke-results.json';+const results = [];+const T0 = Date.now();++function log(...a) {+ console.log(`[${((Date.now() - T0) / 1000).toFixed(1)}s]`, ...a);+}+function record(name, status, detail) {+ results.push({name, status, detail});+ log(+ `${status.toUpperCase().padEnd(4)} ${name}: ${typeof detail === 'string' ? detail : JSON.stringify(detail)}`,+ );+}+const ok = (name, cond, detail) => record(name, cond ? 'pass' : 'fail', detail);++// ---------------------------------------------------------------- packed branch packages+function readTgzPackageJson(file) {+ const buf = zlib.gunzipSync(fs.readFileSync(file));+ let off = 0;+ let longName = null;+ while (off + 512 <= buf.length) {+ const h = buf.subarray(off, off + 512);+ if (h.every(b => b === 0)) break;+ let name = h.subarray(0, 100).toString('utf8').replace(/\0.*$/s, '');+ const prefix = h.subarray(345, 500).toString('utf8').replace(/\0.*$/s, '');+ if (prefix) name = `${prefix}/${name}`;+ const size = parseInt(+ h.subarray(124, 136).toString('utf8').replace(/\0.*$/s, '').trim() || '0',+ 8,+ );+ const type = String.fromCharCode(h[156]);+ const body = buf.subarray(off + 512, off + 512 + size);+ if (type === 'x') {+ const m = body.toString('utf8').match(/\d+ path=([^\n]+)\n/);+ if (m) longName = m[1];+ } else {+ if (longName) name = longName;+ longName = null;+ if (+ name.replace(/^[^/]+\//, '') === 'package.json' &&+ name.split('/').length === 2+ )+ return JSON.parse(body.toString('utf8'));+ }+ off += 512 + Math.ceil(size / 512) * 512;+ }+ throw new Error(`no package.json in ${file}`);+}++const packsDir = path.resolve(args.packs || 'packs');+const packFiles = fs.readdirSync(packsDir).filter(f => f.endsWith('.tgz'));+const overlay = {};+for (const f of packFiles) {+ const file = path.join(packsDir, f);+ const pj = readTgzPackageJson(file);+ if (!['@astryxdesign/cli', '@astryxdesign/core'].includes(pj.name)) continue;+ const bytes = fs.readFileSync(file);+ overlay[pj.name] = {+ pj,+ bytes,+ integrity:+ 'sha512-' + crypto.createHash('sha512').update(bytes).digest('base64'),+ shasum: crypto.createHash('sha1').update(bytes).digest('hex'),+ };+}+if (!overlay['@astryxdesign/cli'] || !overlay['@astryxdesign/core']) {+ console.error(+ `need packed @astryxdesign/cli and @astryxdesign/core in ${packsDir}`,+ );+ process.exit(2);+}+const LABEL = overlay['@astryxdesign/cli'].pj.version;+if (overlay['@astryxdesign/core'].pj.version !== LABEL) {+ console.error('packed CLI and Core versions differ');+ process.exit(2);+}++// ---------------------------------------------------------------- local registries+const upstreamCache = new Map();+async function upstreamPackument(name, accept) {+ const key = `${name}|${accept}`;+ if (!upstreamCache.has(key)) {+ upstreamCache.set(+ key,+ (async () => {+ const r = await fetch(`${UPSTREAM}/${name.replace('/', '%2f')}`, {+ headers: {accept},+ });+ if (!r.ok) return null;+ return r.text();+ })(),+ );+ }+ const t = await upstreamCache.get(key);+ return t == null ? null : JSON.parse(t);+}++function startRegistry({latest = null, throttleBytesPerSec = 0} = {}) {+ return new Promise(resolve => {+ const server = http.createServer(async (req, res) => {+ try {+ const url = decodeURIComponent(req.url.split('?')[0]);+ const self = `http://127.0.0.1:${server.address().port}`;+ const tgz = url.match(/^\/((?:@[^/]+\/)?[^/]+)\/-\/(.+\.tgz)$/);+ if (tgz) {+ const [, name, file] = tgz;+ let body;+ if (overlay[name] && file.endsWith(`-${LABEL}.tgz`))+ body = overlay[name].bytes;+ else {+ const r = await fetch(`${UPSTREAM}/${name}/-/${file}`);+ if (!r.ok) {+ res.writeHead(r.status);+ return res.end();+ }+ body = Buffer.from(await r.arrayBuffer());+ }+ res.writeHead(200, {+ 'content-type': 'application/octet-stream',+ 'content-length': body.length,+ });+ if (!throttleBytesPerSec) return res.end(body);+ let i = 0;+ const step = Math.max(1, Math.floor(throttleBytesPerSec / 10));+ const t = setInterval(() => {+ if (res.destroyed) return clearInterval(t);+ res.write(body.subarray(i, i + step));+ i += step;+ if (i >= body.length) {+ clearInterval(t);+ res.end();+ }+ }, 100);+ return;+ }+ const m = url.match(/^\/((?:@[^/]+\/)?[^/@]+)(?:\/(.+))?$/);+ if (!m || url.startsWith('/-/')) {+ res.writeHead(404);+ return res.end('{}');+ }+ const name = m[1];+ const accept =+ req.headers.accept && req.headers.accept.includes('install-v1')+ ? 'application/vnd.npm.install-v1+json'+ : 'application/json';+ const p = await upstreamPackument(name, accept);+ if (!p) {+ res.writeHead(404);+ return res.end('{}');+ }+ if (throttleBytesPerSec) {+ for (const v of Object.values(p.versions || {}))+ if (v.dist?.tarball)+ v.dist.tarball = v.dist.tarball.replace(+ /^https?:\/\/[^/]+/,+ self,+ );+ }+ if (overlay[name]) {+ const o = overlay[name];+ const keep = [+ 'dependencies',+ 'peerDependencies',+ 'peerDependenciesMeta',+ 'optionalDependencies',+ 'bin',+ 'engines',+ ];+ p.versions[LABEL] = {+ name,+ version: LABEL,+ ...Object.fromEntries(+ keep.filter(k => o.pj[k]).map(k => [k, o.pj[k]]),+ ),+ dist: {+ tarball: `${self}/${name}/-/${name.split('/')[1]}-${LABEL}.tgz`,+ integrity: o.integrity,+ shasum: o.shasum,+ },+ };+ if (p.time)+ p.time[LABEL] = new Date(Date.now() - 3 * 86400e3).toISOString();+ // A newer `latest` that the registry does not hold yet is listed as+ // a copy of the branch release under that version, for notices.+ if (latest && !p.versions[latest]) {+ p.versions[latest] = {...p.versions[LABEL], version: latest};+ }+ p['dist-tags'] = {...p['dist-tags'], latest: latest || LABEL};+ }+ if (m[2]) {+ const v = p['dist-tags'][m[2]] || m[2];+ const body = p.versions[v];+ res.writeHead(body ? 200 : 404, {'content-type': 'application/json'});+ return res.end(JSON.stringify(body || {}));+ }+ const body = Buffer.from(JSON.stringify(p));+ res.writeHead(200, {+ 'content-type': 'application/json',+ 'content-length': body.length,+ });+ res.end(body);+ } catch (e) {+ res.writeHead(502);+ res.end(JSON.stringify({error: String(e)}));+ }+ });+ server.listen(0, '127.0.0.1', () =>+ resolve({server, url: `http://127.0.0.1:${server.address().port}/`}),+ );+ });+}++// ---------------------------------------------------------------- processes+function quoteWin(a) {+ return /[\s"&|<>^()%!]/.test(a) ? `"${a.replace(/"/g, '""')}"` : a;+}+function run(+ cmd,+ argv,+ {cwd, env, timeoutMs = 300_000, shell = false, input = null} = {},+) {+ return new Promise(resolve => {+ const t0 = Date.now();+ let child;+ if (shell && WIN)+ child = spawn(+ 'cmd.exe',+ ['/d', '/s', '/c', `"${[cmd, ...argv].map(quoteWin).join(' ')}"`],+ {cwd, env, windowsVerbatimArguments: true},+ );+ else child = spawn(cmd, argv, {cwd, env});+ let stdout = '';+ let stderr = '';+ child.stdout.on('data', d => (stdout += d));+ child.stderr.on('data', d => (stderr += d));+ if (input != null) child.stdin.end(input);+ else child.stdin.end();+ const timer = setTimeout(() => {+ stderr += '\n[smoke: timed out]';+ try {+ if (WIN)+ execFileSync('taskkill', ['/pid', String(child.pid), '/t', '/f'], {+ stdio: 'ignore',+ });+ else child.kill('SIGKILL');+ } catch {}+ }, timeoutMs);+ child.on('close', (code, signal) => {+ clearTimeout(timer);+ resolve({+ code,+ signal,+ stdout,+ stderr,+ secs: +((Date.now() - t0) / 1000).toFixed(2),+ });+ });+ child.on('error', e => {+ clearTimeout(timer);+ resolve({+ code: -1,+ signal: null,+ stdout,+ stderr: stderr + String(e),+ secs: +((Date.now() - t0) / 1000).toFixed(2),+ });+ });+ });+}++function listProcesses(match) {+ try {+ if (WIN) {+ const out = execFileSync(+ 'powershell.exe',+ [+ '-NoProfile',+ '-Command',+ `Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -like '*${match}*' } | Select-Object ProcessId,Name,CommandLine | ConvertTo-Json -Compress`,+ ],+ {encoding: 'utf8'},+ );+ if (!out.trim()) return [];+ const j = JSON.parse(out);+ return (Array.isArray(j) ? j : [j])+ .filter(p => !String(p.CommandLine).includes('Get-CimInstance'))+ .map(p => ({+ pid: p.ProcessId,+ cmd: String(p.CommandLine).slice(0, 160),+ }));+ }+ const out = execFileSync('ps', ['-axo', 'pid=,command='], {+ encoding: 'utf8',+ });+ return out+ .split('\n')+ .filter(l => l.includes(match) && !l.includes('ps -axo'))+ .map(l => ({+ pid: +l.trim().split(/\s+/)[0],+ cmd: l.trim().slice(0, 160),+ }));+ } catch (e) {+ return [{error: String(e).slice(0, 200)}];+ }+}++const sleep = ms => new Promise(r => setTimeout(r, ms));++// ---------------------------------------------------------------- setup+const WORK = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-smoke-'));+const PREFIX = path.join(WORK, 'prefix');+const BIN_DIR = WIN ? PREFIX : path.join(PREFIX, 'bin');+const CLI_ENTRY = path.join(+ PREFIX,+ WIN ? '' : 'lib',+ 'node_modules',+ '@astryxdesign',+ 'cli',+ 'clients',+ 'cli',+ 'bin',+ 'astryx.mjs',+);++function homeEnv(home, registry) {+ const env = {...process.env};+ for (const k of Object.keys(env))+ if (+ /^(npm_|NPM_|XDG_CACHE_HOME$|XDG_CONFIG_HOME$|ASTRYX|CI$|NO_UPDATE_NOTIFIER$)/.test(+ k,+ )+ )+ delete env[k];+ const pathKey =+ Object.keys(env).find(k => k.toUpperCase() === 'PATH') || 'PATH';+ const oldPath = env[pathKey] || '';+ for (const k of Object.keys(env))+ if (k.toUpperCase() === 'PATH') delete env[k];+ env[pathKey] = `${BIN_DIR}${path.delimiter}${oldPath}`;+ Object.assign(env, {+ HOME: home,+ USERPROFILE: home,+ LOCALAPPDATA: path.join(home, 'AppData', 'Local'),+ APPDATA: path.join(home, 'AppData', 'Roaming'),+ npm_config_registry: registry,+ npm_config_cache: path.join(WORK, 'npm-cache'),+ npm_config_update_notifier: 'false',+ npm_config_fund: 'false',+ npm_config_audit: 'false',+ NO_COLOR: '1',+ });+ return env;+}+function newHome(name) {+ const h = path.join(WORK, 'homes', name);+ fs.mkdirSync(path.join(h, 'AppData', 'Local'), {recursive: true});+ fs.mkdirSync(path.join(h, 'AppData', 'Roaming'), {recursive: true});+ return h;+}+function configDirOf(home) {+ if (WIN) return path.join(home, 'AppData', 'Roaming', 'astryx');+ if (MAC) return path.join(home, 'Library', 'Application Support', 'astryx');+ return path.join(home, '.config', 'astryx');+}+function cacheDirOf(home) {+ if (WIN) return path.join(home, 'AppData', 'Local', 'astryx', 'Cache');+ if (MAC) return path.join(home, 'Library', 'Caches', 'astryx');+ return path.join(home, '.cache', 'astryx');+}+const npmCmd = 'npm';+const astryx = (argv, opts) => run('astryx', argv, {...opts, shell: true});+const astryxDirect = (argv, opts) =>+ run(process.execPath, [CLI_ENTRY, ...argv], opts);++function listTree(dir) {+ const out = [];+ const walk = d => {+ for (const e of fs.readdirSync(d, {withFileTypes: true})) {+ const p = path.join(d, e.name);+ if (e.name === 'node_modules') continue;+ if (e.isDirectory()) walk(p);+ else out.push(path.relative(dir, p));+ }+ };+ walk(dir);+ return out.sort();+}+const lastLine = s => (s.trim().split(/\r?\n/).pop() || '').trim();+const whoLines = s =>+ s+ .split(/\r?\n/)+ .filter(l => l.startsWith('astryx: ') && !/installing|waiting/i.test(l));+function cleanJson(r) {+ try {+ const j = JSON.parse(r.stdout);+ return {json: j, clean: r.stderr.trim() === ''};+ } catch {+ return {json: null, clean: false};+ }+}++async function makeProject(dir, deps, registry) {+ fs.mkdirSync(path.join(dir, 'src'), {recursive: true});+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ JSON.stringify(+ {+ name: path.basename(dir),+ version: '1.0.0',+ private: true,+ dependencies: deps,+ },+ null,+ 2,+ ),+ );+ const env = homeEnv(newHome(`fx-${path.basename(dir)}`), registry);+ const r = await run(+ npmCmd,+ [+ 'install',+ '--ignore-scripts',+ '--no-audit',+ '--no-fund',+ '--loglevel=error',+ ],+ {cwd: dir, env, shell: true, timeoutMs: 600_000},+ );+ if (r.code !== 0)+ throw new Error(`npm install in ${dir} failed: ${r.stderr.slice(-800)}`);+}++// ---------------------------------------------------------------- main+async function main() {+ log(+ `platform ${process.platform} ${os.release()} node ${process.version}; branch label ${LABEL}; work ${WORK}`,+ );+ const regMain = await startRegistry();+ const NEWER = LABEL.replace(+ /^(\d+)\.(\d+)\..*$/,+ (_, a, b) => `${a}.${Number(b) + 1}.0`,+ );+ const regNewer = await startRegistry({latest: NEWER});+ const regSlow = await startRegistry({throttleBytesPerSec: 20_000});+ const OFFLINE = 'http://127.0.0.1:9/';+ const npmV = await run(npmCmd, ['--version'], {+ env: homeEnv(newHome('v'), regMain.url),+ shell: true,+ });+ log(`npm ${npmV.stdout.trim()}`);++ // global install of the packed branch+ const homeG = newHome('global');+ const gi = await run(+ npmCmd,+ [+ 'install',+ '-g',+ '--prefix',+ PREFIX,+ `@astryxdesign/cli@${LABEL}`,+ '--no-audit',+ '--no-fund',+ '--loglevel=error',+ ],+ {env: homeEnv(homeG, regMain.url), shell: true, timeoutMs: 600_000},+ );+ ok(+ 'global npm install of the packed CLI',+ gi.code === 0 && fs.existsSync(CLI_ENTRY),+ `rc=${gi.code} ${gi.stderr.trim().slice(-300)}`,+ );+ if (gi.code !== 0) return;++ // fixtures+ const FX = path.join(WORK, 'fx');+ const own068 = path.join(FX, 'own 068'); // a space in the path on purpose+ const core071 = path.join(FX, 'core071');+ const core070 = path.join(FX, 'core070');+ const core063 = path.join(FX, 'core063');+ const fresh068 = path.join(FX, 'fresh068');+ const empty = path.join(FX, 'empty', 'a');+ await Promise.all([+ makeProject(+ own068,+ {'@astryxdesign/cli': '0.6.8', '@astryxdesign/core': '0.6.8'},+ regMain.url,+ ),+ makeProject(core071, {'@astryxdesign/core': '0.7.1'}, regMain.url),+ makeProject(core070, {'@astryxdesign/core': '0.7.0'}, regMain.url),+ makeProject(core063, {'@astryxdesign/core': '0.6.3'}, regMain.url),+ ]);+ // Projects whose own CLI cannot start (its package, with no astryx+ // command): only they get the release equal to their Core from the cache.+ for (const [dir, version] of [+ [core070, '0.7.0'],+ [core063, '0.6.3'],+ ]) {+ const own = path.join(dir, 'node_modules', '@astryxdesign', 'cli');+ fs.rmSync(own, {recursive: true, force: true});+ fs.mkdirSync(own, {recursive: true});+ fs.writeFileSync(+ path.join(own, 'package.json'),+ JSON.stringify({name: '@astryxdesign/cli', version}),+ );+ }+ fs.mkdirSync(path.join(fresh068, 'src'), {recursive: true});+ const fdeps = {'@astryxdesign/cli': '0.6.8', '@astryxdesign/core': '0.6.8'};+ fs.writeFileSync(+ path.join(fresh068, 'package.json'),+ JSON.stringify(+ {name: 'fresh068', version: '1.0.0', private: true, dependencies: fdeps},+ null,+ 2,+ ),+ );+ fs.writeFileSync(+ path.join(fresh068, 'package-lock.json'),+ JSON.stringify(+ {+ name: 'fresh068',+ lockfileVersion: 3,+ requires: true,+ packages: {+ '': {name: 'fresh068', dependencies: fdeps},+ 'node_modules/@astryxdesign/cli': {version: '0.6.8'},+ 'node_modules/@astryxdesign/core': {version: '0.6.8'},+ },+ },+ null,+ 2,+ ),+ );+ fs.mkdirSync(empty, {recursive: true});+ log('fixtures ready');++ // which release answers, the notice, --json clean+ const homeA = newHome('answers');+ const envA = homeEnv(homeA, regMain.url);+ const cases = [+ [+ 'project with its own CLI 0.6.8',+ own068,+ '0.6.8',+ `answered by this project's CLI 0.6.8, handed over from CLI ${LABEL}`,+ ],+ [+ 'project with Core 0.7.1 only',+ core071,+ LABEL,+ `this project has no Astryx CLI installed; answered by CLI ${LABEL} while its Core is 0.7.1.`,+ ],+ [+ 'fresh clone (lockfile 0.6.8, nothing installed)',+ fresh068,+ LABEL,+ `this project has no Astryx CLI installed; answered by CLI ${LABEL} while its Core is 0.6.8.`,+ ],+ ['empty folder', empty, LABEL, 'outside a project'],+ ];+ for (const [label, dir, want, line] of cases) {+ const before = listTree(dir);+ const v = await astryx(['--version'], {cwd: dir, env: envA});+ const who = whoLines(v.stderr);+ ok(+ `${label}: release`,+ v.code === 0 && lastLine(v.stdout) === want,+ `rc=${v.code} answered ${lastLine(v.stdout)} (want ${want}) ${v.secs}s`,+ );+ ok(+ `${label}: one notice line`,+ who.length === 1 && who[0].includes(line),+ who.join(' | ') || v.stderr.trim().slice(-200),+ );+ const j = await astryx(['component', 'Typeahead', '--json'], {+ cwd: dir,+ env: envA,+ });+ const {json, clean} = cleanJson(j);+ const ab = json?.meta?.answeredBy;+ const abOk = want === LABEL ? ab && ab.cli === LABEL : true; // older releases predate the field+ // a fresh clone has no Core installed: the copy that started the run answers as it would there (ERR_CORE_NOT_FOUND or its own Core), still as clean JSON+ const rcOk =+ j.code === 0 || (dir === fresh068 && json?.code === 'ERR_CORE_NOT_FOUND');+ ok(+ `${label}: --json clean`,+ rcOk && json && clean && abOk,+ `rc=${j.code} json=${!!json} code=${json?.code ?? '-'} stderr=${JSON.stringify(j.stderr.trim().slice(0, 160))} answeredBy=${JSON.stringify(ab)}`,+ );+ if (dir === fresh068) {+ const after = listTree(dir);+ ok(+ `${label}: nothing written in the project`,+ JSON.stringify(before) === JSON.stringify(after),+ `before=${before.length} after=${after.length} new=${after.filter(f => !before.includes(f)).slice(0, 4)}`,+ );+ }+ }++ // G25: a folder typed in another letter case answers as the folder (case-insensitive file systems)+ if (MAC || WIN) {+ const typed = path.join(+ path.dirname(own068),+ path.basename(own068).toUpperCase(),+ );+ const v = await astryx(['--version'], {cwd: typed, env: envA});+ const who = whoLines(v.stderr);+ ok(+ 'G25 a folder typed in another letter case answers as the folder',+ v.code === 0 &&+ lastLine(v.stdout) === '0.6.8' &&+ who.length === 1 &&+ who[0].includes("project's CLI 0.6.8"),+ `cwd=${typed} rc=${v.code} answered ${lastLine(v.stdout)} ${JSON.stringify(who)}`,+ );+ }++ // G26: Windows paths and installs+ if (WIN) {+ const lowerDrive = own068.replace(/^[A-Z]:/, d => d.toLowerCase());+ const v = await astryx(['--version'], {cwd: lowerDrive, env: envA});+ ok(+ 'G26 a lower-case drive letter answers as the folder',+ v.code === 0 && lastLine(v.stdout) === '0.6.8',+ `cwd=${lowerDrive} rc=${v.code} answered ${lastLine(v.stdout)}`,+ );+ const d = await astryx(['doctor', '--json'], {cwd: empty, env: envA});+ const check = cleanJson(d).json?.data?.checks?.find(+ c => c.id === 'cli-on-path',+ );+ ok(+ 'G26 doctor finds the npm shim on the search path',+ check?.status === 'pass',+ JSON.stringify(check ?? d.stdout.slice(0, 200)).slice(0, 300),+ );+ ok(+ 'G26 the release cache is under LOCALAPPDATA',+ fs.existsSync(cacheDirOf(homeA)),+ cacheDirOf(homeA),+ );+ }++ // printed commands, pasted into the shells people use+ for (const [label, dir, want] of [+ ['project with Core 0.7.1 only', core071, LABEL],+ ['empty folder', empty, LABEL],+ ]) {+ const b = await astryx(['build', 'settings page'], {cwd: dir, env: envA});+ const line = (b.stdout + '\n' + b.stderr)+ .split(/\r?\n/)+ .find(l => /^command:\s+/.test(l));+ if (!line) {+ ok(`${label}: printed command found`, false, b.stdout.slice(0, 300));+ continue;+ }+ const printed = line.replace(/^command:\s+/, '').trim();+ const target = `out-${Math.random().toString(36).slice(2, 6)}/Settings.tsx`;+ const cmd = printed.replace('<path>', target);+ const shells = WIN+ ? [+ [+ 'PowerShell',+ 'powershell.exe',+ ['-NoProfile', '-NonInteractive', '-Command', cmd],+ ],+ ['cmd', 'cmd.exe', ['/d', '/s', '/c', cmd]],+ ]+ : [['sh', '/bin/sh', ['-c', cmd]]];+ for (const [sname, exe, argv] of shells) {+ const t = path.join(dir, target.split('/')[0]);+ fs.rmSync(t, {recursive: true, force: true});+ const r = await run(exe, argv, {cwd: dir, env: envA, timeoutMs: 300_000});+ const made = fs.existsSync(path.join(dir, target));+ // A project with only Core is answered, with no line, by the copy the+ // printed command starts: the CLI pinned to the release that printed it.+ const same =+ r.stderr.includes(`CLI ${want} with Core`) ||+ r.stderr.includes(`project's CLI ${want}`) ||+ (dir === core071 && printed.includes(`@astryxdesign/cli@${want}`));+ ok(+ `${label}: printed command runs in ${sname} and reaches ${want}`,+ r.code === 0 && made && same,+ `${printed} -> rc=${r.code} wrote=${made} answered=${JSON.stringify(whoLines(r.stderr))} ${r.code ? r.stderr.trim().slice(-200) : ''}`,+ );+ fs.rmSync(t, {recursive: true, force: true});+ }+ }++ // init --user in a project on an older release (computer-level text)+ {+ const home = newHome('user-text');+ const env = homeEnv(home, regMain.url);+ const before = listTree(own068);+ const r = await astryx(['init', '--user'], {cwd: own068, env});+ const files = [+ path.join(home, '.agents', 'skills', 'astryx', 'SKILL.md'),+ path.join(home, '.claude', 'skills', 'astryx', 'SKILL.md'),+ ];+ const exist = files.map(f => fs.existsSync(f));+ const txt = exist[0] ? fs.readFileSync(files[0], 'utf8') : '';+ const same =+ exist.every(Boolean) && txt === fs.readFileSync(files[1], 'utf8');+ const desc = (txt.match(/^description: (.*)$/m) || [])[1] || '';+ const quoted = /^".*"$/.test(desc);+ ok(+ 'init --user writes both skill files under the home folder',+ r.code === 0 && same,+ `rc=${r.code} files=${files.map(f => path.relative(home, f)).join(', ')} exist=${exist} identical=${same}`,+ );+ ok(+ 'init --user skill frontmatter description is quoted',+ quoted,+ desc.slice(0, 80),+ );+ ok(+ 'init --user writes nothing in the project',+ JSON.stringify(before) === JSON.stringify(listTree(own068)),+ 'project unchanged',+ );+ const rm = await astryx(['init', '--user', '--remove-agents'], {+ cwd: own068,+ env,+ });+ ok(+ 'init --user --remove-agents removes them',+ rm.code === 0 && files.every(f => !fs.existsSync(f)),+ `rc=${rm.code}`,+ );+ }++ // offline, cold cache+ {+ const home = newHome('offline');+ // A project with only Core is answered by the copy that started the run,+ // online or offline, and nothing is installed.+ const c = await astryx(['docs', '--json'], {+ cwd: core071,+ env: homeEnv(home, OFFLINE),+ });+ let cj = null;+ try {+ cj = JSON.parse(c.stdout);+ } catch {}+ ok(+ 'offline, a project with only Core: the starting copy answers (copy starting), nothing installed',+ c.code === 0 &&+ cj?.meta?.answeredBy?.copy === 'starting' &&+ cj?.meta?.answeredBy?.cli === LABEL &&+ !/installing CLI release/u.test(c.stderr) &&+ c.secs < 20,+ `rc=${c.code} answeredBy=${JSON.stringify(cj?.meta?.answeredBy)} ${c.secs}s`,+ );+ // Core 0.7.0's own CLI cannot start, so it needs release 0.7.0, which is+ // not cached and cannot be fetched: the starting copy answers, and says so.+ const t = await astryx(['--version'], {+ cwd: core070,+ env: homeEnv(home, OFFLINE),+ });+ const warnings = t.stderr+ .split(/\r?\n/u)+ .filter(line => line.includes('could not get Astryx'));+ ok(+ 'offline, a project whose own CLI cannot start: the starting copy answers, with one warning line',+ t.code === 0 &&+ lastLine(t.stdout) === LABEL &&+ warnings.length === 1 &&+ /^astryx: could not get Astryx 0\.7\.0 to match this project's Core \(.+\); answering with CLI .+ instead$/u.test(+ warnings[0],+ ) &&+ t.secs < 90,+ `rc=${t.code} ${lastLine(t.stdout)} warnings=${warnings.length} ${t.secs}s`,+ );+ const r = await astryx(['docs', '--json'], {+ cwd: core070,+ env: homeEnv(home, OFFLINE),+ });+ let j = null;+ try {+ j = JSON.parse(r.stdout);+ } catch {}+ ok(+ 'offline, a project whose own CLI cannot start: JSON intact, meta.answeredBy.copy is fallback',+ r.code === 0 &&+ j?.meta?.answeredBy?.copy === 'fallback' &&+ j?.meta?.answeredBy?.cli === LABEL &&+ r.secs < 90,+ `rc=${r.code} answeredBy=${JSON.stringify(j?.meta?.answeredBy)} ${r.secs}s`,+ );+ // The failed install is remembered: the next offline run starts no+ // install and prints no "installing" line.+ const again = await astryx(['--version'], {+ cwd: core070,+ env: homeEnv(home, OFFLINE),+ });+ ok(+ 'offline, a project whose own CLI cannot start: the next run does not try the install again',+ again.code === 0 &&+ !/installing CLI release/u.test(again.stderr) &&+ /could not get Astryx 0\.7\.0 /u.test(again.stderr) &&+ again.secs < 20,+ `rc=${again.code} ${again.secs}s stderr=${JSON.stringify(again.stderr.trim().slice(0, 200))}`,+ );+ const o = await astryx(['--version'], {+ cwd: empty,+ env: homeEnv(home, OFFLINE),+ });+ ok(+ 'offline, outside a project: answers at once',+ o.code === 0 && lastLine(o.stdout) === LABEL && o.secs < 20,+ `rc=${o.code} ${lastLine(o.stdout)} ${o.secs}s`,+ );+ }++ // stopping a run in the middle of a release install+ for (const how of ['ctrl-c', 'kill-cli-only']) {+ const home = newHome(`stop-${how}`);+ const env = homeEnv(home, regSlow.url);+ const child = spawn(process.execPath, [CLI_ENTRY, '--version'], {+ cwd: core063,+ env,+ detached: !WIN,+ });+ let err = '';+ child.stderr.on('data', d => (err += d));+ child.stdout.on('data', () => {});+ const started = Date.now();+ while (!/installing/i.test(err) && Date.now() - started < 30_000)+ await sleep(250);+ await sleep(3000);+ const during = listProcesses('@astryxdesign/[email protected]');+ if (how === 'ctrl-c') {+ if (WIN) {+ // no console to send Ctrl-C to from here; closest equivalent is ending the process tree+ try {+ execFileSync('taskkill', ['/pid', String(child.pid), '/t'], {+ stdio: 'ignore',+ });+ } catch {}+ } else process.kill(-child.pid, 'SIGINT');+ } else {+ child.kill('SIGKILL'); // the CLI process alone (TerminateProcess on Windows)+ }+ const closed = await Promise.race([+ new Promise(r => child.on('close', () => r(true))),+ sleep(15_000).then(() => false),+ ]);+ if (!closed) {+ child.kill('SIGKILL');+ await new Promise(r => child.on('close', r));+ }+ await sleep(3000);+ const left = listProcesses('@astryxdesign/[email protected]');+ const status = left.length === 0 ? 'pass' : WIN ? 'info' : 'fail'; // Windows: documented limit, reported+ record(+ `stop during install (${how}): no package-manager process left`,+ status,+ `${WIN ? (how === 'ctrl-c' ? 'taskkill /t' + (closed ? '' : ' then forced') : 'TerminateProcess') + '; ' : ''}progress line=${/installing/i.test(err)} npm processes during=${during.length} after=${left.length} ${JSON.stringify(left).slice(0, 300)}`,+ );+ for (const p of left)+ if (p.pid)+ try {+ process.kill(p.pid, 'SIGKILL');+ } catch {}+ const again = await astryxDirect(['--version'], {+ cwd: core063,+ env: homeEnv(home, regMain.url),+ timeoutMs: 400_000,+ });+ ok(+ `stop during install (${how}): next run recovers`,+ again.code === 0 && lastLine(again.stdout) === '0.6.3',+ `rc=${again.code} ${lastLine(again.stdout)} ${again.secs}s`,+ );+ }++ // the daily update check and its notice (outside a project), notify-only+ {+ const home = newHome('update');+ const env1 = homeEnv(home, regNewer.url);+ await astryx(['--version'], {cwd: empty, env: env1});+ const sfile = path.join(configDirOf(home), 'state.json');+ let st = {};+ try {+ st = JSON.parse(fs.readFileSync(sfile, 'utf8'));+ } catch {}+ st.firstRunAt = Date.now() - 2 * 86400e3;+ fs.mkdirSync(path.dirname(sfile), {recursive: true});+ fs.writeFileSync(sfile, JSON.stringify(st));+ const kick = await astryx(['--version'], {cwd: empty, env: env1});+ const t = Date.now();+ const latestOf = () => {+ try {+ return JSON.parse(fs.readFileSync(sfile, 'utf8')).latest;+ } catch {+ return undefined;+ }+ };+ while (!latestOf() && Date.now() - t < 240_000) await sleep(1000);+ const js = await astryx(['search', 'button', '--json'], {+ cwd: empty,+ env: env1,+ });+ const ci = await astryx(['--version'], {+ cwd: empty,+ env: {...env1, CI: 'true'},+ });+ const a = await astryx(['--version'], {cwd: empty, env: env1});+ const b = await astryx(['--version'], {cwd: empty, env: env1});+ const noticeOf = r =>+ r.stderr+ .split(/\r?\n/)+ .filter(l => /^(A new release of Astryx|To upgrade, run:)/.test(l));+ ok(+ 'update check does not slow the run that starts it',+ kick.secs < 10,+ `${kick.secs}s`,+ );+ ok(+ `update: the check finds ${NEWER}, installs nothing, and ${LABEL} keeps answering`,+ latestOf() === NEWER &&+ lastLine(a.stdout) === LABEL &&+ !fs.existsSync(path.join(cacheDirOf(home), 'releases', NEWER)),+ `latest=${latestOf()} answered ${lastLine(a.stdout)}`,+ );+ // The CLI is installed into a throwaway npm prefix, not one npm uses by+ // default, so the notice upgrades into that prefix, named by its real path+ // (quoted when it holds a space).+ const prefixForms = [+ ...new Set([+ PREFIX,+ fs.realpathSync(PREFIX),+ fs.realpathSync.native(PREFIX),+ ]),+ ].map(p => (/\s/.test(p) ? JSON.stringify(p) : p));+ // The check the first run starts can finish before that run exits, so+ // the pair prints on whichever of the two comes first: exactly one of+ // them prints it.+ const pairs = [kick, a].filter(r => noticeOf(r).length > 0);+ const notice = pairs.length === 1 ? noticeOf(pairs[0]) : [];+ ok(+ 'update: one two-line notice after the first text run, upgrading into the install prefix; none in JSON, in CI, or after',+ pairs.length === 1 &&+ notice.length === 2 &&+ notice[0] ===+ `A new release of Astryx is available: ${LABEL} → ${NEWER}` &&+ prefixForms.some(+ p =>+ notice[1] ===+ `To upgrade, run: npm i -g --prefix ${p} @astryxdesign/cli@latest`,+ ) &&+ js.stderr.trim() === '' &&+ noticeOf(ci).length === 0 &&+ noticeOf(b).length === 0,+ `notice=${JSON.stringify(notice)} prefix=${JSON.stringify(prefixForms)} kick=${noticeOf(kick).length} a=${noticeOf(a).length} json-stderr=${JSON.stringify(js.stderr.trim().slice(0, 100))} ci=${noticeOf(ci).length} after=${noticeOf(b).length}`,+ );+ }+}++main()+ .catch(e =>+ record('smoke harness', 'fail', String(e.stack || e).slice(0, 800)),+ )+ .finally(() => {+ const summary = {+ platform: process.platform,+ release: os.release(),+ node: process.version,+ label: LABEL,+ results,+ pass: results.filter(r => r.status === 'pass').length,+ fail: results.filter(r => r.status === 'fail').length,+ info: results.filter(r => r.status === 'info').length,+ };+ fs.writeFileSync(OUT, JSON.stringify(summary, null, 2));+ const md = [+ `### Global-mode smoke: ${process.platform} (${os.release()}), Node ${process.version}, CLI ${LABEL}`,+ '',+ `pass ${summary.pass} · fail ${summary.fail} · info ${summary.info}`,+ '',+ '| Check | Result | Detail |',+ '|---|---|---|',+ ...results.map(+ r =>+ `| ${r.name} | ${r.status} | ${String(+ typeof r.detail === 'string' ? r.detail : JSON.stringify(r.detail),+ )+ .replace(/\|/g, '\\|')+ .replace(/\r?\n/g, ' ')+ .slice(0, 300)} |`,+ ),+ ].join('\n');+ if (process.env.GITHUB_STEP_SUMMARY)+ fs.appendFileSync(process.env.GITHUB_STEP_SUMMARY, md + '\n');+ console.log('\n' + md);+ process.exit(summary.fail ? 1 : 0);+ });diff --git a/.github/workflows/cli-global-mode-smoke.yml b/.github/workflows/cli-global-mode-smoke.ymlnew file mode 100644index 0000000000..ee8c629a92--- /dev/null+++ b/.github/workflows/cli-global-mode-smoke.yml@@ -0,0 +1,68 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.++# CLI global mode smoke test, started by hand. Packs the CLI and Core from the+# commit it runs on, installs the packed CLI for the computer with npm, and+# runs .github/scripts/cli-global-mode-smoke.mjs on macOS, Windows, and Linux.+# It covers the rows of AST-081's global and project table that depend on an+# operating system's own file system (G25, G26), which the in-repo tests check+# only for their path rules. It never runs on pull requests.+name: CLI Global Mode Smoke (manual)++on:+ workflow_dispatch:++permissions: {}++jobs:+ pack:+ runs-on: ubuntu-latest+ timeout-minutes: 30+ permissions:+ contents: read+ steps:+ - uses: actions/checkout@v7+ - uses: ./.github/actions/setup+ - name: Pack CLI and Core+ run: |+ mkdir -p "$RUNNER_TEMP/packs"+ pnpm -F @astryxdesign/build build+ pnpm -F @astryxdesign/core pack --pack-destination "$RUNNER_TEMP/packs"+ pnpm -F @astryxdesign/cli pack --pack-destination "$RUNNER_TEMP/packs"+ ls -la "$RUNNER_TEMP/packs"+ - uses: actions/upload-artifact@v7+ with:+ name: packs+ path: ${{ runner.temp }}/packs/*.tgz+ if-no-files-found: error++ smoke:+ needs: pack+ strategy:+ fail-fast: false+ matrix:+ os: [macos-latest, windows-latest, ubuntu-latest]+ runs-on: ${{ matrix.os }}+ timeout-minutes: 45+ permissions:+ contents: read+ steps:+ - uses: actions/checkout@v7+ with:+ sparse-checkout: |+ .github/scripts/cli-global-mode-smoke.mjs+ .nvmrc+ sparse-checkout-cone-mode: false+ - uses: actions/setup-node@v7+ with:+ node-version-file: .nvmrc+ - uses: actions/download-artifact@v8+ with:+ name: packs+ path: packs+ - name: Smoke test+ run: node .github/scripts/cli-global-mode-smoke.mjs --packs packs --out results-${{ matrix.os }}.json+ - uses: actions/upload-artifact@v7+ if: always()+ with:+ name: results-${{ matrix.os }}+ path: results-${{ matrix.os }}.jsondiff --git a/README.md b/README.mdindex 0c1996fdb0..677ef09f87 100644--- a/README.md+++ b/README.md@@ -55,6 +55,14 @@ yarn add @astryxdesign/core @astryxdesign/theme-neutral @stylexjs/stylexyarn add -D @astryxdesign/cli```+You can also install the CLI once for your computer, so `astryx` works in any folder and every coding agent knows Astryx; in a project, it still runs that project's own version:++```bash+npm i -g @astryxdesign/cli+```++Project install, global install, or both? `astryx docs global/project-global-or-both` compares them (both is recommended), and `astryx docs global` explains how global mode works.+The simplest setup is a few CSS imports plus a theme provider — no build plugin, no PostCSS or Babel config. See the **[@astryxdesign/core README](packages/core/README.md#quick-start)** for the full guide (Next.js, Tailwind, Vite, and CDN).For reliable CLI access, add a script to your `package.json`:diff --git a/apps/docsite/scripts/docs-pages.mjs b/apps/docsite/scripts/docs-pages.mjsindex 85b557b72d..36e70d88a8 100644--- a/apps/docsite/scripts/docs-pages.mjs+++ b/apps/docsite/scripts/docs-pages.mjs@@ -54,6 +54,15 @@ export const GUIDE_NAMESPACE_PAGES = new Map([],]);+/**+ * Older slugs of a root namespace's page, which redirect to it: global mode+ * was `cli/global`, and before that the `cli/install-once` guide.+ * @type {Map<string, string[]>}+ */+export const ROOT_PAGE_ALIASES = new Map([+ ['global', ['cli-global', 'cli-install-once']],+]);+/*** Flat topics whose full text the site shows on another topic's page. The* theme split (before namespaces) left `theme` as a short overview and moved@@ -120,6 +129,43 @@ export function withoutResolvedTokens(sections) {}));}+/**+ * Doc text with its CLI commands shown the way a reader runs them. Docs write+ * commands as bare `astryx ...`; the CLI prefixes them when it prints a doc,+ * and the docsite does the same with its own door name. `show(text, lang)`+ * prefixes the commands in one piece of text: prose and list items (`lang`+ * null), or one code block's body in its language. A table cell that is a+ * whole command is prefixed too, the way `astryx docs` prints it.+ * @param {any[]} sections+ * @param {(text: string, lang?: string | null) => string} show+ * @param {string} stem the invocation `show` prefixes with+ */+export function withCliCommands(sections, show, stem) {+ /** @param {string} cell */+ const cell = cell =>+ /^astryx(\s|$)/.test(cell ?? '')+ ? `${stem}${cell.slice('astryx'.length)}`+ : show(cell ?? '');+ return sections.map(section => ({+ ...section,+ content: (section.content ?? []).map(block => {+ switch (block?.type) {+ case 'prose':+ case 'heading':+ return {...block, text: show(block.text ?? '')};+ case 'code':+ return {...block, code: show(block.code ?? '', block.lang ?? '')};+ case 'list':+ return {...block, items: (block.items ?? []).map(item => show(item))};+ case 'table':+ return {...block, rows: (block.rows ?? []).map(row => row.map(cell))};+ default:+ return block;+ }+ }),+ }));+}+/*** The sidebar group of a namespace page: the namespace's own category when it* declares one, otherwise `foundations` when every guide under it is adiff --git a/apps/docsite/scripts/generate-data.mjs b/apps/docsite/scripts/generate-data.mjsindex cbd962eb51..8e59e3ccf2 100644--- a/apps/docsite/scripts/generate-data.mjs+++ b/apps/docsite/scripts/generate-data.mjs@@ -31,11 +31,21 @@ import {import {GUIDE_NAMESPACE_PAGES,GUIDE_PAGE_NAMESPACES,+ ROOT_PAGE_ALIASES,mergeFlatTopics,namespacePage,routeSlug,+ withCliCommands,withoutResolvedTokens,} from './docs-pages.mjs';+import {+ DOCSITE_CLI_COMMAND,+ GLOBAL_PAGE,+ GLOBAL_PAGE_CLI_COMMAND,+ getCliInvocation,+ prefixCliCommands,+ runWithCliDoor,+} from './lib/cli-command.mjs';import {docs as readDocs,template as queryTemplates,@@ -1754,7 +1764,9 @@ async function docsTreePages() {continue;}routes.push(...(await treeRoutes(root)));- const full = await namespacePage(readDocs, root);+ const full = await namespacePage(readDocs, root, {+ aliases: ROOT_PAGE_ALIASES.get(root) ?? [],+ });if (!full) continue;pages.push(full.page);Object.assign(redirects, full.redirects);@@ -1901,6 +1913,24 @@ async function generateDocsRegistry() {}docTopics.sort((a, b) => a.topic.localeCompare(b.topic));+ // Docs write commands as bare `astryx ...`. The site shows them as+ // `npx @astryxdesign/cli ...`, which runs before any install, and as plain+ // `astryx ...` on the global mode page, whose readers installed it. Each is+ // a docsite door name, and goes through the CLI's picker like any other.+ const cliStem = runWithCliDoor(DOCSITE_CLI_COMMAND, () =>+ getCliInvocation(DOCSITE_ROOT),+ );+ const globalStem = runWithCliDoor(GLOBAL_PAGE_CLI_COMMAND, () =>+ getCliInvocation(DOCSITE_ROOT),+ );+ for (const topic of docTopics) {+ const stem = topic.topic === GLOBAL_PAGE ? globalStem : cliStem;+ topic.sections = withCliCommands(+ topic.sections,+ (text, lang = null) => prefixCliCommands(text, stem, lang),+ stem,+ );+ }const content = `// Auto-generated by scripts/generate-data.mjs — do not editdiff --git a/apps/docsite/scripts/lib/cli-command.mjs b/apps/docsite/scripts/lib/cli-command.mjsnew file mode 100644index 0000000000..8ad95f2c26--- /dev/null+++ b/apps/docsite/scripts/lib/cli-command.mjs@@ -0,0 +1,30 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file The docsite's door into the CLI's command picker.+ *+ * Docs write commands as bare `astryx ...`, and whoever shows a doc prefixes+ * them with the command its readers run. The CLI does that with the project's+ * invocation; the docsite does it with its own door name: `npx @astryxdesign/cli`,+ * which runs the CLI before any install (a bare `npx astryx` reaches an+ * unrelated package), and plain `astryx` on the global mode pages, whose+ * readers have installed it. Same monorepo-relative import as the+ * ShadCN registry generator: the door is not part of the CLI's public API.+ *+ * @position apps/docsite/scripts/lib — read by generate-data.mjs.+ */++export {runWithCliDoor} from '../../../../packages/cli/foundation/env/cli-command.mjs';+export {+ getCliInvocation,+ prefixCliCommands,+} from '../../../../packages/cli/foundation/env/package-manager.mjs';++/** The command docsite pages show for running the CLI. */+export const DOCSITE_CLI_COMMAND = 'npx @astryxdesign/cli';++/** The command the global mode pages show: their readers installed the CLI. */+export const GLOBAL_PAGE_CLI_COMMAND = 'astryx';++/** The page whose readers run the CLI they installed for their computer. */+export const GLOBAL_PAGE = 'global';diff --git a/apps/docsite/src/__tests__/code-linkifiers.test.ts b/apps/docsite/src/__tests__/code-linkifiers.test.tsindex de53c4bb4a..f243e92f86 100644--- a/apps/docsite/src/__tests__/code-linkifiers.test.ts+++ b/apps/docsite/src/__tests__/code-linkifiers.test.ts@@ -16,6 +16,8 @@ describe('doc topic linkifier', () => {['astryx docs tokens', '/docs/tokens'],['astryx docs styling-libraries', '/docs/styling-libraries'],['npx astryx docs icons', '/docs/icons'],+ ['npx @astryxdesign/cli docs icons', '/docs/icons'],+ ['npx @astryxdesign/[email protected] docs global', '/docs/global'],[' astryx docs theme ', '/docs/theme'],// The docs index, for a bare command.['astryx docs', '/docs'],diff --git a/apps/docsite/src/__tests__/docs-pages.test.ts b/apps/docsite/src/__tests__/docs-pages.test.tsindex 97157e5950..850be9b309 100644--- a/apps/docsite/src/__tests__/docs-pages.test.ts+++ b/apps/docsite/src/__tests__/docs-pages.test.ts@@ -6,9 +6,10 @@ import {namespaceCategory,namespacePage,sectionAnchors,+ withCliCommands,} from '../../scripts/docs-pages.mjs';import {buildOutline} from '../components/docs/docOutline';-import type {DocSection} from '../generated/docsRegistry';+import {docTopics, type DocSection} from '../generated/docsRegistry';const section = (title: string, text = `${title} text.`) => ({title,@@ -269,3 +270,44 @@ describe('sectionAnchors', () => {);});});++describe('CLI commands on docsite pages', () => {+ it('prefixes commands in prose, lists, tables and shell code only', () => {+ const show = (text: string, lang: string | null = null) =>+ lang === 'tsx' ? text : text.replaceAll('`astryx', '`npx astryx');+ const [shown] = withCliCommands(+ [+ {+ title: 'Run it',+ content: [+ {type: 'prose', text: 'Run `astryx docs`.'},+ {type: 'list', items: ['`astryx doctor`']},+ {type: 'table', rows: [['Neutral', 'astryx theme add neutral']]},+ {type: 'code', lang: 'tsx', code: '`astryx docs`'},+ ],+ },+ ],+ show,+ 'npx astryx',+ );+ expect(shown.content).toEqual([+ {type: 'prose', text: 'Run `npx astryx docs`.'},+ {type: 'list', items: ['`npx astryx doctor`']},+ {type: 'table', rows: [['Neutral', 'npx astryx theme add neutral']]},+ {type: 'code', lang: 'tsx', code: '`astryx docs`'},+ ]);+ });++ it('shows the CLI Integrations page a command that runs before any install', () => {+ const page = docTopics.find(topic => topic.topic === 'cli-integrations');+ const section = page?.sections.find(+ each => each.title === 'Verify the packed import',+ );+ expect(section?.content).toContainEqual(+ expect.objectContaining({+ type: 'code',+ code: 'npx @astryxdesign/cli integration verify',+ }),+ );+ });+});diff --git a/apps/docsite/src/__tests__/route-resolution.test.ts b/apps/docsite/src/__tests__/route-resolution.test.tsindex 64762df889..9614e84b31 100644--- a/apps/docsite/src/__tests__/route-resolution.test.ts+++ b/apps/docsite/src/__tests__/route-resolution.test.ts@@ -91,7 +91,7 @@ describe('route resolution', () => {it('lists the guides the sidebar listed before the splits, plus new topics only', () => {// The Guide section as it was before the CLI integration guide and the// other topics were split into short guides. `styling-overview` is a- // topic added since.+ // topic added since; `global` is the Global mode page.const sidebarGuides = docTopics.filter(d => d.category === 'guide' && d.topic !== 'getting-started').map(d => d.topic)@@ -103,6 +103,7 @@ describe('route resolution', () => {'cli-component-lookups','cli-integrations','cli-writing-docs',+ 'global','internationalization','layout','migration',@@ -130,6 +131,45 @@ describe('route resolution', () => {);});+ it('shows global mode as one page under Guide, with its older slugs redirecting to it', () => {+ expect(docTopics.find(d => d.topic === 'global')?.category).toBe('guide');+ expect(pageBySlug.has('global')).toBe(true);+ expect(pageBySlug.has('cli-global')).toBe(false);+ expect(docRedirects['cli-global']).toBe('/docs/global');+ expect(docRedirects['cli-install-once']).toBe('/docs/global');+ for (const route of docsTreeRoutes) {+ if (!route.startsWith('global/')) continue;+ const slug = route.replaceAll('/', '-');+ expect(docRedirects[slug], slug).toMatch(/^\/docs\/global#/);+ }+ });++ it('introduces global mode in Getting Started and links its page', () => {+ const start = pageBySlug.get('getting-started')!;+ const section = start.sections.find(+ s => s.title === 'Install once, use everywhere',+ );+ expect(section).toBeDefined();+ const text = JSON.stringify(section);+ expect(text).toContain('npm i -g @astryxdesign/cli');+ // Its link to the global mode page renders as a command that opens it.+ expect(text).toContain('`npx @astryxdesign/cli docs global`');+ expect(linkifyCode('npx @astryxdesign/cli docs global')).toBe(+ '/docs/global',+ );+ });++ it('shows commands that reach the CLI: npx @astryxdesign/cli, and plain astryx on the global mode page', () => {+ const textOf = (topic: (typeof docTopics)[number]) =>+ JSON.stringify(topic.sections);+ const global = textOf(pageBySlug.get('global')!);+ expect(global).toContain('`astryx docs global/');+ expect(global).not.toContain('npx @astryxdesign/cli docs');+ expect(textOf(pageBySlug.get('getting-started')!)).toContain(+ 'npx @astryxdesign/cli',+ );+ });+it('keeps /docs/cli the CLI package page', () => {expect(pageBySlug.has('cli')).toBe(false);expect(packages.some(pkg => pkg.name === '@astryxdesign/cli')).toBe(true);diff --git a/apps/docsite/src/components/codeLinkifiers.ts b/apps/docsite/src/components/codeLinkifiers.tsindex 90ca3c3f9c..ddf52f1919 100644--- a/apps/docsite/src/components/codeLinkifiers.ts+++ b/apps/docsite/src/components/codeLinkifiers.ts@@ -36,7 +36,7 @@ const KNOWN_TOPICS = new Set(docTopics.map(d => d.topic));*/const docTopic: CodeLinkifier = code => {const match =- /^(?:npx )?astryx docs(?:\s+([a-z][\w-]*(?:\/[a-z][\w-]*)*))?(?:\s.*)?$/.exec(+ /^(?:npx (?:@astryxdesign\/cli(?:@\S+)?|astryx)|astryx) docs(?:\s+([a-z][\w-]*(?:\/[a-z][\w-]*)*))?(?:\s.*)?$/.exec(code,);if (!match) {diff --git a/docs/contributing/cli-conventions.md b/docs/contributing/cli-conventions.mdindex 64db1c8ee0..3cd83b6127 100644--- a/docs/contributing/cli-conventions.md+++ b/docs/contributing/cli-conventions.md@@ -164,6 +164,38 @@ manifest are generated from it, so an undocumented flag is an invisible flag.Give at least one example that an agent would actually run, including a `--json`one.+## Global mode: every command works outside a project++People install the CLI once for their computer and run it in any folder+(`spec:AST-081`). So every command also has to work, or explain itself, in a+folder that is not a project, and its docs have to say which.++1. **Declare `outsideProject`** in the command doc: `same` (it answers as it+ would in a new project), `refuse` (it writes nothing and fails before doing+ any work, naming what it needs), or `own` (it does something else). A+ command that only groups subcommands declares nothing.+ `clients/cli/commands/outside-project.test.mjs` runs every command in an+ empty folder and checks what it does against this value, and fails on a+ command without one; an `own` command needs a test of its own there.+2. **Add the note, for readers.** Every `refuse` and every `own` command+ carries one prose note that starts `In global mode:`, says exactly what it+ does outside a project (the error code and message it stops with, or what+ it does instead), and links `{@link namespace:global}`.+ `test/global-mode-notes.test.mjs` fails on a missing note, and+ `test/global-mode-docs.test.mjs` checks that the error code a note names is+ the one the command stops with. An API function whose result depends on+ `cwd` being in a project carries the same sentence in its description.+3. **Add a who-answers row** when a change touches which copy of the CLI+ answers (an install layout, a door, a hand-off rule): one row in the global+ and project table of `spec:AST-081` and its test in+ `packages/cli/test/global-local.test.mjs`, named with the row's number+ (`G12 …`); a test there fails on a gap in the row numbers.+4. **Quote, never paraphrase, what the CLI prints.** A terminal line shown on a+ global-mode page must be one the CLI prints; `test/global-mode-docs.test.mjs`+ builds those lines from the CLI's own strings.++The user-facing explanation lives in `astryx docs global`.+## Every integration item ships a typed docA discoverable contribution is not done without a strongly typed@@ -222,6 +254,9 @@ change.- [ ] The doc declares `outsideProject` (`same`, `refuse`, or `own`), and a testrun outside a project matches it.- [ ] Marked as work in progress if it is not ready to be depended on.+- [ ] The command doc declares `outsideProject`; a value other than `same`+ has its `In global mode:` note and a test of what it does outside a+ project.## Common review smellsdiff --git a/packages/cli/README.md b/packages/cli/README.mdindex 63d1454eea..c65bb73985 100644--- a/packages/cli/README.md+++ b/packages/cli/README.md@@ -13,7 +13,19 @@ npx @astryxdesign/cli docs migrationnpx @astryxdesign/cli template --list```-Once it's a project dependency (`npm install -D @astryxdesign/cli`), drop the scope and use the shorter `astryx` — e.g. `npx astryx component Button` or `pnpm exec astryx component Button`. Bare `astryx` resolves to an unrelated npm package until the CLI is installed, so prefer the scoped form above for first-run/one-off use.+Once it's a project dependency (`npm install -D @astryxdesign/cli`), the same scoped commands run the version you installed, or use your package manager's runner with the shorter name, such as `pnpm exec astryx component Button`. Never run the unscoped name through npx before the CLI is installed: `astryx` alone resolves to an unrelated npm package.++## Install it once for your computer++```bash+npm i -g @astryxdesign/cli+```++Then `astryx` works in any folder, for you and for every coding agent on your computer. In a project, Astryx runs the project's own version, so a global install never changes what a project gets; outside a project, your global version answers. It tells you when a newer version is out, and never upgrades itself or a project.++- Project install, global install, or both (recommended)? `astryx docs global/project-global-or-both` compares them.+- How it works, and what it prints: `astryx docs global`.+- Something looks wrong: `astryx docs global/problems`. Uninstall: `astryx docs global/uninstall`.## Reading the CLI's own docs@@ -65,7 +77,7 @@ Results for "button" (20 of 239):→ astryx template BannerCollapsibleContent```-(The CLI prints the follow-up commands with your actual runner — `npx astryx …` when installed, or `npx @astryxdesign/cli …` when run one-off.)+(The CLI prints the follow-up commands so they reach the release that answered — the project's runner, such as `pnpm exec astryx …`, when the project's own CLI answered, `astryx …` outside a project for the copy installed for your computer, or the package pinned to the answering release, such as `npx @astryxdesign/[email protected] …`, otherwise — or with the command an installed integration sets as its `cliCommand`.)Options:@@ -76,25 +88,27 @@ Options:## Commands+Each command declares what it does in a folder outside any project, and `astryx manifest --json` publishes it as `outsideProject`: `same` gives the answer a new project on this release would get, `refuse` writes nothing and fails with `ERR_PROJECT_REQUIRED` (or the code its earlier releases used), and `own` does something else that its docs (`astryx docs cli/commands/<name>`) describe.+<!-- BEGIN GENERATED: commands -->-| Command | Description |-| ------------- | ----------------------------------------------------------------------------- |-| `blog` | Read the Astryx blog from the published feed |-| `build` | Build a page: the template to start from, or the workflow playbook (no query) |-| `component` | List components or print component docs |-| `discover` | Browse and search integrations: the ones you have and the ones you could add |-| `docs` | Print reference docs |-| `doctor` | Diagnose Astryx projects and integration packages |-| `gap-report` | Report a missing component or feature to the package that owns it |-| `hook` | List hooks or print hook docs |-| `init` | Initialize the design system in your project |-| `integration` | Author and verify an Astryx integration package |-| `search` | Search components, hooks, docs, templates, and themes in one ranked list |-| `swizzle` | Copy component source for customization |-| `template` | List, show, or scaffold page and block templates |-| `theme` | Add, switch, build, and author themes |-| `upgrade` | Update your code after upgrading Astryx, and refresh ShadCN-copied components |+| Command | Description | Outside a project |+| ------------- | ----------------------------------------------------------------------------- | ----------------- |+| `blog` | Read the Astryx blog from the published feed | `same` |+| `build` | Build a page: the template to start from, or the workflow playbook (no query) | `same` |+| `component` | List components or print component docs | `same` |+| `discover` | Browse and search integrations: the ones you have and the ones you could add | `same` |+| `docs` | Print reference docs | `same` |+| `doctor` | Diagnose Astryx projects and integration packages | `own` |+| `gap-report` | Report a missing component or feature to the package that owns it | `same` |+| `hook` | List hooks or print hook docs | `same` |+| `init` | Initialize the design system in your project | `own` |+| `integration` | Author and verify an Astryx integration package | by subcommand |+| `search` | Search components, hooks, docs, templates, and themes in one ranked list | `same` |+| `swizzle` | Copy component source for customization | `refuse` |+| `template` | List, show, or scaffold page and block templates | `same` |+| `theme` | Add, switch, build, and author themes | by subcommand |+| `upgrade` | Update your code after upgrading Astryx, and refresh ShadCN-copied components | `own` |<!-- END GENERATED: commands --><!-- Generated by scripts/generate-cli-readme.mjs from `astryx manifest`. Run `pnpm -F @astryxdesign/cli readme`. -->@@ -114,9 +128,11 @@ Options:Every command supports `--json` for machine-readable output. Responses are typed envelopes:```json-{"apiVersion": 1, "type": "component.detail", "data": {"name": "Button", ...}}+{"apiVersion": 1, "type": "component.detail", "data": {"name": "Button", ...}, "meta": {"answeredBy": {"cli": "0.7.2", "core": "0.7.2", "copy": "project"}}}```+Every successful envelope carries `meta.answeredBy`: the CLI version that answered, the Core version it paired with (`null` when there is none), and which copy answered (`project`, `starting`, `matched`, `carried`, or `fallback`).+Errors:```json@@ -159,60 +175,62 @@ if (isError(result)) {<!-- BEGIN GENERATED: error-codes -->-| Code | Meaning |-| --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `ERR_UNKNOWN` | Fallback for any error without a more specific code. |-| `ERR_UNKNOWN_COMMAND` | A top-level command name was not recognized (e.g. `astryx bogus`). |-| `ERR_UNKNOWN_SUBCOMMAND` | A subcommand under a command group was not recognized (e.g. `astryx theme bogus`). |-| `ERR_INVALID_OPTION` | An unknown option was passed, --json was given to a command without JSON output. |-| `ERR_INVALID_ARGUMENT` | An argument or option value is invalid: wrong type, out of range, an unknown choice, an extra argument, or a conflicting combination. |-| `ERR_MISSING_ARGUMENT` | A required argument or option value was omitted. |-| `ERR_INVALID_LANG` | `--lang` was given a value outside its choices (en, zh, dense). |-| `ERR_INVALID_DETAIL` | `--detail` was given a value outside its choices (full, compact, brief). |-| `ERR_NODE_VERSION` | The running Node.js version is below the supported minimum. |-| `ERR_CORE_NOT_FOUND` | `@astryxdesign/core` could not be located (not installed / not in a monorepo). |-| `ERR_CORE_INCOMPATIBLE` | The installed `@astryxdesign/core` loaded but is too old for this input — it lacks a capability the CLI must call to emit correct output (upgrade core). |-| `ERR_UNKNOWN_COMPONENT` | No component matched the requested name. |-| `ERR_UNKNOWN_HOOK` | No hook matched the requested name. |-| `ERR_UNKNOWN_TOPIC` | No docs topic matched the requested name. |-| `ERR_UNKNOWN_SECTION` | A docs topic exists but the requested section within it does not. |-| `ERR_UNKNOWN_CATEGORY` | A `--category` filter value did not match any known category. |-| `ERR_UNKNOWN_TEMPLATE` | No template matched the requested name. |-| `ERR_AMBIGUOUS_TEMPLATE` | A template id matched more than one template (narrow with --type/--package). |-| `ERR_AMBIGUOUS_COMPONENT` | A component name is owned by more than one package (narrow with --package). |-| `ERR_AMBIGUOUS_THEME` | A theme slug is owned by more than one package (narrow with --package). |-| `ERR_UNKNOWN_THEME` | No theme matched the requested slug (theme add). |-| `ERR_INTEGRATION_ROOT_CONFLICT` | An integration manifest already declares a different path for the requested contribution root. |-| `ERR_INTEGRATION_EXPORT_CONFLICT` | A package export already maps a generated contribution subpath to a different target. |-| `ERR_UNKNOWN_PACKAGE` | No package matched the requested name. |-| `ERR_UNKNOWN_AGENT` | An unrecognized `--agent` value was passed to init. |-| `ERR_UNKNOWN_FEATURE` | An unrecognized `--features` value was passed to init. |-| `ERR_UNKNOWN_CODEMOD` | A `--codemod` value did not match any registered codemod (upgrade). |-| `ERR_CODEMOD_FAILED` | One or more codemods failed during an upgrade run. |-| `ERR_CODEMOD_PROTECTED` | A required codemod change remains blocked by a protected consumer file. |-| `ERR_CODEMOD_PROTECTION_SOURCE` | A working-tree protection declaration could not be read or parsed. |-| `ERR_NOT_FOUND` | A generic discover/lookup query matched nothing in any package. |-| `ERR_NO_DOC` | A component exists but has no typed `.doc.mjs` file. |-| `ERR_NO_SHOWCASE` | No showcase exists for the requested component. |-| `ERR_NO_SOURCE` | No source file could be located for the requested component/template. |-| `ERR_INVALID_DOC` | A component's docs failed validation (malformed `.doc.mjs`). |-| `ERR_FILE_NOT_FOUND` | A required input file did not exist. |-| `ERR_FILE_EXISTS` | Refused to overwrite an existing file. |-| `ERR_PATH_TRAVERSAL` | A path escaped its allowed root, or a name contained traversal markers. |-| `ERR_WRITE_FAILED` | Writing output files failed (and was rolled back). |-| `ERR_THEME_INVALID` | A theme definition or contributed theme descriptor is invalid. |-| `ERR_THEME_LOAD` | A theme file could not be loaded / parsed into a defineTheme result. |-| `ERR_PALETTE_GENERATION` | A palette generation request or one of its constraints was invalid. |-| `ERR_VERSION_DETECT` | The current `@astryxdesign/core` version could not be detected. |-| `ERR_INVALID_VERSION` | A `--from`/`--to` value was not a valid semver string. |-| `ERR_DEP_MISSING` | A required external dependency (e.g. jscodeshift) is missing. |-| `ERR_GH_CLI` | GitHub CLI (`gh`) is not installed or not authenticated. |-| `ERR_UNKNOWN_POST` | No blog post matched the requested slug in the feed. |-| `ERR_FETCH_FAILED` | A network fetch (RSS feed or post text) failed. |-| `ERR_LAYOUT_PARSE` | A layout expression failed to parse (syntax error, with line/col). |-| `ERR_LAYOUT_INVALID` | A layout expression parsed but failed validation (unknown component/prop/enum/block). |-| `ERR_UNCLASSIFIED_EXIT` | Recorded in the debug log, never printed: a command exited non-zero without reporting an error code. |-| `ERR_SIGNAL_TERMINATED` | Recorded in the debug log, never printed: the process was ended by a signal (Ctrl-C, SIGTERM) before the command reached a terminal path. |+| Code | Meaning |+| --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `ERR_UNKNOWN` | Fallback for any error without a more specific code. |+| `ERR_UNKNOWN_COMMAND` | A top-level command name was not recognized (e.g. `astryx bogus`). |+| `ERR_UNKNOWN_SUBCOMMAND` | A subcommand under a command group was not recognized (e.g. `astryx theme bogus`). |+| `ERR_INVALID_OPTION` | An unknown option was passed, --json was given to a command without JSON output. |+| `ERR_INVALID_ARGUMENT` | An argument or option value is invalid: wrong type, out of range, an unknown choice, an extra argument, or a conflicting combination. |+| `ERR_MISSING_ARGUMENT` | A required argument or option value was omitted. |+| `ERR_INVALID_LANG` | `--lang` was given a value outside its choices (en, zh, dense). |+| `ERR_INVALID_DETAIL` | `--detail` was given a value outside its choices (full, compact, brief). |+| `ERR_NODE_VERSION` | The running Node.js version is below the supported minimum. |+| `ERR_CORE_NOT_FOUND` | `@astryxdesign/core` could not be located (not installed / not in a monorepo). |+| `ERR_CORE_INCOMPATIBLE` | The installed `@astryxdesign/core` loaded but is too old for this input — it lacks a capability the CLI must call to emit correct output (upgrade core). |+| `ERR_UNKNOWN_COMPONENT` | No component matched the requested name. |+| `ERR_UNKNOWN_HOOK` | No hook matched the requested name. |+| `ERR_UNKNOWN_TOPIC` | No docs topic matched the requested name. |+| `ERR_UNKNOWN_SECTION` | A docs topic exists but the requested section within it does not. |+| `ERR_UNKNOWN_CATEGORY` | A `--category` filter value did not match any known category. |+| `ERR_UNKNOWN_TEMPLATE` | No template matched the requested name. |+| `ERR_AMBIGUOUS_TEMPLATE` | A template id matched more than one template (narrow with --type/--package). |+| `ERR_AMBIGUOUS_COMPONENT` | A component name is owned by more than one package (narrow with --package). |+| `ERR_AMBIGUOUS_THEME` | A theme slug is owned by more than one package (narrow with --package). |+| `ERR_UNKNOWN_THEME` | No theme matched the requested slug (theme add). |+| `ERR_INTEGRATION_ROOT_CONFLICT` | An integration manifest already declares a different path for the requested contribution root. |+| `ERR_INTEGRATION_EXPORT_CONFLICT` | A package export already maps a generated contribution subpath to a different target. |+| `ERR_UNKNOWN_PACKAGE` | No package matched the requested name. |+| `ERR_UNKNOWN_AGENT` | An unrecognized `--agent` value was passed to init. |+| `ERR_UNKNOWN_FEATURE` | An unrecognized `--features` value was passed to init. |+| `ERR_UNKNOWN_CODEMOD` | A `--codemod` value did not match any registered codemod (upgrade). |+| `ERR_CODEMOD_FAILED` | One or more codemods failed during an upgrade run. |+| `ERR_CODEMOD_PROTECTED` | A required codemod change remains blocked by a protected consumer file. |+| `ERR_CODEMOD_PROTECTION_SOURCE` | A working-tree protection declaration could not be read or parsed. |+| `ERR_NOT_FOUND` | A generic discover/lookup query matched nothing in any package. |+| `ERR_NO_DOC` | A component exists but has no typed `.doc.mjs` file. |+| `ERR_NO_SHOWCASE` | No showcase exists for the requested component. |+| `ERR_NO_SOURCE` | No source file could be located for the requested component/template. |+| `ERR_INVALID_DOC` | A component's docs failed validation (malformed `.doc.mjs`). |+| `ERR_FILE_NOT_FOUND` | A required input file did not exist. |+| `ERR_FILE_EXISTS` | Refused to overwrite an existing file. |+| `ERR_PATH_TRAVERSAL` | A path escaped its allowed root, or a name contained traversal markers. |+| `ERR_WRITE_FAILED` | Writing output files failed (and was rolled back). |+| `ERR_THEME_INVALID` | A theme definition or contributed theme descriptor is invalid. |+| `ERR_THEME_LOAD` | A theme file could not be loaded / parsed into a defineTheme result. |+| `ERR_PALETTE_GENERATION` | A palette generation request or one of its constraints was invalid. |+| `ERR_VERSION_DETECT` | The current `@astryxdesign/core` version could not be detected. |+| `ERR_INVALID_VERSION` | A `--from`/`--to` value was not a valid semver string. |+| `ERR_DEP_MISSING` | A required external dependency (e.g. jscodeshift) is missing. |+| `ERR_GH_CLI` | GitHub CLI (`gh`) is not installed or not authenticated. |+| `ERR_UNKNOWN_POST` | No blog post matched the requested slug in the feed. |+| `ERR_FETCH_FAILED` | A network fetch (RSS feed or post text) failed. |+| `ERR_LAYOUT_PARSE` | A layout expression failed to parse (syntax error, with line/col). |+| `ERR_LAYOUT_INVALID` | A layout expression parsed but failed validation (unknown component/prop/enum/block). |+| `ERR_UNCLASSIFIED_EXIT` | Recorded in the debug log, never printed: a command exited non-zero without reporting an error code. |+| `ERR_SIGNAL_TERMINATED` | Recorded in the debug log, never printed: the process was ended by a signal (Ctrl-C, SIGTERM) before the command reached a terminal path. |+| `ERR_VERSIONS_UNAVAILABLE` | Nothing could answer this run, and nothing was written: the project's own CLI could not start and nothing else could answer, or the Core a command needs outside a project could not be installed. |+| `ERR_PROJECT_REQUIRED` | The command needs a project (an app with Astryx installed, or an integration package) and was run outside one. Nothing was written. |<!-- END GENERATED: error-codes --><!-- Generated by scripts/generate-cli-readme.mjs from the error-codes EnumDoc (== ERROR_CODES). Run `pnpm -F @astryxdesign/cli readme`. -->@@ -423,6 +441,7 @@ Every response has a `type` discriminant. The full set is below (generated from| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ || `init.run` | The install receipt: the `mode` (`default` \| `features`), the features run, agent-doc files written, any soft `docsError`, whether theme guidance was emitted, the template outcome (`workflow` \| `created` \| `skipped`) plus its path, and whether the next-steps were emitted. || `init.remove` | The removal receipt — returned when --remove-agents is set: `data.removed` is true when a managed agent-docs block was found and removed, and false when there was none to remove. |+| `init.user` | The computer-level agent text receipt — returned when --user is set: `data.files`, one `{path, action, reason?}` per path acted on, the skill file first and then each link to its folder (action `written` \| `linked` \| `unchanged` \| `removed` \| `absent` \| `kept`; `reason` only on `kept`: `edited` when a person changed the text, `not-astryx` when Astryx did not write it), `data.command` (the command the text names), and `data.warnings`. || `component.list` | The component catalog grouped by component group (each component's group field): `detail` (the level: names \| compact \| full) and `components`, the grouped map of names entries ({name, package, and optional canonical import for integrations}), brief entries ({name, package, description, import}), or a full ComponentDoc per entry with its package. || `component.batch` | The component specialization of the shared `BatchResponse` and `BatchRow` types. An explicit programmatic selector array, or two or more CLI selectors, returns one ordered receipt: `count` plus `results`, one row per selector including duplicates. Every row carries `selector` and `status` (found \| not_found \| ambiguous \| error). A found row carries `result`, the same {type, data} response as one selector. An ambiguous row carries `code`, `error`, and `candidates` ({package, component, kind, installed}). Other failed rows carry `code`, `error`, and optional `suggestions` ({name, reason}). || `component.detail` | One component's authored ComponentDoc plus ownership fields (package, the owner; import, the specifier; sourceAvailable, whether source exists) and parentDoc (present when the component is documented inside another component's doc, naming that doc). The envelope's package names the same owner. |@@ -442,7 +461,7 @@ Every response has a `type` discriminant. The full set is below (generated from| `discover.detail.doc` | The validated ComponentDoc for one installed component, for an @scope/name/Component query. || `discover.item` | One item that is not an installed component, for an @scope/name/<item> query: its kind, name, package, version, and whether the project has the package. || `discover.search` | The echoed query plus every matching item and package across all packages, each with its kind and whether the project has it, even when only one matches; total is set when --limit cut the list. |-| `search` | The echoed query, `matchCount` (total matches, before `limit`), and results, a ranked SearchResultEntry[] bounded by `limit`: each {domain, name, package, score, reason, description, command} (package is the npm package that owns the result), plus import (components, hooks), title, parent (the command that opens the level above), and, for a hit on one section, section (docs), or displayName and kind (templates). |+| `search` | The echoed query, `matchCount` (total matches, before `limit`), and results, a ranked SearchResultEntry[] bounded by `limit`: each {domain, name, package, score, reason, description, command} (package is the npm package that owns the result), plus import (components, hooks), title, parent (the command that opens the level above), and, for a hit on one section, section (docs), or displayName and kind (templates). When a search with no `type` could not obtain @astryxdesign/core, `meta.partial` is {skipped, reason}: the domains it skipped (component, hook, template) and why. || `build.help` | The how-to-build-a-page playbook, emitted when no query is given: `playbook: true`, a title, the ordered steps (title, commands, optional returns), the on-system rules, and related lookups. Commands are bare subcommands for the caller to render with its own invocation. || `build.kit` | The template to start from and its kit: query, hasResults, matchCount (never a cap), directMatch, start {name, package, command, basis, reason, alternatives, ...} (the start and each alternative name the package that owns the template), pages (search's closest templates), blocks and domain as SearchResultEntry[] (each naming its package), frame and foundation (Core component names), and hint {reason, commands} when thin. || `swizzle.list` | The names of swizzlable components discoverable from cwd's @astryxdesign/core. The envelope's package is @astryxdesign/core. |@@ -470,13 +489,13 @@ Every response has a `type` discriminant. The full set is below (generated from| `upgrade.registry` | The copied-composition receipt for --registry: applied, ok, the counts (found, current, wouldUpdate, updated, wouldMerge, merged, wouldRefreshReceipt, receiptsRefreshed, conflicts, missing, invalid, failed), and items. || `upgrade.status` | A short-circuit outcome with no codemods run (up_to_date, no_codemods, or config_fixable), each carrying the agent-docs summary. no_codemods and config_fixable carry cliBehindCore ({cliVersion, command}) when the installed Core is newer than the CLI, which then has no codemods for the releases after its own version. || `upgrade.run` | The run receipt: from/to versions, codemod count, integrations processed, the agent-docs summary, sourcePathFound (false when the resolved source directory does not exist, so no source file was read), and (apply mode) filesChanged, transformsApplied, and per-codemod errors. When the installed Core is newer than the CLI, it also carries cliBehindCore ({cliVersion, command}): codemods for the releases after cliVersion did not run. |-| `manifest` | The CLI capability manifest: name, version, apiVersion, description, globalOptions, commands (each name, description, arguments, options, json, aliases?, responseTypes?, examples?, exitCodes? as [{code, when}], subcommands?), jsonSupported, and the flat responseTypes index. |+| `manifest` | The CLI capability manifest: name, version, apiVersion, description, globalOptions, commands (each name, description, arguments, options, json, aliases?, responseTypes?, examples?, exitCodes? as [{code, when}], outsideProject? (same, refuse, or own; absent on a group), subcommands?), jsonSupported, globalMode ({docs, summary}: what a run may do beyond its command, such as the hand-off to the project's own CLI, the daily update check, and the agent skill file, and the docs topic that explains it), and the flat responseTypes index. || `help` | Help, in one of two shapes. A bare `astryx --json` returns the root manifest: name, version, commands (the command names), jsonSupported, and manifest (the full payload `astryx manifest --json` returns). `--help --json` on any command, or `astryx help [command] --json`, returns that command's help: command, description, usage, options (each flags, description, and defaultValue and choices when set), and subcommands (each name and description). data.manifest marks the first shape; data.usage marks the second. || `version` | The CLI version, for `astryx --version --json`: {version}. || `doctor` | The health-check report: `checks` (each with id, label, status: pass \| warn \| fail \| info, a message, and an optional fix, always present on warn and fail) plus a `summary` of counts per status. || `integration.add` | A contribution-writer receipt: kind, name, optional root {path, created}, integration-manifest path, every affected project-relative path, written, and dryRun. || `integration.pack-check` | The packed-package check: name, version, packable, tarball {filename, fileCount, size, unpackedSize} or null, inventory {manifest, roots [{kind, path, expectedFiles, missingFiles, complete}], expectedFiles, packedFiles}, contributions {local, packed}, each null or {themes [{slug, exportName}], components, templates [{id, type, name}], codemods [{version, id}], docs, agentDocsAppend}, and issues [{code, severity, message, fix?, file?, line?}] (the issues validation finds in the source and, prefixed packed_, in the packed tree, with the fix and the place when the check knows them). |-| `integration.validate` | The validation result: validated (false when nothing was validated: with no package.json the issues list carries one no_package error so the command exits 1, and with a package.json but no integration manifest the issues list is empty and proves nothing), the package name and version (both null when validated is false) plus issues, an AstryxIntegrationIssue[] of {code, severity: warning \| error, message, fix?, file?, line?} (fix: the change that resolves it; file and line: where, relative to the package). When the manifest loads, docTypes checks each doc against its published authoring type: status (checked \| skipped), reason, typescript, docs, findings (all warnings, each naming the field and a fix), unchecked, and fixtures (test fixture docs not checked). |+| `integration.validate` | The validation result: validated (false when nothing was validated: with no package.json the issues list carries one no_package error so the command exits 1, and with a package.json but no integration manifest the issues list is empty and proves nothing), the package name and version (both null when validated is false) plus issues, an AstryxIntegrationIssue[] of {code, severity: warning \| error, message, fix?, file?, line?} (fix: the change that resolves it; file and line: where, relative to the package), and notes when there are any: {code, message} information that fails nothing, such as invalid_cli_command for a malformed cliCommand. When the manifest loads, docTypes checks each doc against its published authoring type: status (checked \| skipped), reason, typescript, docs, findings (all warnings, each naming the field and a fix), unchecked, and fixtures (test fixture docs not checked). || `integration.template-conflicts` | validated (false when no integration manifest was found, so nothing was inspected), the integration identity, structural issues, and non-blocking Core template-id conflicts as {id, severity: warning, integrationPackage, integrationType, integrationName, coreMatches, message, command}. || `integration.component-conflicts` | validated (false when no integration manifest was found, so nothing was inspected), the integration identity, structural issues, and non-blocking conflicts where an integration component name is also owned by Core; each conflict includes the exact package-qualified command. When the manifest loads and declares a components root, propDrift compares documented props with the TypeScript props: status (checked \| skipped), reason, typescript, components, typesCompared, typesSkipped, findings (all warnings; a default_mismatch carries docDefault, codeDefault, and a fix), unchecked, typesNotCompared, and propsNotChecked. || `integration.doc-conflicts` | validated (false when no integration manifest was found, so nothing was inspected), the integration identity, structural issues, and Core doc overlaps. Each finding includes `severity` (`info` \| `error`) and `relationship` (`replaces` \| `extends` \| `accidental`). copiedPassages lists each pair of topics that repeat 10 or more words of prose word for word: topic, section, otherTopic, otherOwner (package \| core), words, passages, owner (the topic that should keep the text), text (the passage as the topic writes it), line (where the copy starts in the topic to change, or null), and message (the exact replacement); each is also a copied_passage warning in issues. fluff lists padding phrases and low-density topics: topic, kind (phrase \| density), phrase, section, file (relative to the package root), line, density, and message (what to cut or write instead); each is also a doc_fluff warning in issues. strayPointers lists each code span that is exactly `astryx docs <name>` for a doc that exists, in the prose, description or summary of a topic or the text fields of a component doc: topic (the topic or component doc), kind (topic \| component), section, field (the field outside any section, such as description or usage.bestPractices[0].description, else null), file (relative to the package root), line, pointer (the written command), link (the {@link} that replaces it), and message; each is also a stray_doc_pointer warning in issues. |@@ -653,13 +672,14 @@ export default {};```-| Field | Type | Purpose |-| ------------ | -------- | --------------------------------------------------------------------------------- |-| `components` | `string` | Directory holding the package's components and their `.doc.*` files. |-| `templates` | `string` | Directory holding the package's page/block templates. |-| `codemods` | `string` | Directory holding upgrade codemods run by `astryx upgrade`. |-| `docs` | `string` | Directory of reference docs; each `{topic}.doc.*` becomes a topic the CLI serves. |-| `issuesUrl` | `string` | Where "report an issue" links for this package's contributions point. |+| Field | Type | Purpose |+| ------------ | -------- | ----------------------------------------------------------------------------------------------------------- |+| `components` | `string` | Directory holding the package's components and their `.doc.*` files. |+| `templates` | `string` | Directory holding the package's page/block templates. |+| `codemods` | `string` | Directory holding upgrade codemods run by `astryx upgrade`. |+| `docs` | `string` | Directory of reference docs; each `{topic}.doc.*` becomes a topic the CLI serves. |+| `issuesUrl` | `string` | Where "report an issue" links for this package's contributions point. |+| `cliCommand` | `string` | The command its users run the CLI with, such as `acme astryx`; every command the CLI prints starts with it. |Every field is optional; declare only the roots the package ships. There is nofactory: write a plain object, and annotate it with the `AstryxIntegration` typediff --git a/packages/cli/api/build/_adapter.mjs b/packages/cli/api/build/_adapter.mjsindex c1b03e20f1..c7ae38aad5 100644--- a/packages/cli/api/build/_adapter.mjs+++ b/packages/cli/api/build/_adapter.mjs@@ -20,7 +20,7 @@ import fs from 'node:fs';import {discoverTemplates} from '../template/template.mjs';import {componentKeywords} from '../search/search.mjs';-import {findCoreDir} from '../../foundation/fs/paths.mjs';+import {findCoreDir, requireCoreDir} from '../../foundation/fs/paths.mjs';import {analyzeTemplateNeeds} from '../../foundation/discovery/template-needs.mjs';/**@@ -177,3 +177,14 @@ export function templateSetupNotes(template, cwd) {return [];}}++/**+ * The Core a build answers from: the project's, else the release's own,+ * installed into the per-user cache first when needed (a network install+ * and an npm subprocess; spec AST-081 FR3). Throws as requireCoreDir does.+ * @param {string} cwd+ * @returns {string}+ */+export function requireBuildCoreDir(cwd) {+ return requireCoreDir(cwd);+}diff --git a/packages/cli/api/build/build.doc.mjs b/packages/cli/api/build/build.doc.mjsindex 03decf67b8..d11ba5de40 100644--- a/packages/cli/api/build/build.doc.mjs+++ b/packages/cli/api/build/build.doc.mjs@@ -76,6 +76,10 @@ export const doc = {code: 'ERR_CORE_NOT_FOUND',when: 'a query is given and @astryxdesign/core cannot be found from cwd',},+ {+ code: 'ERR_VERSIONS_UNAVAILABLE',+ when: 'a query is given outside a project, or in a project with nothing installed, and the Core of the release that answers is not beside it or cached, and cannot be installed into the per-user cache (offline, a registry without it, or an unwritable cache)',+ },],examples: [{label: 'Get the playbook', code: 'const r = await build();'},diff --git a/packages/cli/api/build/kit/kit.mjs b/packages/cli/api/build/kit/kit.mjsindex 3be2e2d673..00c3583594 100644--- a/packages/cli/api/build/kit/kit.mjs+++ b/packages/cli/api/build/kit/kit.mjs@@ -28,11 +28,9 @@*/import {search, searchedComponents} from '../../search/search.mjs';-import {findCoreDir} from '../../../foundation/fs/paths.mjs';-import {AstryxError} from '../../error.mjs';-import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';+import {coreDirOrThrow} from '../../error.mjs';import {getResultCoverage} from '../../search/coverage.mjs';-import {loadComponents, loadPageTemplates, loadWeights, templateSetupNotes} from '../_adapter.mjs';+import {loadComponents, loadPageTemplates, loadWeights, requireBuildCoreDir, templateSetupNotes} from '../_adapter.mjs';import {asksForNewPage,ideaKind,@@ -260,13 +258,7 @@ export async function buildKit(query, options = {}) {const {cwd = process.cwd(), type, limit = 60} = options;// A kit is built from Core's components, hooks, and templates. An open// search without core covers the docs alone, so the kit asks for core here.- if (type !== 'doc' && !findCoreDir(cwd)) {- throw new AstryxError(- 'Could not find @astryxdesign/core package',- undefined,- ERROR_CODES.ERR_CORE_NOT_FOUND,- );- }+ if (type !== 'doc') coreDirOrThrow(requireBuildCoreDir, cwd);// search()'s JSDoc @returns widens results to object[]; the SearchResponse// shape is the contract (api/search/search.type.mjs). Cast locally rather than// tightening the search @returns (a separate follow-up).diff --git a/packages/cli/api/component/_adapter.mjs b/packages/cli/api/component/_adapter.mjsindex e1fe489177..a633999ef9 100644--- a/packages/cli/api/component/_adapter.mjs+++ b/packages/cli/api/component/_adapter.mjs@@ -22,7 +22,7 @@ import * as fs from 'node:fs';import * as path from 'node:path';import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';import {- findCoreDir,+ requireCoreDir as requireAnswerCoreDir,discoverExternalPackages,} from '../../foundation/fs/paths.mjs';import {@@ -44,7 +44,7 @@ import {Project} from '../../foundation/config/project.mjs';import {loadComponentDoc as loadValidatedComponentDoc} from '../../foundation/discovery/component-loader.mjs';import {resolveComponentReplacements} from '../../foundation/discovery/component-replacement.mjs';import {searchComponents} from '../../foundation/text/string-utils.mjs';-import {AstryxError} from '../error.mjs';+import {AstryxError, coreDirOrThrow} from '../error.mjs';import {componentLinkProvider,linkComponentDoc,@@ -121,15 +121,7 @@ export {CORE_PACKAGE, unscopedComponentOwners};* @returns {string}*/export function requireCoreDir(cwd) {- const coreDir = findCoreDir(cwd);- if (!coreDir) {- throw new AstryxError(- 'Could not find @astryxdesign/core package',- undefined,- ERROR_CODES.ERR_CORE_NOT_FOUND,- );- }- return coreDir;+ return coreDirOrThrow(requireAnswerCoreDir, cwd);}/**diff --git a/packages/cli/api/component/component.doc.mjs b/packages/cli/api/component/component.doc.mjsindex 5e189fd703..0aa318195c 100644--- a/packages/cli/api/component/component.doc.mjs+++ b/packages/cli/api/component/component.doc.mjs@@ -24,7 +24,8 @@ export const doc = {'showcase, or example blocks. An integration component that replaces a Core ' +'component (its doc sets replaces, and its package declares the CLI range that ' +'turns replacement on) answers to the Core name in detail, batch, and list ' +- "results; use options.package '@astryxdesign/core' for the original.",+ "results; use options.package '@astryxdesign/core' for the original." ++ " In global mode: with `cwd` outside a project, components from integrations installed next to this CLI package globally resolve too; inside a project, only the project's own integrations count. See {@link namespace:global} and {@link generic:computer-integrations}.",importPath: '@astryxdesign/cli/api',signature:'component(name?: string | string[], options?: ComponentOptions): Promise<ComponentListResponse | ComponentBatchResponse | ComponentDetailResponse | ComponentDetailPropsResponse | ComponentDetailSourceResponse | ComponentDetailShowcaseResponse | ComponentDetailBlocksResponse>',@@ -164,6 +165,10 @@ export const doc = {code: 'ERR_CORE_NOT_FOUND',when: '@astryxdesign/core cannot be resolved from cwd',},+ {+ code: 'ERR_VERSIONS_UNAVAILABLE',+ when: 'outside a project, or in a project with nothing installed, the Core of the release that answers is not beside it or cached, and cannot be installed into the per-user cache (offline, a registry without it, or an unwritable cache)',+ },{code: 'ERR_UNKNOWN_CATEGORY',when: 'options.category is not a string or matches no component group',diff --git a/packages/cli/api/discover/_adapter.mjs b/packages/cli/api/discover/_adapter.mjsindex 6c2a184c1c..291958ab56 100644--- a/packages/cli/api/discover/_adapter.mjs+++ b/packages/cli/api/discover/_adapter.mjs@@ -19,9 +19,12 @@import {createHash} from 'node:crypto';import * as fs from 'node:fs';-import * as os from 'node:os';import * as path from 'node:path';-import {Project} from '../../foundation/config/project.mjs';+import {+ Project,+ availableComputerIntegrations,+} from '../../foundation/config/project.mjs';+import {isOutsideProject} from '../../foundation/env/project-scope.mjs';import {scanAllPackages,findComponentInPackages,@@ -31,6 +34,7 @@ import {collectIdentities} from '../../foundation/integrations/contribution-inveimport {detectPackageManager} from '../../foundation/env/package-manager.mjs';import {isValidSemver, semverCompare} from '../../foundation/env/semver.mjs';import {assertWithin} from '../../foundation/fs/path-safety.mjs';+import {userCacheDir} from '../../foundation/env/user-dirs.mjs';import {CLI_ROOT, findInstalledPackage} from '../../foundation/fs/paths.mjs';import {parseDiscoverCatalog} from '../../authoring/discover/parse.mjs';import {AstryxError} from '../error.mjs';@@ -245,6 +249,38 @@ export function hasSources(project) {);}+/** The source name of a package installed for the computer. */+const COMPUTER_SOURCE = 'installed for this computer';++/**+ * The integrations installed for the computer that a project could add, as+ * available entries with the project's install command (spec AST-081 FR12).+ * Empty outside a project, where they load instead.+ * @param {Project | undefined} project+ * @param {Array<{name: string}>} installed+ * @param {Set<string>} declared+ * @param {(name: string, version?: string) => string} add+ * @returns {Promise<import('./discover.type.mjs').DiscoverAvailableEntry[]>}+ */+export async function computerAvailableEntries(+ project,+ installed,+ declared,+ add,+) {+ const cwd = project?.cwd ?? process.cwd();+ if (isOutsideProject(cwd)) return [];+ const have = new Set([...installed.map(pkg => pkg.name), ...declared]);+ return (await availableComputerIntegrations(cwd, have)).map(c => ({+ name: c.name,+ components: [],+ ...(c.version ? {version: c.version} : {}),+ ...(c.description ? {description: c.description} : {}),+ source: COMPUTER_SOURCE,+ install: add(c.name),+ }));+}+/*** Package names the project's package.json declares in any dependency field.* @param {Project | undefined} project@@ -438,21 +474,7 @@ export function addCommand(project, {official = []} = {}) {* @returns {string}*/export function defaultCacheDir() {- const home = os.homedir();- if (process.platform === 'win32') {- return path.join(- process.env.LOCALAPPDATA || path.join(home, 'AppData', 'Local'),- 'astryx',- 'Cache',- );- }- if (process.platform === 'darwin') {- return path.join(home, 'Library', 'Caches', 'astryx');- }- return path.join(- process.env.XDG_CACHE_HOME || path.join(home, '.cache'),- 'astryx',- );+ return userCacheDir();}/**diff --git a/packages/cli/api/discover/discover.doc.mjs b/packages/cli/api/discover/discover.doc.mjsindex 84c63ac0bf..34074e9fa0 100644--- a/packages/cli/api/discover/discover.doc.mjs+++ b/packages/cli/api/discover/discover.doc.mjs@@ -21,7 +21,8 @@ export const doc = {'project and its integrations list, with what each one adds per kind. An @scope/name query shows one package with every ' +'version its source knows; @scope/name@version shows one version; @scope/name/Component returns an installed ' +"component's validated doc, and any other item path returns that item. A free-text term searches every item and " +- 'package. Discover only reads: it prints the command that adds a package and never runs it.',+ 'package. Discover only reads: it prints the command that adds a package and never runs it.' ++ " In global mode: with `cwd` outside a project, integrations installed next to this CLI package globally are listed as installed; inside a project, only the project's own are, and the compatible global ones are listed in `meta.available` with source `installed for this computer` and an `install` command. See {@link namespace:global} and {@link generic:computer-integrations}.",importPath: '@astryxdesign/cli/api',signature:'discover(query?: string, options?: DiscoverOptions): Promise<DiscoverListResponse | DiscoverDetailResponse | DiscoverDetailDocResponse | DiscoverItemResponse | DiscoverSearchResponse>',@@ -90,7 +91,7 @@ export const doc = {{type: 'discover.list',description:- 'What the project has: the integrations it loads and the official packages it declares (name, category, components, version, and a list per other kind they add), official packages first. meta.available lists what the project could add, official packages first, each with the command that adds it, and meta.sources reports each source, the official list last. When it lists no integration it carries meta.configured.',+ 'What the project has: the integrations it loads and the official packages it declares (name, category, components, version, and a list per other kind they add), official packages first. meta.available lists what the project could add, official packages first, each with the command that adds it; inside a project, an integration installed for the computer that the project does not install is listed there too, with source `installed for this computer` and the install command for the project in `install`. meta.sources reports each source, the official list last. When it lists no integration it carries meta.configured.',},{type: 'discover.detail',diff --git a/packages/cli/api/discover/discover.mjs b/packages/cli/api/discover/discover.mjsindex 9b0128bb0a..629a45fe62 100644--- a/packages/cli/api/discover/discover.mjs+++ b/packages/cli/api/discover/discover.mjs@@ -27,6 +27,7 @@ export {OFFICIAL_SOURCE_NAME} from './_adapter.mjs';import {addCommand,callSources,+ computerAvailableEntries,declaredDependencies,describeInstalled,discoverPackages,@@ -216,18 +217,31 @@ export async function discover(query, options = {}) {if (!query || (integrations.length === 0 && !hasSources(project))) {const catalog = await catalogFor();const packages = installedFor(catalog);+ // Inside a project, the integrations installed for the computer are+ // available, never loaded (spec AST-081 FR12).+ const computer = await computerAvailableEntries(+ project,+ packages,+ declared,+ add,+ );+ const fromSources = officialFirst(+ availableEntries(catalog, packages, declared, {+ officialDeclared: declarations.any,+ install: installFor,+ }),+ official.packages,+ entry => entry.name,+ );+ const named = new Set(fromSources.map(entry => entry.name));return list(withLatest(packages, catalog), {configured,type,only,- available: officialFirst(- availableEntries(catalog, packages, declared, {- officialDeclared: declarations.any,- install: installFor,- }),- official.packages,- entry => entry.name,- ),+ available: [+ ...fromSources,+ ...computer.filter(entry => !named.has(entry.name)),+ ],sources: catalog.sources,});}diff --git a/packages/cli/api/discover/discover.type.mjs b/packages/cli/api/discover/discover.type.mjsindex 8363a2fcdc..10af39a354 100644--- a/packages/cli/api/discover/discover.type.mjs+++ b/packages/cli/api/discover/discover.type.mjs@@ -71,9 +71,11 @@* @property {string} [description]* @property {string[]} [aliases] The integration's other package names.* @property {string} source The discover source that lists it; `Astryx` for- * the official list.- * @property {string} [install] The package-manager command that adds it;- * discover prints it and never runs it.+ * the official list; `installed for this computer` for an integration+ * installed beside the CLI that the project does not install (spec AST-081+ * FR12).+ * @property {string} [install] The package-manager command that adds it to+ * this project; discover prints it and never runs it.*//**diff --git a/packages/cli/api/docs/_adapter.mjs b/packages/cli/api/docs/_adapter.mjsindex 4d76219dd8..e07f9e0a30 100644--- a/packages/cli/api/docs/_adapter.mjs+++ b/packages/cli/api/docs/_adapter.mjs@@ -70,6 +70,7 @@ import {import {findCoreDir} from '../../foundation/fs/paths.mjs';import {AstryxError} from '../error.mjs';import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';+import {formatCliCommand} from '../../foundation/env/package-manager.mjs';export {OVERLAY_LANGUAGES, overlayLanguages};@@ -1596,7 +1597,7 @@ export async function unknownTopicError(topic, catalog) {export function notLoaded(catalog) {const packages = [...new Set(catalog.issues.map(issue => issue.package))];if (packages.length === 0) return '';- return `. The docs of ${packages.join(', ')} did not load; run \`astryx doctor integration docs\` in that package to see why.`;+ return `. The docs of ${packages.join(', ')} did not load; run \`${formatCliCommand('doctor integration docs')}\` in that package to see why.`;}/**@@ -1614,7 +1615,7 @@ export async function resolveTopicDocs(topic, options = {}) {if (found.kind !== 'topic') {throw found.kind === 'node'? new AstryxError(- `"${found.node.route}" is a ${found.node.kind === 'namespace' ? 'namespace' : `${found.node.kind} doc`} in the docs tree, not a topic. Read it with \`astryx docs ${found.node.route}\`.`,+ `"${found.node.route}" is a ${found.node.kind === 'namespace' ? 'namespace' : `${found.node.kind} doc`} in the docs tree, not a topic. Read it with \`${formatCliCommand(`docs ${found.node.route}`)}\`.`,undefined,ERROR_CODES.ERR_UNKNOWN_TOPIC,)diff --git a/packages/cli/api/docs/docs.doc.mjs b/packages/cli/api/docs/docs.doc.mjsindex fa850130c8..e422c2a234 100644--- a/packages/cli/api/docs/docs.doc.mjs+++ b/packages/cli/api/docs/docs.doc.mjs@@ -34,7 +34,8 @@ export const doc = {'for a typed doc, `related` to the docs it names (its command or function, ' +'and its related docs); `previous` and `next` ' +'to the section or node before and after it. ' +- 'Overlay options select localized or dense variants.',+ 'Overlay options select localized or dense variants.' ++ " In global mode: with `cwd` outside a project, doc topics from integrations installed next to this CLI package globally are listed too; inside a project, only the project's own integrations count. See {@link namespace:global} and {@link generic:computer-integrations}.",importPath: '@astryxdesign/cli/api',signature:'docs(topic?: string, section?: string, options?: DocsOptions): Promise<DocsListResponse | DocsIndexResponse | DocsDetailResponse | DocsDetailSectionResponse | DocsNodeResponse>',diff --git a/packages/cli/api/docs/docs.mjs b/packages/cli/api/docs/docs.mjsindex d6d090a44d..e8831b3a6a 100644--- a/packages/cli/api/docs/docs.mjs+++ b/packages/cli/api/docs/docs.mjs@@ -34,6 +34,7 @@ import {node as nodeLeaf, nodeView} from './node/node.mjs';import {resolveDocsArgument} from './_adapter.mjs';import {AstryxError} from '../error.mjs';import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';+import {formatCliCommand} from '../../foundation/env/package-manager.mjs';export {list, index, detail, sectionLeaf as section, nodeLeaf as node};@@ -108,7 +109,7 @@ export async function docs(topic, section, options = {}) {return namespaceSection(found.tree, found.node, section, options);}throw new AstryxError(- `"${found.node.route}" has no sections. Read it whole: astryx docs ${found.node.route}.`,+ `"${found.node.route}" has no sections. Read it whole: ${formatCliCommand(`docs ${found.node.route}`)}.`,[{name: found.node.route, reason: found.node.summary}],ERROR_CODES.ERR_UNKNOWN_SECTION,);diff --git a/packages/cli/api/docs/docs.test.mjs b/packages/cli/api/docs/docs.test.mjsindex d391321937..fdbd8cdc73 100644--- a/packages/cli/api/docs/docs.test.mjs+++ b/packages/cli/api/docs/docs.test.mjs@@ -11,6 +11,7 @@import {describe, it, expect} from 'vitest';import {docs} from './docs.mjs';import {AstryxError} from '../error.mjs';+import {formatCliCommand} from '../../foundation/env/package-manager.mjs';const SLOW = 30_000;@@ -92,7 +93,7 @@ describe('docs() dispatcher routing', () => {it("lists the docs tree's namespaces in meta, so every data entry reads as a topic", async () => {const res = await docs();- expect(res.meta.namespaces.map(entry => entry.topic)).toEqual(['cli', 'internationalization', 'layout', 'migration', 'styling', 'styling-libraries', 'tokens', 'typography', 'unorganized']);+ expect(res.meta.namespaces.map(entry => entry.topic)).toEqual(['cli', 'global', 'internationalization', 'layout', 'migration', 'styling', 'styling-libraries', 'tokens', 'typography', 'unorganized']);for (const entry of res.data) {expect((await docs(entry.topic)).type).toBe('docs.detail');}@@ -107,7 +108,9 @@ describe('docs() dispatcher routing', () => {it('a section of a typed doc -> ERR_UNKNOWN_SECTION, suggesting the doc itself', async () => {const err = await docs('cli/api/functions/search', 'x').catch(e => e);expect(err.code).toBe('ERR_UNKNOWN_SECTION');- expect(err.message).toContain('astryx docs cli/api/functions/search');+ expect(err.message).toContain(+ formatCliCommand('docs cli/api/functions/search'),+ );expect(err.suggestions.map(s => s.name)).toEqual(['cli/api/functions/search']);}, SLOW);diff --git a/packages/cli/api/docs/reference-blocks.test.mjs b/packages/cli/api/docs/reference-blocks.test.mjsindex f6d4da54e9..9861bceb8d 100644--- a/packages/cli/api/docs/reference-blocks.test.mjs+++ b/packages/cli/api/docs/reference-blocks.test.mjs@@ -276,9 +276,7 @@ describe('a reference block in a topic section', () => {expect(status).toBe(0);expect(stdout).toMatch(/^Field +\| Type +\| Required +\| Description/m);expect(stdout).toMatch(/^components +\| string +\| no +\| /m);- expect(stdout).toContain(- 'From Astryx Integration: `astryx docs authoring integration`',- );+ expect(stdout).toContain(' docs authoring integration`');},SLOW,);diff --git a/packages/cli/api/doctor/_adapter.mjs b/packages/cli/api/doctor/_adapter.mjsindex 8485273086..e82f62afde 100644--- a/packages/cli/api/doctor/_adapter.mjs+++ b/packages/cli/api/doctor/_adapter.mjs@@ -2,15 +2,52 @@/** @file Environment adapter for app-theme doctor evidence. */+import {isOutsideProject} from '../../foundation/env/project-scope.mjs';+import {answeredBy} from '../../foundation/release/run-context.mjs';+import {+ knownLatestRelease,+ lastCheckFailure,+ stateLockHolder,+} from '../../foundation/release/global-state.mjs';+import {+ addCliCommand,+ alignCliAndCore,+ globalBehind,+ globalUpgradeCommand,+ lastNoticeSkip,+ projectLag,+} from '../../foundation/release/notices.mjs';+import {+ coreVersionOf,+ isGlobalCopy,+ projectRootOf,+} from '../../foundation/release/choose.mjs';+import {readReleaseFacts} from '../../foundation/release/project.mjs';+import {detectPackageManager} from '../../foundation/env/package-manager.mjs';+import {astryxCommandsOnSearchPath} from '../../foundation/env/search-path.mjs';+import {readDeclaredDependencies} from '../../foundation/integrations/autolink.mjs';+import {+ displayHomePath,+ inspectComputerAgentText,+} from '../../foundation/agent-docs/computer-agent-text.mjs';+import {computerAgentTextSettings} from '../../foundation/env/user-settings.mjs';import * as fs from 'node:fs';import * as path from 'node:path';-import {Project} from '../../foundation/config/project.mjs';+import {+ Project,+ availableComputerIntegrations,+ computerIntegrationCandidates,+} from '../../foundation/config/project.mjs';import {discoverUnmigratedThemeCopies,themeImportPackage,} from '../../foundation/discovery/theme-discovery.mjs';import {resolveThemeImports} from '../../foundation/discovery/theme-imports.mjs';-import {findCoreDir, findInstalledPackage} from '../../foundation/fs/paths.mjs';+import {+ CLI_ROOT,+ findProjectCoreDir,+ findInstalledPackage,+} from '../../foundation/fs/paths.mjs';export {isLocalThemeOwner,planThemeAppWrite,@@ -104,7 +141,7 @@ export function listProjectSourceFiles(root, generatedModule) {/** @param {string} projectDir */export async function discoverDoctorThemes(projectDir) {- const project = await Project.load(projectDir);+ const project = await Project.load(projectDir, {core: 'project'});return project.themes();}@@ -124,7 +161,7 @@ export function discoverDoctorUnmigratedCopies(projectDir) {/** @param {string} projectDir */export function findDoctorCoreDir(projectDir) {- return findCoreDir(projectDir);+ return findProjectCoreDir(projectDir);}/** @param {string} projectDir @param {string} packageName */@@ -188,3 +225,185 @@ export function readPackageJson(file) {return null;}}++/**+ * The integrations installed for the computer, and, outside a project, which+ * of them the folder loads (spec AST-081 FR12): those it uses, and the names+ * of the integrations the folder loads itself, whose copies win.+ * @param {string} cwd+ * @returns {Promise<{computerIntegrations: import('../../foundation/integrations/computer-integrations.mjs').ComputerIntegrationCandidate[], loadedComputerIntegrations: string[], folderIntegrations: string[]}>}+ */+export async function computerIntegrationsOutside(cwd) {+ const computerIntegrations = computerIntegrationCandidates(cwd);+ if (computerIntegrations.length === 0) {+ return {+ computerIntegrations,+ loadedComputerIntegrations: [],+ folderIntegrations: [],+ };+ }+ try {+ const project = await Project.load(cwd, {core: 'project'});+ /** @type {Array<{name: string, __computer?: boolean, __loadError?: string}>} */+ const loaded = project.loadedIntegrations;+ return {+ computerIntegrations,+ loadedComputerIntegrations: loaded+ .filter(i => i.__computer && !i.__loadError)+ .map(i => i.name),+ folderIntegrations: loaded.filter(i => !i.__computer).map(i => i.name),+ };+ } catch {+ return {+ computerIntegrations,+ loadedComputerIntegrations: [],+ folderIntegrations: [],+ };+ }+}++/**+ * Inside a project: the integrations installed for the computer it could add+ * (spec AST-081 FR12), leaving out every package it loads or declares.+ * @param {string} cwd+ * @param {string[]} loadedNames the integrations the project loads+ * @returns {Promise<import('../../foundation/integrations/computer-integrations.mjs').ComputerIntegrationCandidate[]>}+ */+export async function computerIntegrationsToAdd(cwd, loadedNames) {+ const installed = new Set([...loadedNames, ...declaredPackageNames(cwd)]);+ return availableComputerIntegrations(cwd, installed);+}++/**+ * The package names the folder's package.json declares, nearest first.+ * @param {string} cwd+ * @returns {string[]}+ */+function declaredPackageNames(cwd) {+ for (let dir = path.resolve(cwd); ;) {+ if (fs.existsSync(path.join(dir, 'package.json'))) {+ return readDeclaredDependencies(dir).map(d => d.name);+ }+ const parent = path.dirname(dir);+ if (parent === dir) return [];+ dir = parent;+ }+}++/**+ * The computer-level agent text's setting and its state on disk.+ * @returns {{settings: import('../../foundation/env/user-settings.mjs').ComputerAgentTextSettings, entries: Array<{path: string, state: import('../../foundation/agent-docs/computer-agent-text.mjs').ComputerAgentTextState, link?: true}>}}+ */+export function computerAgentTextState() {+ const settings = computerAgentTextSettings();+ return {settings, entries: inspectComputerAgentText({links: settings.links})};+}++export {displayHomePath};++/**+ * The release facts doctor reports, read here so the checks stay pure+ * (spec AST-081 FR5, FR6, FR10; architecture:cli-surface INV21): who+ * answered, the newest release the computer knows of, how far the global copy+ * or the project is behind, and every `astryx` on the search path with the+ * command that upgrades it.+ * @param {string} cwd+ * @param {{project: boolean}} options+ * @returns {{answeredBy: {cli: string, core: string | null, copy: string}, latest: string | null, globalBehind: ReturnType<typeof globalBehind> | null, projectLag: ReturnType<typeof projectLag> | null, lastNoticeSkip: ReturnType<typeof lastNoticeSkip>, lastCheckFailure: ReturnType<typeof lastCheckFailure>, stateLock: ReturnType<typeof stateLockHolder>, searchPathCommands: Array<import('../../foundation/env/search-path.mjs').SearchPathCommand & {upgrade: string | null}>}}+ */+export function releaseFacts(cwd, {project}) {+ const answered = answeredBy(cwd);+ return {+ answeredBy: answered,+ latest: knownLatestRelease(),+ lastNoticeSkip: lastNoticeSkip(),+ lastCheckFailure: lastCheckFailure(),+ stateLock: stateLockHolder(),+ globalBehind:+ !project && isGlobalCopy(CLI_ROOT)+ ? globalBehind({self: {version: answered.cli, root: CLI_ROOT}})+ : null,+ // The project's version is its own CLI's, or, with none, its Core's:+ // installed, else locked, else declared, as the daily notice reads it.+ projectLag: project+ ? projectLag({+ cwd,+ current:+ (answered.copy === 'starting' && projectCoreVersion(cwd)) ||+ answered.cli,+ })+ : null,+ searchPathCommands: astryxCommandsOnSearchPath().map(row => ({+ ...row,+ upgrade: row.cliRoot ? globalUpgradeCommand(row.cliRoot) : null,+ })),+ };+}++/** Whether `cwd` is outside every project. */+export function outsideProject(/** @type {string} */ cwd) {+ return isOutsideProject(cwd);+}++/**+ * The commands that bring a project's own CLI and Core to one release, with+ * the project's package manager: Core up to the CLI, then its codemods, when+ * the CLI is newer; else the CLI to the Core's release.+ * @param {string} cwd+ * @param {string} cli+ * @param {string} core+ * @returns {string}+ */+export function alignCommand(cwd, cli, core) {+ return alignCliAndCore({cwd, cli, core});+}++/**+ * The Core release the project at `cwd` names: installed, else locked, else+ * declared; the version the daily hint and notice compare against (spec+ * AST-081 FR2). Null outside a project or when it names none.+ * @param {string} cwd+ * @returns {string | null}+ */+export function projectCoreVersion(cwd) {+ return coreVersionOf(readReleaseFacts(cwd));+}++/**+ * Whether the project at `cwd` installs its own CLI (spec AST-081 FR2).+ * @param {string} cwd+ * @returns {boolean}+ */+export function projectHasOwnCli(cwd) {+ return Boolean(readReleaseFacts(cwd).cli);+}++/**+ * The command that adds the CLI at `version` with the project's package+ * manager.+ * @param {string} cwd+ * @param {string} version+ * @returns {string}+ */+export function addCliCommandFor(cwd, version) {+ return addCliCommand(projectRootOf(readReleaseFacts(cwd)) ?? cwd, version);+}++/**+ * The command that adds a package with the folder's package manager, read+ * from its lockfiles and `packageManager` field.+ * @param {string} cwd+ * @returns {(name: string) => string}+ */+export function installCommandFor(cwd) {+ const pm = detectPackageManager(cwd);+ const verb =+ pm === 'pnpm'+ ? 'pnpm add'+ : pm === 'yarn'+ ? 'yarn add'+ : pm === 'bun'+ ? 'bun add'+ : 'npm install';+ return name => `${verb} ${name}`;+}diff --git a/packages/cli/api/doctor/doctor.doc.mjs b/packages/cli/api/doctor/doctor.doc.mjsindex d68f0eb269..175b65785c 100644--- a/packages/cli/api/doctor/doctor.doc.mjs+++ b/packages/cli/api/doctor/doctor.doc.mjs@@ -24,7 +24,8 @@ export const doc = {'integration provider identity and contribution issues, agent docs, the ' +'detected package manager, and the health of the docs the CLI reads (authoring ' +'and CLI docs, the docs tree, doc size), and returns a structured ' +- 'report. Theme checks run when the generated app module exists; without one, doctor reports that the CLI manages no themes and names theme add. Earlier descriptor-less copies are a non-failing upgrade warning. It never installs, writes, or mutates. It imports astryx.config, executes every added theme source while validating private inputs, and loads every recorded built theme module to prove its runtime imports work, including themes from installed packages. Local theme source also runs during build-freshness checks. Stylesheets are parsed without execution. Config and theme top-level code therefore run, so use doctor only with project code you trust.',+ 'report. Theme checks run when the generated app module exists; without one, doctor reports that the CLI manages no themes and names theme add. Earlier descriptor-less copies are a non-failing upgrade warning. It never installs, writes, or mutates. It imports astryx.config, executes every added theme source while validating private inputs, and loads every recorded built theme module to prove its runtime imports work, including themes from installed packages. Local theme source also runs during build-freshness checks. Stylesheets are parsed without execution. Config and theme top-level code therefore run, so use doctor only with project code you trust. Outside a project it checks the computer instead: the Node version (`node-version`), the release that answered (`answering-release`), the newest release the computer knows of (`newest-release`), the astryx commands on the search path (`cli-on-path`), the integrations installed for the computer (`computer-integrations`: each one used outside a project, and a warning for one skipped because its peer range excludes the answering release or that fails to load), and the computer-level agent text (`computer-agent-text`): present and matching this release, present but different, edited, absent, or turned off, and where it is linked, with `astryx init --user` as the fix for the stale and absent cases. The agent-text check is always info. The newest-release check also runs inside a project: it names a newer release when the computer knows of one; inside a project whose release is older it names the install and upgrade commands; outside one, when the CLI installed for the computer is older, it names the command of the package manager that installed it, after the Node the newest release needs when the computer runs an older one. It is always info and installs nothing. The `cli-on-path` check also runs inside a project: it lists every astryx command on the search path in order, passes when the first is a release that hands each project run to the release of that project, and warns when the first is another program or a release that predates the hand-off, naming `npm i -g @astryxdesign/cli@latest`. Inside a project, `computer-integrations` lists, as info, the integrations installed for the computer that the project does not install, with its install command; they are not used there. It never fails a check because the folder has no project, and installs nothing.' ++ ' In global mode: with `cwd` outside a project, it checks the computer instead (the Node version, the version that answered, the newest version it knows of, the astryx commands on the search path, the integrations installed globally, and the agent guide for the computer) and never fails a check because the folder has no project. See {@link namespace:global} and {@link generic:who-answers}.',importPath: '@astryxdesign/cli/api',signature: 'doctor(options?: DoctorOptions): Promise<DoctorResponse>',keywords: ['doctor', 'diagnose', 'health', 'check', 'verify', 'environment'],@@ -33,7 +34,7 @@ export const doc = {name: 'options.cwd',type: 'string',description:- 'Directory to diagnose. A missing directory is not an error; it shows up in the checks (e.g. core-installed: fail).',+ 'Directory to diagnose. A directory outside any project, a missing one included, gets the computer checks.',default: 'process.cwd()',},],diff --git a/packages/cli/api/doctor/doctor.mjs b/packages/cli/api/doctor/doctor.mjsindex a6630141b3..a04a23292a 100644--- a/packages/cli/api/doctor/doctor.mjs+++ b/packages/cli/api/doctor/doctor.mjs@@ -4,7 +4,11 @@* @file Health-check engine for `astryx doctor`.** Runs a series of diagnostic checks against the user's project and- * environment, returning a structured report. Each check is a small,+ * environment, returning a structured report. Outside a project it checks the+ * computer instead (spec AST-081 FR4): the Node version, the release that+ * answered, the newest release the computer knows of, and whether the+ * computer-level agent text is present and current; no check fails because+ * the folder has no project. Each check is a small,* self-contained function that returns a {@link DoctorCheck} record, so* adding a new diagnostic is just appending a function to {@link SYNC_CHECKS}.*@@ -25,8 +29,9 @@ import * as path from 'node:path';import {MIN_NODE_VERSION, isNodeVersionSupported} from '../../foundation/env/node-version.mjs';import {AGENT_DOC_PATHS} from '../../foundation/agent-docs/agent-doc-state.mjs';-import {CLI_ROOT, findCoreDir, findInstalledPackage} from '../../foundation/fs/paths.mjs';-import {explainPackageManager, getCliInvocation} from '../../foundation/env/package-manager.mjs';+import {CLI_ROOT, findProjectCoreDir, findInstalledPackage} from '../../foundation/fs/paths.mjs';+import {explainPackageManager, formatCliCommand, getCliInvocation, guessCliInvocation} from '../../foundation/env/package-manager.mjs';+import {chooseDeclaredCliCommand, declaredCliCommandsOf} from '../../foundation/env/cli-command.mjs';import {findConfigPath,Project,@@ -52,6 +57,8 @@ import {typedEdges} from '../docs/node/node.mjs';import {detailView, indexView} from '../../foundation/doc-compiler/lenses.mjs';import {semverCompare, isValidSemver, satisfiesRange} from '../../foundation/env/semver.mjs';import {checkAppThemes, checkThemes} from './theme-checks.mjs';+import {availableLine, upgradeLine} from '../../foundation/release/notices.mjs';+import {alignCommand, addCliCommandFor, computerAgentTextState, installCommandFor, projectCoreVersion, projectHasOwnCli, computerIntegrationsOutside, computerIntegrationsToAdd, displayHomePath, outsideProject, releaseFacts} from './_adapter.mjs';/*** @typedef {'pass'|'warn'|'fail'|'info'} DoctorStatus@@ -71,6 +78,10 @@ import {checkAppThemes, checkThemes} from './theme-checks.mjs';* @property {string} cwd - Directory to diagnose.* @property {string} nodeVersion - Running Node version.* @property {string|null} coreDir - Resolved core package directory, or null.+ * @property {boolean} [ownCli] - Whether the project installs its own CLI;+ * false means the copy that started the run answered it (spec AST-081 FR2).+ * @property {string|null} [projectCore] - The Core release the project names+ * (installed, else locked, else declared), as the daily hint reads it.* @property {string|null} configPath - Resolved astryx.config.mjs path, or null.* @property {import('../../foundation/integrations/integrations.mjs').LoadedIntegration[]|null} [integrations]* Every integration the project loaded, or null when the project could not be@@ -229,7 +240,12 @@ export function checkCoreInstalled(ctx) {* @returns {DoctorCheck}*/export function checkVersionAlignment(ctx) {- const coreVersion = pkgVersion(ctx.coreDir);+ // A project with no CLI of its own and no Core installed yet (a fresh+ // clone) is compared by the Core it locks or declares, as the daily hint+ // compares it (spec AST-081 FR2).+ const coreVersion =+ pkgVersion(ctx.coreDir) ??+ (ctx.ownCli === false ? (ctx.projectCore ?? null) : null);const cliPkg = readPkg(path.join(CLI_ROOT, 'package.json'));const cliVersion = cliPkg?.version ?? null;@@ -258,25 +274,33 @@ export function checkVersionAlignment(ctx) {};}- const [coreMajor, coreMinor] = coreVersion.split('.').map(Number);- const [cliMajor, cliMinor] = cliVersion.split('.').map(Number);- const drift = coreMajor !== cliMajor || coreMinor !== cliMinor;-+ // A project with no CLI of its own is answered by the copy that started+ // the run (spec AST-081 FR2): say so, and how to add the CLI at Core's+ // version.+ if (ctx.ownCli === false) {+ return {+ id: 'version-alignment',+ label: '@astryxdesign/core <-> @astryxdesign/cli alignment',+ status: coreVersion === cliVersion ? 'info' : 'warn',+ message:+ coreVersion === cliVersion+ ? `This project has no Astryx CLI installed; CLI ${cliVersion}, the one you started, answered and matches its Core.`+ : `This project has no Astryx CLI installed; CLI ${cliVersion}, the one you started, answered while its Core is ${coreVersion}.`,+ fix: `${coreVersion === cliVersion ? 'To pin it for the team and CI' : 'To match'}, run: ${addCliCommandFor(ctx.cwd, coreVersion)}.`,+ };+ }+ // The project's own CLI answers this project whatever its version+ // (spec AST-081 FR2), so any difference means templates, docs, and agent+ // text come from one release and components from another.+ const drift = coreVersion !== cliVersion;return {id: 'version-alignment',label: '@astryxdesign/core <-> @astryxdesign/cli alignment',status: drift ? 'warn' : 'pass',message: drift- ? `@astryxdesign/core v${coreVersion} drifts from @astryxdesign/cli v${cliVersion} (major/minor mismatch).`+ ? `This project's CLI ${cliVersion} answers it, but its Core is ${coreVersion}: templates, docs, and agent text come from CLI ${cliVersion}, components from Core ${coreVersion}.`: `@astryxdesign/core v${coreVersion} is in step with @astryxdesign/cli v${cliVersion}.`,- ...(drift- ? {- fix:- semverCompare(cliVersion, coreVersion) > 0- ? `Update @astryxdesign/core to ${cliMajor}.${cliMinor}.x to match the CLI.`- : `Update @astryxdesign/cli to ${coreMajor}.${coreMinor}.x to match @astryxdesign/core.`,- }- : {}),+ ...(drift ? {fix: `To align them, run: ${alignCommand(ctx.cwd, cliVersion, coreVersion)}.`} : {}),};}@@ -331,7 +355,7 @@ export async function checkConfig(ctx) {label: 'astryx.config.mjs',status: 'fail',message: `astryx.config.mjs loads, but the CLI could not load the project from it: ${firstLine(ctx.projectError)}`,- fix: 'Fix what the message names. `astryx docs authoring config` lists every field astryx.config accepts.',+ fix: `Fix what the message names. \`${formatCliCommand('docs authoring config', ctx.cwd)}\` lists every field astryx.config accepts.`,};}return {@@ -500,7 +524,7 @@ function describeUnreadableManifests(failures) {return (` ${failures.length} installed ${one ? 'dependency ships' : 'dependencies ship'} ` +`an astryx.integration.* manifest that could not be loaded, so ${one ? 'it contributes' : 'they contribute'} ` +- `nothing: ${listed}. Run \`astryx doctor integration validate <package>\` for details.`+ `nothing: ${listed}. Run \`${formatCliCommand('doctor integration validate <package>')}\` for details.`);}@@ -574,7 +598,7 @@ export function checkConfiguredIntegrations(ctx) {`${withdrawn.length} of ${configured.length} integration${plural} named in astryx.config could not be loaded, ` +`so ${withdrawn.length === 1 ? 'it contributes' : 'they contribute'} nothing: ${listed}.`,fix:- 'Install each one, fix its astryx.integration.* manifest (`astryx doctor integration validate <package>` says what is wrong), ' ++ `Install each one, fix its astryx.integration.* manifest (\`${formatCliCommand('doctor integration validate <package>', ctx.cwd)}\` says what is wrong), ` +'or remove it from `integrations` in astryx.config.',};}@@ -772,7 +796,7 @@ export function checkIntegrationIssues(ctx) {label: 'Integration contributions',status: 'warn',message: `${issues.length} integration issue(s)${errors > 0 ? `, ${errors} of them errors` : ''}: ${details}`,- fix: 'Run `astryx doctor integration` for package-specific diagnostics and resolve cross-package precedence in astryx.config.',+ fix: `Run \`${formatCliCommand('doctor integration', ctx.cwd)}\` for package-specific diagnostics and resolve cross-package precedence in astryx.config.`,};}@@ -978,7 +1002,7 @@ function surfaceProblems(surface) {const problems = [];if (surface.types === 0 && surface.untraced.length === 0) {problems.push(- '@astryxdesign/cli/authoring exports no types, so nothing was compared with `astryx docs authoring`',+ `@astryxdesign/cli/authoring exports no types, so nothing was compared with \`${formatCliCommand('docs authoring')}\``,);}for (const {module, names, reason, source, key} of surface.unreadable) {@@ -991,7 +1015,7 @@ function surfaceProblems(surface) {? `${source} does not load`: `${source} renders section "${key}", which the topic's index does not list`;problems.push(- `${nameTypes(names)} from ${module} ${names.length === 1 ? 'has' : 'have'} no doc in \`astryx docs authoring\`: ${why}`,+ `${nameTypes(names)} from ${module} ${names.length === 1 ? 'has' : 'have'} no doc in \`${formatCliCommand('docs authoring')}\`: ${why}`,);}for (const {name, reason} of surface.untraced) {@@ -1032,7 +1056,7 @@ export async function checkAuthoringDocs(_ctx, options = {}) {const audit = await auditAuthoringSelfDocs({root, sources});const problems = [...audit.unreachable.map(- source => `${source} is not in \`astryx docs authoring\``,+ source => `${source} is not in \`${formatCliCommand('docs authoring')}\``,),...audit.failed.map(({source, error}) => `${source} failed to load: ${error}`,@@ -1048,7 +1072,7 @@ export async function checkAuthoringDocs(_ctx, options = {}) {: {keys: options.topicKeys};const surface = [...('error' in topic- ? [`\`astryx docs authoring\` could not be read: ${topic.error}`]+ ? [`\`${formatCliCommand('docs authoring')}\` could not be read: ${topic.error}`]: []),...surfaceProblems(await auditAuthoringSurface({root, sources, topicKeys: topic.keys}),@@ -1072,7 +1096,7 @@ export async function checkAuthoringDocs(_ctx, options = {}) {id,label,status: 'pass',- message: `All ${audit.sections} authoring schemas are readable in \`astryx docs authoring\`.`,+ message: `All ${audit.sections} authoring schemas are readable in \`${formatCliCommand('docs authoring')}\`.`,};} catch (err) {return {@@ -1112,11 +1136,11 @@ export async function checkCliDocs(_ctx, options = {}) {const problems = [...audit.missing.map(source =>- `${source} has no namespace, so no \`astryx docs\` topic reads it`,+ `${source} has no namespace, so no \`${formatCliCommand('docs')}\` topic reads it`,),...audit.unknown.map(({source, namespace}) =>- `${source} has namespace "${namespace}", which no \`astryx docs\` topic reads`,+ `${source} has namespace "${namespace}", which no \`${formatCliCommand('docs')}\` topic reads`,),...audit.misfiled.map(({message}) => message),...audit.failed.map(@@ -1140,7 +1164,7 @@ export async function checkCliDocs(_ctx, options = {}) {id,label,status: 'pass',- message: `All ${audit.docs} CLI docs are readable: ${audit.tree} in the \`astryx docs cli\` tree and ${audit.authoring} in \`astryx docs authoring\`.`,+ message: `All ${audit.docs} CLI docs are readable: ${audit.tree} in the \`${formatCliCommand('docs cli')}\` tree and ${audit.authoring} in \`${formatCliCommand('docs authoring')}\`.`,};} catch (err) {return {@@ -1302,6 +1326,423 @@ export async function checkDocsProgressiveDisclosure(ctx) {};}+/**+ * Check 11 — the command every printed command starts with, and a warning when+ * loaded integrations declare different ones (their `cliCommand`). Then the+ * picker uses neither, so commands fall back to the package-manager guess.+ *+ * @param {DoctorContext} ctx+ * @returns {DoctorCheck}+ */+export function checkCliCommand(ctx) {+ const id = 'cli-command';+ const label = 'CLI command';+ const {command, conflict, declared} = chooseDeclaredCliCommand(+ declaredCliCommandsOf(ctx.integrations ?? []),+ );+ if (conflict) {+ const claims = declared+ .map(entry => `${entry.package} (\`${entry.command}\`)`)+ .join(', ');+ return {+ id,+ label,+ status: 'warn',+ message: `Loaded integrations declare different CLI commands: ${claims}. Neither is used, so printed commands start with \`${guessCliInvocation(ctx.cwd)}\`.`,+ fix: 'Remove the integration that does not belong here, or have every package declare the same `cliCommand` in its astryx.integration manifest.',+ };+ }+ if (command) {+ const packages = declared.map(entry => entry.package).join(', ');+ return {+ id,+ label,+ status: 'pass',+ message: `Printed commands start with \`${command}\`, the cliCommand of ${packages}.`,+ };+ }+ return {+ id,+ label,+ status: 'info',+ message: `No loaded integration declares a cliCommand, so printed commands start with \`${getCliInvocation(ctx.cwd)}\`.`,+ };+}++/* ── outside a project: the computer ─────────────────────────────────── */++/**+ * What a computer check reads: the running Node, the release that answered+ * (`meta.answeredBy`), and the newest release the computer knows of.+ * @typedef {object} ComputerContext+ * @property {string} nodeVersion+ * @property {{cli: string, core: string | null, copy: string}} answeredBy+ * @property {string | null} latest the newest release known, or null+ * @property {Array<{path: string, state: import('../../foundation/agent-docs/computer-agent-text.mjs').ComputerAgentTextState}>} [agentText]+ * each file of the computer-level agent text against this release's rendering+ * @property {import('../../foundation/env/user-settings.mjs').ComputerAgentTextSettings} [agentTextSettings]+ * the person's choices about the computer-level agent text+ * @property {string} [cwd] the folder doctor runs in, for the printed fix+ * @property {import('../../foundation/release/notices.mjs').GlobalBehind | null} [globalBehind]+ * the CLI installed for the computer, when it is older than the newest+ * release (outside a project)+ * @property {import('../../foundation/release/notices.mjs').ProjectLag | null} [projectLag]+ * the project's release, when it is behind the newest (inside a project)+ * @property {{key: string, reason: string, at: number} | null} [lastNoticeSkip]+ * @property {{at: number, reason: string} | null} [lastCheckFailure] why the+ * last update check did not reach the registry, after the last that did+ * the newest update notice that did not print, and why (diagnostic only)+ * @property {{pid: number | null, host: string | null, since: number} | null} [stateLock]+ * who holds the state file's lock now (diagnostic only)+ * @property {Array<import('../../foundation/env/search-path.mjs').SearchPathCommand & {upgrade?: string | null}>} [searchPathCommands]+ * every `astryx` on the search path, with the command that upgrades it+ * the `astryx` commands on the search path, in order+ * @property {import('../../foundation/integrations/computer-integrations.mjs').ComputerIntegrationCandidate[]} [computerIntegrations]+ * the integrations installed beside the running CLI+ * @property {string[]} [loadedComputerIntegrations] the names of those that+ * loaded outside a project+ * @property {string[]} [folderIntegrations] the names of the integrations the+ * folder loads itself, whose copies win over the computer's+ */++/**+ * The release that answered this run outside a project, and the Core it+ * reads from.+ * @param {ComputerContext} ctx+ * @returns {DoctorCheck}+ */+export function checkAnsweringRelease(ctx) {+ const {cli, core} = ctx.answeredBy;+ return {+ id: 'answering-release',+ label: 'Release that answered',+ status: core ? 'pass' : 'info',+ message: `${+ core+ ? `CLI ${cli} with Core ${core} answered, outside a project.`+ : `CLI ${cli} answered, outside a project. It installs Core ${cli} into the per-user cache the first time a command needs it.`+ } How each folder is answered: \`${formatCliCommand('astryx docs global', ctx.cwd)}\`.`,+ };+}++/**+ * The newest release this computer knows of, beside the one that answered+ * (spec AST-081 FR10). Runs inside and outside a project, and is always+ * info. Inside one, a release behind the newest names the install and+ * upgrade commands; outside one, a CLI installed for the computer that is+ * behind names the command of the package manager that installed it, after+ * the Node it needs when the computer runs an older one. Doctor installs+ * nothing.+ * @param {ComputerContext} ctx+ * @returns {DoctorCheck}+ */+export function checkNewestRelease(ctx) {+ const check = newestReleaseCheck(ctx);+ const notes = [+ checkFailureNote(ctx.lastCheckFailure),+ skipNote(ctx.lastNoticeSkip),+ lockNote(ctx.stateLock),+ ].filter(Boolean);+ return notes.length > 0 ? {...check, message: [check.message, ...notes].join(' ')} : check;+}++/**+ * The note on a state-file lock held right now, which keeps notices from+ * being recorded (diagnostic only).+ * @param {{pid: number | null, host: string | null, since: number} | null | undefined} lock+ * @returns {string | null}+ */+function lockNote(lock) {+ if (!lock) return null;+ const by = lock.pid == null ? '' : ` by process ${lock.pid}${lock.host ? ` on ${lock.host}` : ''}`;+ return `The state file's lock is held${by} since ${new Date(lock.since).toISOString()}.`;+}++/**+ * The note on an update check that did not reach the registry (diagnostic+ * only): no check, no notices.+ * @param {{at: number, reason: string} | null | undefined} failed+ * @returns {string | null}+ */+function checkFailureNote(failed) {+ if (!failed) return null;+ const why =+ failed.reason === 'npm-missing'+ ? 'npm could not be started'+ : failed.reason === 'bad-reply'+ ? "npm's answer named no release"+ : failed.reason.startsWith('npm-failed: ')+ ? `npm failed (${failed.reason.slice('npm-failed: '.length)}); its registry and proxy settings decide where it asks`+ : failed.reason;+ return `The last update check, ${new Date(failed.at).toISOString()}, did not reach the registry: ${why}.`;+}++/** What a recorded notice skip's reason means, for doctor's update line. */+const SKIP_REASONS = {+ 'already-shown': 'it had already printed that day',+ 'no-newer': 'no newer release was known',+};++/**+ * The note on the last update notice that did not print, for diagnosis+ * (diagnostic state, not a contract).+ * @param {{key: string, reason: string, at: number} | null | undefined} skip+ * @returns {string | null}+ */+function skipNote(skip) {+ if (!skip) return null;+ const why = /** @type {Record<string, string>} */ (SKIP_REASONS)[skip.reason] ?? skip.reason;+ return `Last update notice skipped ${new Date(skip.at).toISOString()} (${skip.key}): ${why}.`;+}++/**+ * {@link checkNewestRelease} without the skip note.+ * @param {ComputerContext} ctx+ * @returns {DoctorCheck}+ */+function newestReleaseCheck(ctx) {+ const {latest, globalBehind: behind, projectLag: lag} = ctx;+ const {cli} = ctx.answeredBy;+ const base = {id: 'newest-release', label: 'Newest release', status: /** @type {const} */ ('info')};+ if (behind) {+ return {+ ...base,+ message: `${availableLine(behind.current, behind.newest)}. The CLI installed for the computer stays on its release until you upgrade it.`,+ fix: `${upgradeLine(behind.command, behind.node)}.`,+ };+ }+ if (lag) {+ return {+ ...base,+ message: `This project uses Astryx ${lag.current}; ${lag.newest} is the newest.`,+ fix: `${upgradeLine(`${lag.install}, then ${lag.upgrade}`, lag.node)}.`,+ };+ }+ if (!latest) {+ return {+ ...base,+ message: 'Update check: not run yet, so the newest release is not known here; it runs in the background once a day, after a command.',+ };+ }+ if (isValidSemver(latest) && isValidSemver(cli) && semverCompare(latest, cli) > 0) {+ return {+ ...base,+ message: `Release ${latest} is newer than ${cli}, the release that answered.`,+ };+ }+ return {...base, message: `No newer release is known: the newest is ${latest}.`};+}++/**+ * The `astryx` commands on the search path (spec AST-081 FR11): the first is+ * the one a shell runs. Warns when it is not the Astryx CLI, or is a release+ * that predates the hand-off and so answers every folder itself.+ * @param {ComputerContext} ctx+ * @returns {DoctorCheck}+ */+export function checkCliOnPath(ctx) {+ const rows = ctx.searchPathCommands ?? [];+ const base = {id: 'cli-on-path', label: '`astryx` on the search path'};+ const describe = (/** @type {import('../../foundation/env/search-path.mjs').SearchPathCommand} */ row) =>+ row.astryx ? `${row.file} (CLI ${row.version ?? 'of unknown version'})` : `${row.file} (not the Astryx CLI)`;+ const others = rows.slice(1);+ const othersNote = others.length > 0 ? ` Later on the search path: ${others.map(describe).join(', ')}.` : '';+ const [first] = rows;+ if (!first) {+ return {+ ...base,+ status: 'info',+ message: 'No `astryx` command on the search path, so `astryx` runs only through a package manager.',+ fix: 'To run the CLI in any folder, install it for the computer: `npm i -g @astryxdesign/cli`.',+ };+ }+ if (!first.astryx) {+ return {+ ...base,+ status: 'warn',+ message: `The first \`astryx\` on the search path, ${first.file}, is not the Astryx CLI, so \`astryx\` runs another program.${othersNote}`,+ fix: 'Remove that program from the search path, or put the folder of the CLI installed for the computer before it.',+ };+ }+ if (first.handsOff === false) {+ return {+ ...base,+ status: 'warn',+ message: `The first \`astryx\` on the search path, ${first.file}, runs CLI ${first.version ?? 'of unknown version'}, which predates the hand-off and answers every folder itself.${othersNote}`,+ fix: `To upgrade, run: \`${first.upgrade ?? 'npm i -g @astryxdesign/cli@latest'}\`.`,+ };+ }+ return {+ ...base,+ status: 'pass',+ message: `\`astryx\` runs ${describe(first)}.${othersNote}`,+ };+}++/**+ * The computer-level agent text (spec AST-081 FR4, FR8): turned off, present+ * and equal to this release's rendering, present but different, or absent,+ * for the files the chosen agents read. Always `info`: the text is optional,+ * so it never warns or fails. A file Astryx did not write counts as absent,+ * and a file a person edited is named; both are kept as they are.+ * @param {ComputerContext} ctx+ * @returns {DoctorCheck}+ */+export function checkComputerAgentText(ctx) {+ const state = ctx.agentTextSettings && ctx.agentText ? null : computerAgentTextState();+ const settings = ctx.agentTextSettings ?? /** @type {NonNullable<typeof state>} */ (state).settings;+ const base = {+ id: 'computer-agent-text',+ label: 'Computer-level agent text',+ status: /** @type {const} */ ('info'),+ };+ if (!settings.install) {+ return {+ ...base,+ message: 'The computer-level agent text is turned off (`astryx init --user --remove-agents`), so the CLI installed for the computer does not write it.',+ fix: `To turn it back on, run \`${formatCliCommand('astryx init --user', ctx.cwd)}\`.`,+ };+ }+ const entries = ctx.agentText ?? /** @type {NonNullable<typeof state>} */ (state).entries;+ const fix = `Run \`${formatCliCommand('astryx init --user', ctx.cwd)}\`.`;+ const [file, ...links] = entries;+ const home = (/** @type {{path: string}} */ e) => displayHomePath(e.path);+ const linked = links.filter(l => l.state === 'linked').map(home);+ const copied = links.filter(l => l.state === 'current').map(home);+ const skipped = links.filter(l => l.state === 'foreign' || l.state === 'edited').map(home);+ const dangling = links.filter(l => l.state === 'dangling').map(home);+ const missing = links.filter(l => l.state === 'absent' || l.state === 'differs').map(home);+ const linkNote =+ (linked.length > 0 ? ` Linked into: ${linked.join(', ')}.` : '') ++ (copied.length > 0 ? ` Copied into: ${copied.join(', ')}.` : '') ++ (skipped.length > 0 ? ` Not linked, because something Astryx did not create is there: ${skipped.join(', ')}.` : '') ++ (dangling.length > 0 ? ` Linked, but the skill folder the link points to is not there, so agents reading it see nothing (as in a container that mounts only that folder): ${dangling.join(', ')}.` : '') ++ (missing.length > 0 ? ` Not linked yet: ${missing.join(', ')}.` : '');+ if (file.state === 'foreign' || file.state === 'edited') {+ return {+ ...base,+ message: `${home(file)} ${file.state === 'edited' ? 'was edited since Astryx wrote it' : 'was not written by Astryx'}, so it is left as it is (delete it to get the current text).${linkNote}`,+ };+ }+ if (file.state === 'absent') {+ return {+ ...base,+ message: `No computer-level agent text: agents outside a project with Astryx agent docs do not know Astryx is here.${linkNote}`,+ fix,+ };+ }+ const current = file.state === 'current';+ return {+ ...base,+ message: `${current ? 'The computer-level agent text matches this release' : "The computer-level agent text differs from this release's"}: ${home(file)}.${linkNote}`,+ ...(!current || missing.length > 0 || dangling.length > 0 ? {fix} : {}),+ };+}++/**+ * The integrations installed for the computer (spec AST-081 FR12). Outside a+ * project: each one that loads, and a warning for each that is skipped+ * because its peer ranges exclude the answering release, or fails to load.+ * @param {ComputerContext} ctx+ * @returns {DoctorCheck}+ */+export function checkComputerIntegrations(ctx) {+ const found = ctx.computerIntegrations ?? [];+ const loaded = new Set(ctx.loadedComputerIntegrations ?? []);+ const base = {id: 'computer-integrations', label: 'Integrations installed for this computer'};+ if (found.length === 0) {+ return {+ ...base,+ status: 'info',+ message: 'No integration is installed beside the CLI installed for this computer.',+ };+ }+ const label = (/** @type {{name: string, version?: string}} */ c) => (c.version ? `${c.name}@${c.version}` : c.name);+ const own = new Set(ctx.folderIntegrations ?? []);+ const shadowed = found.filter(c => own.has(c.name));+ const rest = found.filter(c => !own.has(c.name));+ const used = rest.filter(c => !c.incompatible && loaded.has(c.name));+ const skipped = rest.filter(c => c.incompatible);+ const failed = rest.filter(c => !c.incompatible && !loaded.has(c.name));+ const notes = [+ used.length > 0 ? `Used outside a project: ${used.map(label).join(', ')}.` : '',+ ...shadowed.map(c => `${label(c)} is not used here: this folder loads its own copy of ${c.name}.`),+ ...skipped.map(c => `Skipped ${label(c)}: ${c.incompatible}.`),+ ...failed.map(c => `${label(c)} could not be loaded.`),+ ].filter(Boolean);+ const fixes = [+ ...skipped.map(c => `install a release of ${c.name} that supports this CLI`),+ ...failed.map(c => `run \`${formatCliCommand(`astryx doctor integration validate ${c.name}`, ctx.cwd)}\``),+ ];+ return {+ ...base,+ status: skipped.length + failed.length > 0 ? 'warn' : 'pass',+ message: notes.join(' '),+ ...(fixes.length > 0 ? {fix: `To fix: ${fixes.join('; ')}.`} : {}),+ };+}++/**+ * Inside a project, the integrations installed for the computer that the+ * project does not install: available, never used (spec AST-081 FR12).+ * Always info.+ * @param {{installed: Set<string>, candidates: import('../../foundation/integrations/computer-integrations.mjs').ComputerIntegrationCandidate[], install: (name: string) => string}} input+ * `install`: the command that adds a package with the project's package+ * manager (read by the adapter)+ * @returns {DoctorCheck}+ */+export function checkComputerIntegrationsAvailable({installed, candidates, install}) {+ const available = candidates.filter(c => !installed.has(c.name));+ const base = {id: 'computer-integrations', label: 'Integrations installed for this computer', status: /** @type {const} */ ('info')};+ if (available.length === 0) {+ return {...base, message: 'No integration installed for this computer is missing from this project.'};+ }+ const add = install;+ return {+ ...base,+ message: `Installed for this computer but not in this project, so not used here: ${available.map(c => c.name).join(', ')}.`,+ fix: `To use one in this project, run ${available.map(c => `\`${add(c.name)}\``).join(' or ')}.`,+ };+}++/**+ * The checks doctor runs outside a project, in order.+ * @type {Array<(ctx: ComputerContext) => DoctorCheck>}+ */+export const COMPUTER_CHECKS = [+ ctx =>+ checkNodeVersion({+ cwd: '',+ nodeVersion: ctx.nodeVersion,+ coreDir: null,+ configPath: null,+ }),+ checkAnsweringRelease,+ checkNewestRelease,+ checkCliOnPath,+ checkComputerIntegrations,+ checkComputerAgentText,+];++/**+ * Doctor outside a project: the computer, never the folder.+ * @param {string} cwd+ * @returns {Promise<DoctorReport>}+ */+async function runComputerChecks(cwd) {+ /** @type {ComputerContext} */+ const ctx = {+ nodeVersion: process.versions.node,+ cwd,+ ...releaseFacts(cwd, {project: false}),+ };+ Object.assign(ctx, await computerIntegrationsOutside(cwd));+ const checks = COMPUTER_CHECKS.map(fn => fn(ctx));+ const summary = {pass: 0, warn: 0, fail: 0, info: 0};+ for (const c of checks) summary[c.status] += 1;+ return {checks, summary};+}+/*** Ordered list of synchronous check functions. Append here to add a check.* (checkConfig is async and is awaited separately by {@link runChecks}.)@@ -1318,6 +1759,7 @@ export const SYNC_CHECKS = [checkAgentDocs,checkPeerDeps,checkPackageManager,+ checkCliCommand,];/**@@ -1329,7 +1771,8 @@ export const SYNC_CHECKS = [*/export async function runChecks(options = {}) {const cwd = options.cwd ?? process.cwd();- const coreDir = findCoreDir(cwd);+ if (outsideProject(cwd)) return runComputerChecks(cwd);+ const coreDir = findProjectCoreDir(cwd);// findConfigPath throws when multiple config files coexist. That's a// misconfiguration doctor exists to report — catch it and surface it through// checkConfig as a FAIL rather than crashing the whole diagnostic engine.@@ -1363,7 +1806,9 @@ export async function runChecks(options = {}) {/** @type {import('../../foundation/config/project.mjs').Project | null} */let project = null;try {- project = await Project.load(cwd);+ // Doctor judges the project, so it reads only the Core the project+ // installed, never a carried one (spec AST-081 FR3).+ project = await Project.load(cwd, {core: 'project'});} catch (err) {// A project the CLI cannot load leaves the checks that need it// skipped. The reason is kept: those checks and the config@@ -1466,6 +1911,8 @@ export async function runChecks(options = {}) {cwd,nodeVersion: process.versions.node,coreDir,+ ownCli: projectHasOwnCli(cwd),+ projectCore: projectCoreVersion(cwd),configPath,integrations,docsCatalog,@@ -1490,6 +1937,31 @@ export async function runChecks(options = {}) {checks.push(await checkConfig(ctx));}}+ const facts = releaseFacts(cwd, {project: true});+ checks.push(+ checkNewestRelease({+ nodeVersion: ctx.nodeVersion,+ answeredBy: facts.answeredBy,+ latest: facts.latest,+ projectLag: facts.projectLag,+ lastNoticeSkip: facts.lastNoticeSkip,+ lastCheckFailure: facts.lastCheckFailure,+ stateLock: facts.stateLock,+ }),+ );+ checks.push(+ checkCliOnPath({+ nodeVersion: ctx.nodeVersion,+ answeredBy: facts.answeredBy,+ latest: null,+ searchPathCommands: facts.searchPathCommands,+ }),+ );+ {+ const loadedNames = (project?.loadedIntegrations ?? []).map((/** @type {{name: string}} */ i) => i.name);+ const candidates = await computerIntegrationsToAdd(cwd, loadedNames);+ checks.push(checkComputerIntegrationsAvailable({installed: new Set(loadedNames), candidates, install: installCommandFor(cwd)}));+ }checks.push(await checkAuthoringDocs(ctx));checks.push(await checkCliDocs(ctx));checks.push(await checkDocsTree(ctx));diff --git a/packages/cli/api/doctor/doctor.test.mjs b/packages/cli/api/doctor/doctor.test.mjsindex 0747109577..195318416d 100644--- a/packages/cli/api/doctor/doctor.test.mjs+++ b/packages/cli/api/doctor/doctor.test.mjs@@ -21,6 +21,7 @@ import {docs} from '../docs/docs.mjs';import {auditCliSelfDocs} from '../../foundation/discovery/cli-self-docs.mjs';import {doctor,+ checkCliCommand,checkAuthoringDocs,checkCliDocs,checkDocsTree,@@ -31,6 +32,8 @@ import {checkVersionAlignment,checkPackageManager,} from './doctor.mjs';+import {formatCliCommand} from '../../foundation/env/package-manager.mjs';+import {Project} from '../../foundation/config/project.mjs';const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../..');const cwd = REPO;@@ -86,6 +89,30 @@ describe('doctor leaf', () => {}, SLOW);});+describe('doctor never reads the carried Core (spec AST-081 FR3)', () => {+ it('loads the project to read only its installed Core, in a project with nothing installed', async () => {+ const dir = mkProject({+ 'package.json': JSON.stringify({+ name: 'fresh-clone',+ dependencies: {'@astryxdesign/core': '^0.7.0'},+ }),+ });+ const load = vi.spyOn(Project, 'load');+ const coreDir = vi.spyOn(Project.prototype, 'coreDir');+ try {+ await doctor({cwd: dir});+ // Doctor's own project reads only the installed Core, and no Core a+ // project read during the run is the carried one.+ expect(load.mock.calls.some(([, options]) => options?.core === 'project')).toBe(true);+ expect(coreDir).toHaveBeenCalled();+ for (const result of coreDir.mock.results) expect(result.value).toBeNull();+ } finally {+ load.mockRestore();+ coreDir.mockRestore();+ }+ });+});+describe('integration issue check', () => {it('surfaces cross-package replacement warnings', () => {const check = checkIntegrationIssues({@@ -110,7 +137,7 @@ describe('integration issue check', () => {describe('doctor leaf — degradation & error paths', () => {it('does not crash on multiple config files; reports a config FAIL', async () => {const dir = mkProject({- 'package.json': '{"name":"x"}',+ 'package.json': '{"name":"x","dependencies":{"@astryxdesign/core":"*"}}','astryx.config.mjs': 'export default {};','astryx.config.js': 'export default {};',});@@ -123,7 +150,7 @@ describe('doctor leaf — degradation & error paths', () => {it('reports a config FAIL (not a crash) when astryx.config.mjs throws on import', async () => {const dir = mkProject({- 'package.json': '{"name":"x"}',+ 'package.json': '{"name":"x","dependencies":{"@astryxdesign/core":"*"}}','astryx.config.mjs': 'throw new Error("boom");\nexport default {};',});const r = await doctor({cwd: dir});@@ -134,7 +161,7 @@ describe('doctor leaf — degradation & error paths', () => {it('flags a non-object config default export as FAIL', async () => {const dir = mkProject({- 'package.json': '{"name":"x"}',+ 'package.json': '{"name":"x","dependencies":{"@astryxdesign/core":"*"}}','astryx.config.mjs': 'export default 42;',});const r = await doctor({cwd: dir});@@ -190,6 +217,102 @@ describe('doctor — checkVersionAlignment', () => {});});+describe("doctor — the project's own CLI and Core on different releases", () => {+ const cli = JSON.parse(+ fs.readFileSync(new URL('../../package.json', import.meta.url), 'utf8'),+ ).version;+ /** @param {string} core */+ const at = core => {+ const dir = mkProject({+ 'package-lock.json': '{}',+ 'node_modules/@astryxdesign/core/package.json': JSON.stringify({+ name: '@astryxdesign/core',+ version: core,+ }),+ });+ return checkVersionAlignment({+ cwd: dir,+ coreDir: path.join(dir, 'node_modules/@astryxdesign/core'),+ nodeVersion: '',+ configPath: null,+ configTheme: null,+ });+ };++ it('warns on any difference, patch included, and names the align command', () => {+ const older = at('0.0.1');+ expect(older.status).toBe('warn');+ expect(older.message).toContain(+ `This project's CLI ${cli} answers it, but its Core is 0.0.1`,+ );+ expect(older.fix).toBe(+ `To align them, run: npm install @astryxdesign/core@${cli}, then npx astryx upgrade --from 0.0.1 --apply.`,+ );+ const newer = at('99.0.0');+ expect(newer.fix).toBe(+ 'To align them, run: npm install @astryxdesign/[email protected].',+ );+ expect(at(cli).status).toBe('pass');+ });++ it('in a project with no CLI of its own, warns that the started copy answered and names the command that adds the CLI at Core', () => {+ const dir = mkProject({+ 'package-lock.json': '{}',+ 'node_modules/@astryxdesign/core/package.json': JSON.stringify({+ name: '@astryxdesign/core',+ version: '0.0.1',+ }),+ });+ const c = checkVersionAlignment({+ cwd: dir,+ coreDir: path.join(dir, 'node_modules/@astryxdesign/core'),+ nodeVersion: '',+ configPath: null,+ configTheme: null,+ ownCli: false,+ });+ expect(c.status).toBe('warn');+ expect(c.message).toBe(+ `This project has no Astryx CLI installed; CLI ${cli}, the one you started, answered while its Core is 0.0.1.`,+ );+ expect(c.fix).toBe('To match, run: npm install @astryxdesign/[email protected].');+ });+});++describe('checkCliCommand', () => {+ it('is informational when no integration declares a command', () => {+ const dir = mkProject({'pnpm-lock.yaml': ''});+ const c = checkCliCommand({cwd: dir, integrations: [{name: '@acme/a'}]});+ expect(c).toMatchObject({id: 'cli-command', status: 'info'});+ });++ it('passes and names the command and who declared it', () => {+ const c = checkCliCommand({+ cwd: mkProject({}),+ integrations: [{name: '@acme/a', cliCommand: 'acme astryx'}],+ });+ expect(c).toMatchObject({id: 'cli-command', status: 'pass'});+ expect(c.message).toContain('`acme astryx`');+ expect(c.message).toContain('@acme/a');+ });++ it('warns when integrations declare different commands', () => {+ const dir = mkProject({'pnpm-lock.yaml': ''});+ const c = checkCliCommand({+ cwd: dir,+ integrations: [+ {name: '@acme/a', cliCommand: 'acme astryx'},+ {name: '@acme/b', cliCommand: 'other astryx'},+ ],+ });+ expect(c).toMatchObject({id: 'cli-command', status: 'warn'});+ expect(c.message).toContain('@acme/a (`acme astryx`)');+ expect(c.message).toContain('@acme/b (`other astryx`)');+ expect(c.message).toContain('pnpm dlx @astryxdesign/cli');+ expect(c.fix).toContain('cliCommand');+ });+});+describe('checkPackageManager', () => {it('is informational when one lockfile answers', () => {const dir = mkProject({'pnpm-lock.yaml': ''});@@ -529,7 +652,7 @@ describe('checkAuthoringDocs', () => {it('passes when every authoring self-doc is reachable and fits one read', async () => {const c = await checkAuthoringDocs();expect(c).toMatchObject({id: 'authoring-docs', status: 'pass'});- expect(c.message).toContain('astryx docs authoring');+ expect(c.message).toContain(formatCliCommand('docs authoring'));}, SLOW);});@@ -557,7 +680,7 @@ describe('checkCliDocs', () => {id: 'cli-docs',label: 'CLI docs',status: 'pass',- message: `All ${audit.docs} CLI docs are readable: ${audit.tree} in the \`astryx docs cli\` tree and ${audit.authoring} in \`astryx docs authoring\`.`,+ message: `All ${audit.docs} CLI docs are readable: ${audit.tree} in the \`${formatCliCommand('docs cli')}\` tree and ${audit.authoring} in \`${formatCliCommand('docs authoring')}\`.`,});},SLOW,@@ -591,7 +714,7 @@ describe('checkCliDocs', () => {label: 'CLI docs',status: 'fail',message:- '2 problems: api/alpha/alpha.doc.mjs has no namespace, so no `astryx docs` topic reads it; clients/cli/commands/beta.doc.mjs has namespace "cli", which no `astryx docs` topic reads',+ `2 problems: api/alpha/alpha.doc.mjs has no namespace, so no \`${formatCliCommand('docs')}\` topic reads it; clients/cli/commands/beta.doc.mjs has namespace "cli", which no \`${formatCliCommand('docs')}\` topic reads`,fix: CLI_DOCS_FIX,});},@@ -667,7 +790,7 @@ describe('checkDocsTree', () => {describe('checkAuthoringDocs against the public authoring surface', () => {const NAMESPACE = 'doctypes/namespace/namespace.doc.mjs';const NAMESPACE_TYPES =- 'NamespaceDoc, NamespaceProviderScope, NamespaceSlotAcceptance, NamespaceSlot, NamespaceAdoptionSource, NamespaceAdoptionRule from doctypes/namespace/type.ts have no doc in `astryx docs authoring`';+ `NamespaceDoc, NamespaceProviderScope, NamespaceSlotAcceptance, NamespaceSlot, NamespaceAdoptionSource, NamespaceAdoptionRule from doctypes/namespace/type.ts have no doc in \`${formatCliCommand('docs authoring')}\``;const SURFACE_FIX ='Put a self-doc beside each module whose types @astryxdesign/cli/authoring exports and list it in AUTHORING_SELF_DOCS; export what each listed self-doc documents, or remove that self-doc.';@@ -697,7 +820,7 @@ describe('checkAuthoringDocs against the public authoring surface', () => {id: 'authoring-docs',label: 'Authoring docs',status: 'pass',- message: `All ${AUTHORING_SELF_DOCS.length} authoring schemas are readable in \`astryx docs authoring\`.`,+ message: `All ${AUTHORING_SELF_DOCS.length} authoring schemas are readable in \`${formatCliCommand('docs authoring')}\`.`,});},SLOW,@@ -726,7 +849,7 @@ describe('checkAuthoringDocs against the public authoring surface', () => {});expect(c.status).toBe('fail');expect(c.message).toBe(- `2 problems: ${NAMESPACE} is not in \`astryx docs authoring\`; ${NAMESPACE_TYPES}: ${NAMESPACE} is not listed in AUTHORING_SELF_DOCS`,+ `2 problems: ${NAMESPACE} is not in \`${formatCliCommand('docs authoring')}\`; ${NAMESPACE_TYPES}: ${NAMESPACE} is not listed in AUTHORING_SELF_DOCS`,);},SLOW,@@ -824,7 +947,7 @@ describe('checkAuthoringDocs against the public authoring surface', () => {expect(c.fix).toBe(SURFACE_FIX);expect(c.message).toMatch(new RegExp(- `^[A-Za-z, ]+ from ${escape(module)} have no doc in \`astryx docs authoring\`: no self-doc sits beside ${escape(module)}$`,+ `^[A-Za-z, ]+ from ${escape(module)} have no doc in \`${escape(formatCliCommand('docs authoring'))}\`: no self-doc sits beside ${escape(module)}$`,),);for (const name of names) {@@ -867,7 +990,7 @@ describe('checkAuthoringDocs against the public authoring surface', () => {expect(await checkAuthoringDocs()).toMatchObject({status: 'fail',message:- '`astryx docs authoring` could not be read: no built-in docs',+ `\`${formatCliCommand('docs authoring')}\` could not be read: no built-in docs`,fix: SURFACE_FIX,});} finally {@@ -888,7 +1011,7 @@ describe('checkAuthoringDocs against the public authoring surface', () => {const c = await checkAuthoringDocs(undefined, {root});expect(c.status).toBe('fail');expect(c.message).toContain(- '@astryxdesign/cli/authoring exports no types, so nothing was compared with `astryx docs authoring`',+ `@astryxdesign/cli/authoring exports no types, so nothing was compared with \`${formatCliCommand('docs authoring')}\``,);},SLOW,@@ -1098,7 +1221,7 @@ describe('doctor says why it skipped and what it checked', () => {expect(by.config.message).toMatch(/^astryx\.config\.mjs loads, but the CLI could not load the project from it: .*integrations/,);- expect(by.config.fix).toContain('astryx docs authoring config');+ expect(by.config.fix).toContain(' docs authoring config`');for (const id of ['implicit-integrations', 'provider-identity']) {expect(by[id].message).toMatch(/^Skipped — the project configuration could not be read: .*integrations/,@@ -1225,7 +1348,7 @@ describe('a configured integration that cannot load fails the gate', () => {/^1 of 1 integration named in astryx\.config could not be loaded, so it contributes nothing: @acme\/widgets \(/,);expect(check.message).toMatch(reason);- expect(check.fix).toContain('astryx doctor integration validate <package>');+ expect(check.fix).toContain(' doctor integration validate <package>`');expect(summary.fail).toBe(1);},SLOW,diff --git a/packages/cli/api/doctor/release-checks.test.mjs b/packages/cli/api/doctor/release-checks.test.mjsnew file mode 100644index 0000000000..38bb80d879--- /dev/null+++ b/packages/cli/api/doctor/release-checks.test.mjs@@ -0,0 +1,156 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file doctor's release checks (spec AST-081 FR10, FR11): the newest+ * release beside a project's or the global copy's, with the fix, and the+ * `astryx` commands on the search path.+ */++import {describe, expect, it} from 'vitest';+import {checkCliOnPath, checkNewestRelease} from './doctor.mjs';++const answeredBy = {cli: '0.7.1', core: '0.7.1', copy: 'project'};++/** @param {Partial<import('../../foundation/env/search-path.mjs').SearchPathCommand>} row */+const row = row => ({+ file: '/bin/astryx',+ astryx: true,+ cliRoot: '/lib/cli',+ version: '0.8.0',+ handsOff: true,+ ...row,+});++describe('checkNewestRelease', () => {+ it("names a project's install and upgrade commands", () => {+ const check = checkNewestRelease({+ nodeVersion: '24.0.0',+ answeredBy,+ latest: '0.7.3',+ projectLag: {+ root: '/app',+ current: '0.7.1',+ newest: '0.7.3',+ install: 'npm install @astryxdesign/[email protected] @astryxdesign/[email protected]',+ upgrade: 'npx astryx upgrade --from 0.7.1 --apply',+ },+ });+ expect(check).toEqual({+ id: 'newest-release',+ label: 'Newest release',+ status: 'info',+ message: 'This project uses Astryx 0.7.1; 0.7.3 is the newest.',+ fix: 'To upgrade, run: npm install @astryxdesign/[email protected] @astryxdesign/[email protected], then npx astryx upgrade --from 0.7.1 --apply.',+ });+ });++ it('adds the last notice skip and a held state lock, for diagnosis', () => {+ const check = checkNewestRelease({+ nodeVersion: '24.0.0',+ answeredBy,+ latest: '0.7.1',+ lastNoticeSkip: {+ key: 'global',+ reason: 'already-shown',+ at: Date.UTC(2026, 9, 20, 18),+ },+ stateLock: {pid: 42, host: 'mac', since: Date.UTC(2026, 9, 20, 17)},+ });+ expect(check.message).toBe(+ 'No newer release is known: the newest is 0.7.1. ' ++ 'Last update notice skipped 2026-10-20T18:00:00.000Z (global): it had already printed that day. ' ++ "The state file's lock is held by process 42 on mac since 2026-10-20T17:00:00.000Z.",+ );+ });++ it('says when the last update check did not reach the registry, and why', () => {+ const check = checkNewestRelease({+ nodeVersion: '24.0.0',+ answeredBy,+ latest: null,+ lastCheckFailure: {+ at: Date.UTC(2026, 9, 20, 18),+ reason: 'npm-failed: ECONNREFUSED',+ },+ });+ expect(check.message).toContain(+ 'The last update check, 2026-10-20T18:00:00.000Z, did not reach the registry: npm failed (ECONNREFUSED); its registry and proxy settings decide where it asks.',+ );+ expect(+ checkNewestRelease({+ nodeVersion: '24.0.0',+ answeredBy,+ latest: null,+ lastCheckFailure: {at: 0, reason: 'npm-missing'},+ }).message,+ ).toContain('did not reach the registry: npm could not be started.');+ });++ it("names the global copy's upgrade, after the Node the newest release needs", () => {+ const check = checkNewestRelease({+ nodeVersion: '22.13.0',+ answeredBy: {...answeredBy, copy: 'carried'},+ latest: '0.8.0',+ globalBehind: {+ current: '0.7.1',+ newest: '0.8.0',+ node: '>=99',+ command: 'pnpm add -g @astryxdesign/cli@latest',+ },+ });+ expect(check).toEqual({+ id: 'newest-release',+ label: 'Newest release',+ status: 'info',+ message:+ 'A new release of Astryx is available: 0.7.1 → 0.8.0. The CLI installed for the computer stays on its release until you upgrade it.',+ fix: `To upgrade, install Node >=99 (this computer runs Node ${process.versions.node}), then run: pnpm add -g @astryxdesign/cli@latest.`,+ });+ });+});++describe('checkCliOnPath', () => {+ const base = {nodeVersion: '24.0.0', answeredBy, latest: null};++ it('passes for a release that hands off, and lists the later ones', () => {+ const check = checkCliOnPath({+ ...base,+ searchPathCommands: [+ row({}),+ row({file: '/other/astryx', version: '0.7.1', handsOff: false}),+ ],+ });+ expect(check).toMatchObject({+ status: 'pass',+ message:+ '`astryx` runs /bin/astryx (CLI 0.8.0). Later on the search path: /other/astryx (CLI 0.7.1).',+ });+ });++ it('warns about a first release that predates the hand-off, naming the replacement', () => {+ expect(+ checkCliOnPath({+ ...base,+ searchPathCommands: [row({version: '0.7.1', handsOff: false})],+ }),+ ).toMatchObject({+ status: 'warn',+ fix: 'To upgrade, run: `npm i -g @astryxdesign/cli@latest`.',+ });+ });++ it('warns about another program first, and informs when there is none', () => {+ expect(+ checkCliOnPath({+ ...base,+ searchPathCommands: [+ row({astryx: false, cliRoot: null, version: null, handsOff: null}),+ ],+ }),+ ).toMatchObject({status: 'warn'});+ expect(checkCliOnPath({...base, searchPathCommands: []})).toMatchObject({+ status: 'info',+ fix: 'To run the CLI in any folder, install it for the computer: `npm i -g @astryxdesign/cli`.',+ });+ });+});diff --git a/packages/cli/api/doctor/theme-checks.mjs b/packages/cli/api/doctor/theme-checks.mjsindex 42e8dcf1ba..bd8427eb96 100644--- a/packages/cli/api/doctor/theme-checks.mjs+++ b/packages/cli/api/doctor/theme-checks.mjs@@ -32,7 +32,10 @@ import {themeRecordOwner,validateThemePrivateInputs,} from './_adapter.mjs';-import {getCliInvocation} from '../../foundation/env/package-manager.mjs';+import {+ getCliInvocation,+ formatCliCommand,+} from '../../foundation/env/package-manager.mjs';import {satisfiesRange} from '../../foundation/env/semver.mjs';import {logger} from '../logger.mjs';@@ -69,7 +72,7 @@ function unavailableChecks(message, moduleError = null) {moduleError && id === 'theme-module' ? moduleError.message : message,...(moduleError && id === 'theme-module'? {- fix: 'Keep one CLI-generated astryx-themes.ts or astryx-themes.js file, then run `astryx theme add <slug>`.',+ fix: `Keep one CLI-generated astryx-themes.ts or astryx-themes.js file, then run \`${formatCliCommand('theme add <slug>')}\`.`,}: {}),}));@@ -794,6 +797,16 @@ export async function checkAppThemes(cwd) {message:'Could not check local build freshness until every local output resolves.',});+ } else if (localThemes.length > 0 && !findDoctorCoreDir(state.projectDir)) {+ // A build reads Core, and doctor reads only the Core the project+ // installed, never the one the answering copy carries (spec AST-081 FR3).+ checks.push({+ id: 'theme-local-builds',+ label: 'Local theme build freshness',+ status: 'info',+ message:+ "The project's Core isn't installed, so local theme builds were not checked. Install the project's dependencies, then run doctor again.",+ });} else if (localThemes.length === 0) {checks.push({id: 'theme-local-builds',@@ -817,7 +830,7 @@ export async function checkAppThemes(cwd) {const receipt = await themeBuild(path.join(availableTheme.sourceDir, availableTheme.entry),{check: true},- {cwd: state.projectDir},+ {cwd: state.projectDir, projectCore: true},);if (receipt == null ||diff --git a/packages/cli/api/doctor/theme-checks.test.mjs b/packages/cli/api/doctor/theme-checks.test.mjsindex d1dabfa07f..f871183fda 100644--- a/packages/cli/api/doctor/theme-checks.test.mjs+++ b/packages/cli/api/doctor/theme-checks.test.mjs@@ -4,6 +4,7 @@import {afterEach, describe, expect, it} from 'vitest';import * as fs from 'node:fs';+import * as os from 'node:os';import * as path from 'node:path';import {spawnSync} from 'node:child_process';import {checkAppThemes, checkThemes} from './theme-checks.mjs';@@ -12,6 +13,8 @@ import {themeAdd} from '../theme/add/add.mjs';import {themeEject} from '../theme/eject/eject.mjs';import {themeBuild} from '../theme/build/build.mjs';import {parseThemeModuleRecord} from '../../foundation/config/theme-state.mjs';+import {CLI_VERSION} from '../../test-utils/release-fixtures.mjs';+import {globalCli} from '../../test-utils/global-local-fixtures.mjs';/** @type {string[]} */const dirs = [];@@ -25,11 +28,12 @@ function write(file, content) {/*** @param {Array<{slug: string, css?: string, fontFamily?: string, fontCss?: string}>} themeSpecs- * @param {{peerRange?: string, importModule?: boolean}} [options]+ * @param {{peerRange?: string, importModule?: boolean, root?: string}} [options]+ * `root`: the folder the fixture is made in (default: this package)*/async function fixture(themeSpecs = [{slug: 'ocean'}], options = {}) {const dir = fs.mkdtempSync(- path.join(process.cwd(), '.astryx-doctor-themes-'),+ path.join(options.root ?? process.cwd(), '.astryx-doctor-themes-'),);dirs.push(dir);fs.mkdirSync(path.join(dir, 'src'), {recursive: true});@@ -47,7 +51,7 @@ async function fixture(themeSpecs = [{slug: 'ocean'}], options = {}) {);write(path.join(dir, 'node_modules/@astryxdesign/core/package.json'),- JSON.stringify({name: '@astryxdesign/core', version: '1.0.0'}),+ JSON.stringify({name: '@astryxdesign/core', version: CLI_VERSION}),);const packageDir = path.join(dir, 'node_modules/@acme/themes');@@ -67,7 +71,7 @@ async function fixture(themeSpecs = [{slug: 'ocean'}], options = {}) {version: '1.0.0',type: 'module',peerDependencies: {- '@astryxdesign/core': options.peerRange ?? '^1.0.0',+ '@astryxdesign/core': options.peerRange ?? `^${CLI_VERSION}`,},exports: exportsMap,}),@@ -592,6 +596,82 @@ describe('app-theme doctor checks', () => {});});+ it("check 5 is info, and builds nothing, when the project's Core is not installed (spec AST-081 FR3)", async () => {+ // Outside this repository, whose own installed Core would be found above.+ const {dir} = await fixture(undefined, {root: os.tmpdir()});+ await themeEject('ocean', {cwd: dir, package: '@acme/themes'});+ const sourceFile = path.join(dir, 'src/themes/ocean/oceanTheme.ts');+ fs.writeFileSync(+ sourceFile,+ "const oceanTheme = {name: 'ocean', tokens: {'--color-bg': '#000'}};\nexport {oceanTheme};\nexport default oceanTheme;\n",+ );+ await themeBuild(sourceFile, {}, {cwd: dir});+ await themeAdd('ocean', {cwd: dir, import: true});+ // A fresh clone: the project declares Core but has not installed it.+ fs.rmSync(path.join(dir, 'node_modules/@astryxdesign/core'), {+ recursive: true,+ force: true,+ });++ expect(check(await checkAppThemes(dir), 'theme-local-builds')).toEqual({+ id: 'theme-local-builds',+ label: 'Local theme build freshness',+ status: 'info',+ message:+ "The project's Core isn't installed, so local theme builds were not checked. Install the project's dependencies, then run doctor again.",+ });+ // A build that may read only the project's Core refuses instead of+ // reading another one.+ await expect(+ themeBuild(sourceFile, {check: true}, {cwd: dir, projectCore: true}),+ ).rejects.toMatchObject({code: 'ERR_CORE_NOT_FOUND'});+ });++ it.skipIf(process.platform === 'win32')(+ 'check 5 through a CLI installed for the computer, in a fresh clone: info, and no carried Core is read or fetched',+ async () => {+ const home = fs.mkdtempSync(+ path.join(os.tmpdir(), 'astryx-doctor-home-'),+ );+ dirs.push(home);+ const g = globalCli('npm', CLI_VERSION, {root: home});+ const {dir} = await fixture(undefined, {root: os.tmpdir()});+ await themeEject('ocean', {cwd: dir, package: '@acme/themes'});+ const sourceFile = path.join(dir, 'src/themes/ocean/oceanTheme.ts');+ await themeBuild(sourceFile, {}, {cwd: dir});+ await themeAdd('ocean', {cwd: dir, import: true});+ fs.rmSync(path.join(dir, 'node_modules/@astryxdesign/core'), {+ recursive: true,+ force: true,+ });+ const cache = path.join(home, '.cache');+ const result = spawnSync(process.execPath, [g.bin, 'doctor', '--json'], {+ cwd: dir,+ encoding: 'utf8',+ timeout: 120_000,+ env: {+ PATH: path.dirname(process.execPath),+ HOME: home,+ USERPROFILE: home,+ XDG_CACHE_HOME: cache,+ XDG_CONFIG_HOME: path.join(home, '.config'),+ // Nothing can be fetched: a fetch of the carried Core would fail.+ npm_config_registry: 'http://127.0.0.1:9/',+ npm_config_update_notifier: 'false',+ NO_COLOR: '1',+ },+ });+ const checks = JSON.parse(result.stdout).data.checks;+ expect(checks.find(c => c.id === 'theme-local-builds')).toMatchObject({+ status: 'info',+ });+ expect(+ fs.existsSync(path.join(cache, 'astryx', 'releases', CLI_VERSION)),+ ).toBe(false);+ },+ 180_000,+ );+it('check 6 ignores private variables generated from guaranteed component properties', async () => {const {dir, packageDir} = await fixture([{@@ -746,7 +826,7 @@ describe('app-theme doctor checks', () => {for (const name of ['@astryxdesign/core', '@astryxdesign/theme-neutral']) {write(path.join(root, 'node_modules', name, 'package.json'),- JSON.stringify({name, version: '1.0.0'}),+ JSON.stringify({name, version: CLI_VERSION}),);}const app = path.join(root, 'packages/app');@@ -756,8 +836,8 @@ describe('app-theme doctor checks', () => {name: 'app',private: true,dependencies: {- '@astryxdesign/core': '1.0.0',- '@astryxdesign/theme-neutral': '1.0.0',+ '@astryxdesign/core': CLI_VERSION,+ '@astryxdesign/theme-neutral': CLI_VERSION,},astryx: {theme: '@astryxdesign/theme-neutral'},}),diff --git a/packages/cli/api/error.mjs b/packages/cli/api/error.mjsindex 89a313051b..44235ee9f1 100644--- a/packages/cli/api/error.mjs+++ b/packages/cli/api/error.mjs@@ -78,3 +78,28 @@ export function writeFailed(target, cwd, cause, unrestored = []) {ERROR_CODES.ERR_WRITE_FAILED,);}++/**+ * Locate the Core a command answers from (`requireCoreDir` in+ * foundation/fs/paths.mjs), raising its coded failure as an AstryxError:+ * ERR_CORE_NOT_FOUND with no Core to answer from, ERR_VERSIONS_UNAVAILABLE+ * when the carried Core is needed and cannot be installed.+ * @param {(cwd: string) => string} lookup the foundation lookup+ * @param {string} cwd+ * @returns {string}+ */+export function coreDirOrThrow(lookup, cwd) {+ try {+ return lookup(cwd);+ } catch (error) {+ const code = /** @type {any} */ (error)?.code;+ if (typeof code === 'string' && code.startsWith('ERR_')) {+ throw new AstryxError(+ error instanceof Error ? error.message : String(error),+ undefined,+ code,+ );+ }+ throw error;+ }+}diff --git a/packages/cli/api/hook/_adapter.mjs b/packages/cli/api/hook/_adapter.mjsindex e8a2bde137..fc69a640c0 100644--- a/packages/cli/api/hook/_adapter.mjs+++ b/packages/cli/api/hook/_adapter.mjs@@ -14,14 +14,14 @@* @position api/hook/_adapter.mjs — shared by ./list, ./detail, ./detail/params*/-import {findCoreDir} from '../../foundation/fs/paths.mjs';+import {requireCoreDir} from '../../foundation/fs/paths.mjs';import {findHookDoc,getAllHookNames,} from '../../foundation/discovery/hook-discovery.mjs';import {loadDocs} from '../../foundation/discovery/component-loader.mjs';import {levenshteinDistance} from '../../foundation/text/string-utils.mjs';-import {AstryxError} from '../error.mjs';+import {AstryxError, coreDirOrThrow} from '../error.mjs';import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';/** The package that owns Core's components, hooks, and codemods. */@@ -34,15 +34,7 @@ export {CORE_PROVIDER_ID as CORE_PACKAGE} from '../../foundation/identity/provid* @returns {string} Absolute path to the core package directory.*/export function resolveCoreDir(cwd) {- const coreDir = findCoreDir(cwd);- if (!coreDir) {- throw new AstryxError(- 'Could not find @astryxdesign/core package',- undefined,- ERROR_CODES.ERR_CORE_NOT_FOUND,- );- }- return coreDir;+ return coreDirOrThrow(requireCoreDir, cwd);}/**diff --git a/packages/cli/api/hook/hook.doc.mjs b/packages/cli/api/hook/hook.doc.mjsindex d233e10f60..f98881c7b7 100644--- a/packages/cli/api/hook/hook.doc.mjs+++ b/packages/cli/api/hook/hook.doc.mjs@@ -90,6 +90,10 @@ export const doc = {code: 'ERR_CORE_NOT_FOUND',when: '@astryxdesign/core cannot be resolved from cwd',},+ {+ code: 'ERR_VERSIONS_UNAVAILABLE',+ when: 'outside a project, or in a project with nothing installed, the Core of the release that answers is not beside it or cached, and cannot be installed into the per-user cache (offline, a registry without it, or an unwritable cache)',+ },{code: 'ERR_UNKNOWN_CATEGORY',when: 'options.category is not a string or matches no known category',diff --git a/packages/cli/api/init/_adapter.mjs b/packages/cli/api/init/_adapter.mjsnew file mode 100644index 0000000000..2435a84d5d--- /dev/null+++ b/packages/cli/api/init/_adapter.mjs@@ -0,0 +1,59 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Environment adapter for `init --user`: the home folder, the settings+ * file, the per-user state, and the search path (spec AST-081 FR7, FR8;+ * architecture:cli-surface INV21).+ *+ * @input the home folder, the settings file, the search path+ * @output the computer-level agent text written or removed, with the setting+ * and the links recorded+ * @position packages/cli/api/init — imported by the user leaf only+ */++import * as os from 'node:os';+import {+ COMPUTER_COMMAND,+ COMPUTER_INSTALL_STEP,+ astryxOnSearchPath,+ computerAgentCommand,+ displayHomePath,+ removeComputerAgentText,+ writeComputerAgentText,+} from '../../foundation/agent-docs/computer-agent-text.mjs';+import {+ computerAgentTextSettings,+ recordComputerAgentTextSettings,+} from '../../foundation/env/user-settings.mjs';+import {recordAgentTextWritten} from '../../foundation/release/global-state.mjs';+import {cliVersion} from '../../foundation/release/run-context.mjs';++export {COMPUTER_COMMAND, COMPUTER_INSTALL_STEP, displayHomePath};++/**+ * Write or refresh the computer-level agent text, or remove it, and record+ * the setting and the links Astryx made; after a write, record the release+ * that wrote it.+ * @param {{remove: boolean}} options+ * @returns {{home: string, command: string, files: import('./init.type.mjs').InitUserFile[], cliOnSearchPath: boolean}}+ */+export function applyComputerAgentText({remove}) {+ const home = os.homedir();+ const command = computerAgentCommand();+ const recorded = computerAgentTextSettings().links;+ /** @type {import('./init.type.mjs').InitUserFile[]} */+ let files;+ if (remove) {+ files = removeComputerAgentText({home, links: recorded});+ recordComputerAgentTextSettings({install: false, links: []});+ } else {+ const written = writeComputerAgentText({home, command});+ files = written.rows;+ recordComputerAgentTextSettings({+ install: true,+ links: [...new Set([...recorded, ...written.links])],+ });+ recordAgentTextWritten(cliVersion());+ }+ return {home, command, files, cliOnSearchPath: astryxOnSearchPath()};+}diff --git a/packages/cli/api/init/init.doc.mjs b/packages/cli/api/init/init.doc.mjsindex 1c1c82f807..62bf19599d 100644--- a/packages/cli/api/init/init.doc.mjs+++ b/packages/cli/api/init/init.doc.mjs@@ -21,10 +21,14 @@ export const doc = {'agent-docs cheat sheet, including guidance from configured integrations, and ' +"prints getting-started guidance; `features` / `all` print only the chosen features' " +'guidance instead (the theme feature also writes the annotated theme template). ' +- 'With `removeAgents` it removes the managed agent-docs block instead of installing.',+ 'With `removeAgents` it removes the managed agent-docs block instead of installing. ' ++ 'Outside a project it writes the same files but prints no getting-started steps and no step that adds a theme to an app, since those set up a project the folder does not have. ' ++ "With `user` it sets up the computer instead of the folder: it writes the computer-level agent text, one skill file at `~/.agents/skills/astryx/SKILL.md`, linked into the skill folders of agents that read only their own (`~/.claude/skills` always; Kiro, Windsurf, Letta, Xcode's coding assistant, and `~/.config/agents/skills` when that folder exists), with a managed copy for Continue, whose scanner skips links,, telling agents anywhere on the computer that Astryx is there and when to use it; with `user` and `removeAgents` it removes the file and the links it made and records that the text is turned off. " ++ 'The CLI installed for the computer refreshes the file in the background after each upgrade; package install scripts, project setup, and upgrade never write it.' ++ " In global mode: with `cwd` outside a project, it writes the agent docs and prints no getting-started steps; `user` writes only the agent guide for the computer, in the home folder, and touches nothing in `cwd`. See {@link namespace:global} and {@link generic:computer-agent-guide}.",importPath: '@astryxdesign/cli/api',signature:- 'init(options?: InitOptions, ctx?: {cwd?: string}): Promise<InitRunResponse | InitRemoveResponse>',+ 'init(options?: InitOptions, ctx?: {cwd?: string}): Promise<InitRunResponse | InitRemoveResponse | InitUserResponse>',keywords: ['init', 'setup', 'install', 'scaffold', 'agents', 'bootstrap'],params: [{@@ -41,13 +45,24 @@ export const doc = {{name: 'options.removeAgents',type: 'boolean',- description: 'Remove the managed agent-docs block instead of installing.',+ description:+ 'Remove the managed agent-docs block instead of installing. With `user`, remove the computer-level agent text instead.',+ },+ {+ name: 'options.user',+ type: 'boolean',+ description:+ "Write or refresh the computer-level agent text instead of setting up `ctx.cwd`: one skill file at `~/.agents/skills/astryx/SKILL.md` in the current user's home folder, linked (a folder symlink with a relative target, a junction on Windows, or a copy where neither can be made) into `~/.claude/skills/astryx`, and into the skills folder of Kiro, Windsurf, Letta, Xcode's coding assistant, and `~/.config/agents/skills` when that folder exists; Continue, whose scanner skips links, gets a managed copy, refreshed with the file. " ++ 'The text uses the `astryx` command, or the command of the host that started the run; an integration\'s `cliCommand` never applies. ' ++ 'Records the links it made, or with `removeAgents` that the text is turned off, in `astryx/settings.json` in the per-user configuration folder. ' ++ 'A file without the Astryx markers, one edited since Astryx wrote it, or a symlink, is kept as it is, and so is anything at a link target that Astryx did not create. When no `astryx` command on the computer runs the Astryx CLI, the text is still written and the receipt carries a warning to install the CLI for the computer (`npm i -g @astryxdesign/cli`). ' ++ 'Cannot be combined with `features`, `all`, `agent`, or `agentDocsPath`.',},{name: 'options.agent',type: 'string',description:- 'Agent preset: claude, cursor, codex, hermes, muse, all. Used only when the agents feature runs.',+ 'Agent preset: claude, cursor, codex, hermes, muse, all. Used only when the agents feature runs. Refused with `user`.',},{name: 'options.agentDocsPath',@@ -71,22 +86,27 @@ export const doc = {{type: 'init.run',description:- 'The install receipt: the `mode` (`default` | `features`), the features run, agent-doc files written, any soft docsError, the theme-template outcome (`created` | `skipped` | `failed`) plus its path, the page-template outcome (`workflow` | `created` | `skipped`) plus its path, and whether the next-steps were emitted.',+ 'The install receipt: the `mode` (`default` | `features`), the features run, agent-doc files written, any soft docsError, the theme-template outcome (`created` | `skipped` | `failed`) plus its path, the page-template outcome (`workflow` | `created` | `skipped`) plus its path, and whether the next-steps were emitted (never outside a project).',},{type: 'init.remove',description:'The removal receipt, returned when `removeAgents` is set: `data.removed` is true when a managed agent-docs block was found and removed, and false when there was none to remove.',},+ {+ type: 'init.user',+ description:+ 'The computer-level agent text receipt, returned when `user` is set: `data.files`, one `{path, action, reason?}` per path acted on (`~/.agents/skills/astryx/SKILL.md`, then each link to its folder, such as `~/.claude/skills/astryx`; action `written` | `linked` | `unchanged` | `removed` | `absent` | `kept`; `reason` on `kept`: `edited` | `not-astryx`), `data.command` (the command the text names), and `data.warnings`.',+ },],throws: [{code: 'ERR_INVALID_ARGUMENT',- when: '--remove-agents is combined with --features, --all, --agent, or --agent-docs-path; or --all is combined with --features',+ when: '--remove-agents is combined with --features, --all, --agent, or --agent-docs-path; --user is combined with --features, --all, --agent, or --agent-docs-path; or --all is combined with --features',},{code: 'ERR_UNKNOWN_AGENT',- when: 'the agents feature runs (default mode, features includes agents, or all) and `agent` is not one of claude, cursor, codex, hermes, muse, all',+ when: 'the agents feature runs (default mode, features includes agents, or all) and `agent` is not one of claude, cursor, codex, hermes, muse, all',},{code: 'ERR_UNKNOWN_FEATURE',@@ -109,6 +129,7 @@ export const doc = {{label: 'Default setup', code: 'const r = await init();'},{label: 'All features', code: 'await init({all: true});'},{label: 'Remove agent docs', code: 'await init({removeAgents: true});'},+ {label: 'Agent text for the whole computer', code: 'const r = await init({user: true});\nfor (const w of r.data.warnings) console.warn(w);'},],command: 'init',related: ['doctor', 'upgrade', 'build', 'themeTemplate'],diff --git a/packages/cli/api/init/init.mjs b/packages/cli/api/init/init.mjsindex 1edec29783..894d831c82 100644--- a/packages/cli/api/init/init.mjs+++ b/packages/cli/api/init/init.mjs@@ -10,6 +10,9 @@* install path (agent-docs, theme +* page-building guidance, template)* - `init.remove` (remove/remove.mjs) — the `--remove-agents` path+ * - `init.user` (user/user.mjs) — the `--user` path: the+ * computer-level agent text, written+ * or (with `--remove-agents`) removed** This module also re-exports the leaf symbols the CLI + tests import by name* (`getNextSteps`) so api/index.mjs, the command handler@@ -18,6 +21,7 @@import {run} from './run/run.mjs';import {remove} from './remove/remove.mjs';+import {user} from './user/user.mjs';import {AstryxError} from '../error.mjs';import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';@@ -32,17 +36,37 @@ export {getNextSteps} from './run/run.mjs';*//**- * Run the non-interactive init flow. Dispatches to the remove leaf when- * `--remove-agents` is set, otherwise to the install (run) leaf, and returns- * that leaf's receipt. Progress is emitted through `logger` (silent by+ * Run the non-interactive init flow. Dispatches to the user leaf when+ * `--user` is set (it writes, or with `--remove-agents` removes, the+ * computer-level agent text and nothing in the folder), to the remove leaf+ * when `--remove-agents` is set, otherwise to the install (run) leaf, and+ * returns that leaf's receipt. Progress is emitted through `logger` (silent by* default); unknown feature or template names throw AstryxError with a stable* code.** @param {InitOptions} [options]* @param {{cwd?: string}} [ctx]- * @returns {Promise<import('./init.type.mjs').InitRunResponse | import('./init.type.mjs').InitRemoveResponse>}+ * @returns {Promise<import('./init.type.mjs').InitRunResponse | import('./init.type.mjs').InitRemoveResponse | import('./init.type.mjs').InitUserResponse>}*/export async function init(options = {}, {cwd = process.cwd()} = {}) {+ if (options.user) {+ // Its own path: fixed files in the home folder, never the project+ // agent-docs resolution, so it works the same in every folder.+ const refused = [+ options.features ? '--features' : null,+ options.all ? '--all' : null,+ options.agentDocsPath ? '--agent-docs-path' : null,+ options.agent ? '--agent' : null,+ ].filter(Boolean);+ if (refused.length > 0) {+ throw new AstryxError(+ `\`--user\` cannot be combined with ${refused.join(', ')}: it writes one skill file for every agent on the computer, linked into the folders agents read, with no features, agents, or path to choose.`,+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );+ }+ return user({remove: Boolean(options.removeAgents)});+ }if (options.removeAgents) {const ignored = [options.features ? '--features' : null,diff --git a/packages/cli/api/init/init.type.mjs b/packages/cli/api/init/init.type.mjsindex ad7c7ef636..1a28900739 100644--- a/packages/cli/api/init/init.type.mjs+++ b/packages/cli/api/init/init.type.mjs@@ -17,7 +17,7 @@* @property {string | null} themeTemplatePath Relative output path when `themeTemplate === 'created'`.* @property {'workflow' | 'created' | 'skipped' | null} template Template outcome (`workflow` is the CLI default; `created`/`skipped` are programmatic).* @property {string | null} templatePath Relative output path when `template === 'created'`.- * @property {boolean} nextSteps Whether the getting-started "Next steps" were emitted (default mode).+ * @property {boolean} nextSteps Whether the getting-started "Next steps" were emitted (default mode inside a project; false outside one).*//**@@ -32,13 +32,47 @@* @property {{removed: boolean}} data False when no managed agent-docs block was found, so nothing was removed.*/+/**+ * What `init --user` did with one file of the computer-level agent text.+ * `written`: created or refreshed. `unchanged`: already this release's text.+ * `removed`: deleted (with `--remove-agents`). `absent`: nothing to remove.+ * `kept`: a file left as it is, because a person edited it or Astryx did not+ * write it (see `reason`).+ * @typedef {'written' | 'linked' | 'unchanged' | 'removed' | 'absent' | 'kept'} InitUserAction+ */++/**+ * @typedef {object} InitUserFile+ * @property {string} path Absolute path in the home folder: the skill file,+ * or a link to its folder.+ * @property {InitUserAction} action+ * @property {'edited' | 'not-astryx'} [reason] Only on `kept`: `edited`, the+ * text no longer matches the hash Astryx recorded in it; `not-astryx`, it+ * has no Astryx markers or is a symlink, or a link target holds something+ * Astryx did not create.+ */++/**+ * @typedef {object} InitUserData+ * @property {InitUserFile[]} files One row per path acted on: `~/.agents/skills/astryx/SKILL.md` first, then each link to its folder: `~/.claude/skills/astryx` always, and another agent's skills folder when that agent's folder exists (`linked`, or `unchanged` when the link is already there). Removal removes the file and the links Astryx made.+ * @property {string} command The command the text tells agents to run: `astryx`, or the host's command when a host started the run.+ * @property {string[]} warnings Non-fatal notes, such as no `astryx` on the computer that runs the Astryx CLI.+ */++/**+ * @typedef {object} InitUserResponse+ * @property {'init.user'} type+ * @property {InitUserData} data+ */+/*** Options for `init()`.* @typedef {object} InitOptions* @property {string} [features] Comma-separated features to install (agents, theme, template).* @property {boolean} [all] Install all features.- * @property {boolean} [removeAgents] Remove the managed agent-docs block instead of installing.- * @property {string} [agent] Agent preset: claude, cursor, codex, hermes, muse, all.+ * @property {boolean} [removeAgents] Remove the managed agent-docs block instead of installing; with `user`, remove the computer-level agent text.+ * @property {boolean} [user] Write the computer-level agent text (`~/.agents/skills/astryx/SKILL.md`, linked into `~/.claude/skills` and the skill folders of other installed tools, with a copy for Continue) instead of setting up the folder.+ * @property {string} [agent] Agent preset: claude, cursor, codex, hermes, muse, all. Refused with `user`.* @property {string | string[]} [agentDocsPath] Explicit agent-docs file path(s).* @property {string} [templateName] Scaffold a named page template (programmatic only; the CLI never sets it).*/diff --git a/packages/cli/api/init/run/run.mjs b/packages/cli/api/init/run/run.mjsindex 3f6568b2da..b3d1cf142a 100644--- a/packages/cli/api/init/run/run.mjs+++ b/packages/cli/api/init/run/run.mjs@@ -19,6 +19,7 @@ import * as fs from 'node:fs';import {CLI_ROOT} from '../../../foundation/fs/paths.mjs';import {PathSafetyError, assertWithin} from '../../../foundation/fs/path-safety.mjs';import {getCliInvocation} from '../../../foundation/env/package-manager.mjs';+import {isOutsideProject} from '../../../foundation/env/project-scope.mjs';import {installAgentDocs,renderAgentDocsBlock,@@ -39,7 +40,7 @@ const VALID_AGENTS = ['claude', 'cursor', 'codex', 'hermes', 'muse', 'all'];* installed built themes and imports their production and font stylesheets. The* app imports that module once and passes its default to <Theme>.*- * @param {string} invocation install-aware CLI invocation stem (e.g. `npx astryx`, `pnpm exec astryx`, or `npx @astryxdesign/cli` for one-off runs)+ * @param {string} invocation install-aware CLI invocation stem (e.g. `pnpm exec astryx`, `yarn astryx`, or `npx @astryxdesign/cli` for one-off runs)* @returns {string[]} ordered list of human-facing lines*/export function getNextSteps(invocation) {@@ -140,8 +141,11 @@ function applyTheme(cwd, invocation, data) {data.themeTemplate = 'failed';logger.error('Could not write the theme template.');}+ // Outside a project there is no app to add a theme to (spec AST-081 FR3).logger.log(- ` Edit the blank template for a new theme, or run \`${invocation} theme add <slug>\` to import an installed built theme (\`${invocation} theme list\` to browse). Extend an imported theme for ordinary customization; use \`${invocation} theme eject <slug>\` only to fork source.`,+ isOutsideProject(cwd)+ ? ` Edit the blank template for a new theme, or run \`${invocation} theme eject <slug>\` to start from the source of a built theme (\`${invocation} theme list\` to browse).`+ : ` Edit the blank template for a new theme, or run \`${invocation} theme add <slug>\` to import an installed built theme (\`${invocation} theme list\` to browse). Extend an imported theme for ordinary customization; use \`${invocation} theme eject <slug>\` only to fork source.`,);}@@ -276,7 +280,10 @@ export async function run(options = {}, {cwd = process.cwd()} = {}) {}// No flags: TTY-free default — install the AI agent cheat sheet with NO- // prompts, then print the getting-started guidance.+ // prompts, then print the getting-started guidance. Outside a project the+ // steps would set up a project the folder does not have, so they are left+ // out (spec AST-081 FR3).+ const outside = isOutsideProject(cwd);/** @type {import('../init.type.mjs').InitRunData} */const data = {mode: 'default',@@ -288,13 +295,17 @@ export async function run(options = {}, {cwd = process.cwd()} = {}) {themeTemplatePath: null,template: null,templatePath: null,- nextSteps: true,+ nextSteps: !outside,};await applyAgents(cwd, options, invocation, data);logger.log('');logger.log(` Tip: \`${invocation} init --all\` also points you to the theme and page-building workflows.`,);+ if (outside) {+ logger.log('');+ return {type: 'init.run', data};+ }for (const line of getNextSteps(invocation)) logger.log(line);return {type: 'init.run', data};}diff --git a/packages/cli/api/init/user/user.mjs b/packages/cli/api/init/user/user.mjsnew file mode 100644index 0000000000..2eb3196235--- /dev/null+++ b/packages/cli/api/init/user/user.mjs@@ -0,0 +1,87 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file init.user leaf — the `--user` path behind `astryx init`.+ *+ * `user(options)` writes, refreshes, or (with `remove`) removes the+ * computer-level agent text: one skill file in the home folder, linked into+ * the skill folders agents read (spec AST-081 FR7, FR8). It records the+ * setting and the links it made in the settings file, so the global copy,+ * which keeps the text current in the background, does the same, or, after+ * `remove`, writes nothing. The adapter does every file access. It works in any+ * folder and never touches a project's agent docs. A file without the Astryx+ * markers, one a person edited, or a symlinked one is kept as it is. When no+ * `astryx` on the computer's search path runs the Astryx CLI, the text is+ * still written and the receipt warns that the CLI should be installed for+ * the computer.+ *+ * @input `remove`; the home folder, search path, and settings of+ * the computer+ * @output an `init.user` receipt+ * @position packages/cli/api/init — dispatched by init.mjs+ */++import {+ COMPUTER_COMMAND,+ COMPUTER_INSTALL_STEP,+ applyComputerAgentText,+ displayHomePath,+} from '../_adapter.mjs';+import {logger} from '../../logger.mjs';++/**+ * @param {string} file+ * @param {string} home+ * @returns {string}+ */+const display = (file, home) => displayHomePath(file, home);++/** @type {Record<import('../init.type.mjs').InitUserAction, string>} */+const ACTION_LINES = {+ written: '[ok] Wrote',+ linked: '[ok] Linked',+ unchanged: '[ok] Already current:',+ removed: '[ok] Removed',+ absent: '[ok] Nothing to remove:',+ kept: '[skip] Kept',+};++/** @type {Record<'edited' | 'not-astryx', string>} */+const KEPT_REASONS = {+ edited: '(edited since Astryx wrote it; delete it to get the current text):',+ 'not-astryx': '(not created by Astryx):',+};++/**+ * Write or remove the computer-level agent text and return an `init.user`+ * receipt. Progress is emitted through the shared `logger` (silent by+ * default); warnings go to its warn channel.+ *+ * @param {{remove?: boolean}} [options]+ * @returns {Promise<import('../init.type.mjs').InitUserResponse>}+ */+export async function user({remove = false} = {}) {+ const {home, command, files, cliOnSearchPath} = applyComputerAgentText({+ remove,+ });+ /** @type {string[]} */+ const warnings = [];+ // A host's door is its own command; only the plain `astryx` needs a copy of+ // the CLI installed for the computer.+ if (!remove && command === COMPUTER_COMMAND && !cliOnSearchPath) {+ warnings.push(+ `No \`${COMPUTER_COMMAND}\` command on this computer runs the Astryx CLI, so agents cannot run the commands this text names. Install the CLI for the computer: ${COMPUTER_INSTALL_STEP}`,+ );+ }+ for (const file of files) {+ const reason = file.reason ? ` ${KEPT_REASONS[file.reason]}` : '';+ logger.log(+ `${ACTION_LINES[file.action]}${reason || (file.action === 'kept' ? ':' : '')} ${display(file.path, home)}`,+ );+ }+ for (const warning of warnings) logger.warn(`[warn] ${warning}`);+ return {+ type: 'init.user',+ data: {files, command, warnings},+ };+}diff --git a/packages/cli/api/init/user/user.test.mjs b/packages/cli/api/init/user/user.test.mjsnew file mode 100644index 0000000000..83d0c0a16a--- /dev/null+++ b/packages/cli/api/init/user/user.test.mjs@@ -0,0 +1,232 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `init({user})` and `astryx init --user`: the `init.user` receipt, the+ * install warning, the refused combinations, and that it touches nothing in+ * the folder it runs in. Every test uses a temporary home folder and search+ * path.+ */++import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import {init} from '../init.mjs';+import {user} from './user.mjs';+import {runWithCliDoor} from '../../../foundation/env/cli-command.mjs';+import {renderComputerAgentText} from '../../../foundation/agent-docs/computer-agent-text.mjs';+import {runCli} from '../../../test-utils/run-cli.mjs';+import {settingsFile} from '../../../foundation/env/user-settings.mjs';+import {readGlobalState} from '../../../foundation/release/global-state.mjs';+import {cliVersion} from '../../../foundation/release/run-context.mjs';++/** @type {string[]} */+const dirs = [];+/** @param {string} label */+function tmp(label) {+ const dir = fs.mkdtempSync(+ path.join(os.tmpdir(), `astryx-init-user-${label}-`),+ );+ dirs.push(dir);+ return dir;+}++let home = '';+let emptyPath = '';+beforeEach(() => {+ home = tmp('home');+ emptyPath = tmp('path');+ vi.stubEnv('HOME', home);+ vi.stubEnv('USERPROFILE', home);+ vi.stubEnv('PATH', emptyPath);+ // The settings file and the cache live under this home folder too.+ vi.stubEnv('XDG_CONFIG_HOME', path.join(home, '.config'));+ vi.stubEnv('XDG_CACHE_HOME', path.join(home, '.cache'));+ vi.stubEnv('APPDATA', path.join(home, 'AppData', 'Roaming'));+ vi.stubEnv('LOCALAPPDATA', path.join(home, 'AppData', 'Local'));+});++/** The settings file under the temporary home folder. */+const settings = () => {+ try {+ return JSON.parse(fs.readFileSync(settingsFile(), 'utf8'));+ } catch {+ return null;+ }+};+afterEach(() => {+ vi.unstubAllEnvs();+ while (dirs.length) {+ fs.rmSync(/** @type {string} */ (dirs.pop()), {+ recursive: true,+ force: true,+ });+ }+});++const FILE = path.join('.agents', 'skills', 'astryx', 'SKILL.md');+const CLAUDE = path.join('.claude', 'skills', 'astryx');++/** Put a linked Astryx CLI first on the search path. */+function installCliOnPath() {+ const prefix = tmp('prefix');+ const pkg = path.join(prefix, 'lib', 'node_modules', '@astryxdesign', 'cli');+ fs.mkdirSync(pkg, {recursive: true});+ fs.writeFileSync(+ path.join(pkg, 'package.json'),+ '{"name":"@astryxdesign/cli"}',+ );+ fs.writeFileSync(path.join(pkg, 'bin.mjs'), '#!/usr/bin/env node\n');+ fs.chmodSync(path.join(pkg, 'bin.mjs'), 0o755);+ fs.mkdirSync(path.join(prefix, 'bin'));+ fs.symlinkSync(path.join(pkg, 'bin.mjs'), path.join(prefix, 'bin', 'astryx'));+ vi.stubEnv('PATH', path.join(prefix, 'bin'));+}++describe('init({user: true})', () => {+ it('writes the file, links Claude Code to it, and returns the init.user receipt, warning when no astryx runs the CLI', async () => {+ const r = await init({user: true}, {cwd: tmp('cwd')});+ expect(r.type).toBe('init.user');+ if (r.type !== 'init.user') return;+ expect(r.data.files).toEqual([+ {path: path.join(home, FILE), action: 'written'},+ {path: path.join(home, CLAUDE), action: 'linked'},+ ]);+ expect(r.data.command).toBe('astryx');+ expect(r.data.warnings).toHaveLength(1);+ expect(r.data.warnings[0]).toContain('npm i -g @astryxdesign/cli');+ expect(fs.readFileSync(path.join(home, FILE), 'utf8')).toBe(+ renderComputerAgentText({command: 'astryx'}),+ );+ expect(fs.readFileSync(path.join(home, CLAUDE, 'SKILL.md'), 'utf8')).toBe(+ renderComputerAgentText({command: 'astryx'}),+ );+ });++ it.skipIf(process.platform === 'win32')(+ 'does not warn when the astryx on the search path is the Astryx CLI',+ async () => {+ installCliOnPath();+ const r = await user();+ expect(r.data.warnings).toEqual([]);+ },+ );++ it("names the host's door and does not ask for a global install", async () => {+ const r = await runWithCliDoor('acme astryx', () => user());+ expect(r.data.command).toBe('acme astryx');+ expect(r.data.warnings).toEqual([]);+ expect(fs.readFileSync(path.join(home, FILE), 'utf8')).toContain(+ "`acme astryx search '<what you need>'`",+ );+ });++ it('works inside a project and writes nothing in it', async () => {+ const dir = tmp('project');+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ '{"name":"app","dependencies":{"@astryxdesign/core":"*"}}',+ );+ const before = fs.readdirSync(dir).sort();+ const r = await init({user: true}, {cwd: dir});+ expect(r.type).toBe('init.user');+ expect(fs.readdirSync(dir).sort()).toEqual(before);+ });++ it('records the links it made, and the release that wrote the text', async () => {+ await init({user: true});+ expect(settings()).toEqual({+ computerAgentText: {install: true, links: [path.join(home, CLAUDE)]},+ });+ expect(readGlobalState().agentText).toEqual({writtenBy: cliVersion()});+ });++ it('keeps every other setting when it records the choice', async () => {+ fs.mkdirSync(path.dirname(settingsFile()), {recursive: true});+ fs.writeFileSync(settingsFile(), '{"other": 1}');+ await init({user: true, removeAgents: true});+ expect(settings()).toEqual({+ other: 1,+ computerAgentText: {install: false, links: []},+ });+ });++ it('with removeAgents removes the file and the links it made, and records that the text is not wanted', async () => {+ await init({user: true});+ const r = await init({user: true, removeAgents: true});+ expect(r.type).toBe('init.user');+ if (r.type !== 'init.user') return;+ expect(r.data.files).toEqual([+ {path: path.join(home, FILE), action: 'removed'},+ {path: path.join(home, CLAUDE), action: 'removed'},+ ]);+ expect(r.data.warnings).toEqual([]);+ expect(fs.existsSync(path.join(home, FILE))).toBe(false);+ expect(fs.existsSync(path.join(home, CLAUDE))).toBe(false);+ expect(settings()).toEqual({+ computerAgentText: {install: false, links: []},+ });+ });++ it.each([+ [{features: 'agents'}, '--features'],+ [{all: true}, '--all'],+ [{agentDocsPath: 'X.md'}, '--agent-docs-path'],+ [{agent: 'claude'}, '--agent'],+ [{removeAgents: true, agent: 'claude'}, '--agent'],+ ])(+ 'refuses %o with ERR_INVALID_ARGUMENT and writes nothing',+ async (extra, flag) => {+ await expect(init({user: true, ...extra})).rejects.toMatchObject({+ code: 'ERR_INVALID_ARGUMENT',+ message: expect.stringContaining(flag),+ });+ expect(fs.existsSync(path.join(home, '.agents'))).toBe(false);+ expect(fs.existsSync(path.join(home, '.claude'))).toBe(false);+ },+ );+});++describe('astryx init --user', () => {+ it('prints the file, the link, and the install warning in text mode', async () => {+ const r = await runCli(['init', '--user'], tmp('cwd'));+ expect(r.status).toBe(0);+ expect(r.stdout).toContain(`Wrote ~${path.sep}${FILE}`);+ expect(r.stdout).toContain(`Linked ~${path.sep}${CLAUDE}`);+ expect(r.stderr).toContain('npm i -g @astryxdesign/cli');+ });++ it('emits the init.user envelope under --json', async () => {+ const r = await runCli(['--json', 'init', '--user'], tmp('cwd'));+ expect(r.status).toBe(0);+ const env = JSON.parse(r.stdout);+ expect(env.type).toBe('init.user');+ expect(+ env.data.files.map((/** @type {{action: string}} */ f) => f.action),+ ).toEqual(['written', 'linked']);+ expect(env.data.command).toBe('astryx');+ });++ it('names a file a person edited as kept, and why', async () => {+ await runCli(['init', '--user'], tmp('cwd'));+ const file = path.join(home, FILE);+ fs.appendFileSync(file, 'my note\n');+ const r = await runCli(['init', '--user'], tmp('cwd'));+ expect(r.status).toBe(0);+ expect(r.stdout).toContain(+ `Kept (edited since Astryx wrote it; delete it to get the current text): ~${path.sep}${FILE}`,+ );+ expect(fs.readFileSync(file, 'utf8')).toMatch(/my note\n$/u);+ });++ it('exits 1 with ERR_INVALID_ARGUMENT when combined with --all or --agent', async () => {+ for (const extra of [['--all'], ['--agent', 'claude']]) {+ const r = await runCli(+ ['--json', 'init', '--user', ...extra],+ tmp('cwd'),+ );+ expect(r.status).toBe(1);+ expect(JSON.parse(r.stdout).code).toBe('ERR_INVALID_ARGUMENT');+ }+ });+});diff --git a/packages/cli/api/integration/authoring-checks.mjs b/packages/cli/api/integration/authoring-checks.mjsindex 2a36dcd11e..0dfcbeb0bc 100644--- a/packages/cli/api/integration/authoring-checks.mjs+++ b/packages/cli/api/integration/authoring-checks.mjs@@ -25,7 +25,7 @@ import {packageDocsProblems,packageReferenceProblems,} from '../docs/_adapter.mjs';-import {findCoreDir} from '../../foundation/fs/paths.mjs';+import {findProjectCoreDir} from '../../foundation/fs/paths.mjs';import {discoverIntegrationComponents,discoverOwnedComponents,@@ -271,7 +271,7 @@ export async function integrationComponentConflicts(pkg, options = {}) {issues.push({code: 'invalid_doc_graph', severity, message});}- const coreDir = findCoreDir(cwd);+ const coreDir = findProjectCoreDir(cwd);if (!coreDir) {issues.push({code: 'core_not_found',diff --git a/packages/cli/api/integration/integrationCheck.doc.mjs b/packages/cli/api/integration/integrationCheck.doc.mjsindex 3bd450c052..313d2e6662 100644--- a/packages/cli/api/integration/integrationCheck.doc.mjs+++ b/packages/cli/api/integration/integrationCheck.doc.mjs@@ -42,7 +42,7 @@ export const doc = {type: 'boolean',default: 'false',description:- 'Also fail on any warning and on any check that did not run, not only on errors.',+ 'Also fail on any warning and on any check that did not run, not only on errors. A malformed `cliCommand` is reported as a note (`invalid_cli_command`) in `data.notes` of the validate check, which fails nothing until a minor release names it.',},],returns: [diff --git a/packages/cli/api/integration/pack-check.mjs b/packages/cli/api/integration/pack-check.mjsindex d3d2bde375..11277935ee 100644--- a/packages/cli/api/integration/pack-check.mjs+++ b/packages/cli/api/integration/pack-check.mjs@@ -69,6 +69,7 @@ import {collectIdentities,compareIdentities,} from '../../foundation/integrations/contribution-inventory.mjs';+import {formatCliCommand} from '../../foundation/env/package-manager.mjs';/*** @typedef {import('../../foundation/integrations/issue').AstryxIntegrationIssue} Issue@@ -623,7 +624,7 @@ async function validateIncompleteThemeExports(output.kind === 'module'? 'theme_module_stale': 'theme_stylesheet_stale',- `Theme "${localTheme.slug}" ${output.kind} does not match ${sourceRelative}. This incomplete export remains packable, but run \`astryx theme build ${sourceRelative}\` before adding its matching export.`,+ `Theme "${localTheme.slug}" ${output.kind} does not match ${sourceRelative}. This incomplete export remains packable, but run \`${formatCliCommand(`theme build ${sourceRelative}`, packageDir)}\` before adding its matching export.`,),);}@@ -642,7 +643,7 @@ async function validateIncompleteThemeExports(issues.push(error('theme_build_failed',- `Theme "${localTheme.slug}" could not be rebuilt from ${sourceRelative}: ${err instanceof Error ? err.message : String(err)} Run \`astryx theme build ${sourceRelative}\` before packing.`,+ `Theme "${localTheme.slug}" could not be rebuilt from ${sourceRelative}: ${err instanceof Error ? err.message : String(err)} Run \`${formatCliCommand(`theme build ${sourceRelative}`, packageDir)}\` before packing.`,),);} finally {@@ -961,7 +962,7 @@ async function validatePackedThemeExports(issues.push(warning('theme_exports_missing',- `Theme "${localTheme.slug}" has no declared built exports. The package remains source-compatible. To make it importable, run \`astryx theme build ${sourceRelative}\` and export "./themes/${localTheme.slug}" plus "./themes/${localTheme.slug}.css" from package.json; \`astryx integration add theme ${localTheme.slug}\` creates those exports for a new theme.`,+ `Theme "${localTheme.slug}" has no declared built exports. The package remains source-compatible. To make it importable, run \`${formatCliCommand(`theme build ${sourceRelative}`, localIntegration.__packageDir)}\` and export "./themes/${localTheme.slug}" plus "./themes/${localTheme.slug}.css" from package.json; \`${formatCliCommand(`integration add theme ${localTheme.slug}`, localIntegration.__packageDir)}\` creates those exports for a new theme.`,),);continue;@@ -1001,7 +1002,7 @@ async function validatePackedThemeExports(err instanceof ThemeImportError? 'theme_import_unresolvable': 'theme_import_invalid',- `${message} Run \`astryx theme build ${sourceRelative}\` before packing.`,+ `${message} Run \`${formatCliCommand(`theme build ${sourceRelative}`, localIntegration.__packageDir)}\` before packing.`,),);continue;@@ -1022,7 +1023,7 @@ async function validatePackedThemeExports(issues.push(error('theme_build_failed',- `Theme "${localTheme.slug}" did not produce a complete build. Run \`astryx theme build ${sourceRelative}\` before packing.`,+ `Theme "${localTheme.slug}" did not produce a complete build. Run \`${formatCliCommand(`theme build ${sourceRelative}`, localIntegration.__packageDir)}\` before packing.`,),);continue;@@ -1093,10 +1094,10 @@ async function validatePackedThemeExports(error(output.staleCode,localWrapper && !localWrapper.ok && !localWrapper.rebuild- ? `Theme "${localTheme.slug}" module is not the module \`astryx theme build ${sourceRelative}\` writes and does not only wrap it: ${localWrapper.reason}. A module that wraps the built module may only import the theme's own stylesheet and font stylesheet for their side effects and re-export from the built module either everything or only its theme, as ${localTheme.exportName}.`+ ? `Theme "${localTheme.slug}" module is not the module \`${formatCliCommand(`theme build ${sourceRelative}`, localIntegration.__packageDir)}\` writes and does not only wrap it: ${localWrapper.reason}. A module that wraps the built module may only import the theme's own stylesheet and font stylesheet for their side effects and re-export from the built module either everything or only its theme, as ${localTheme.exportName}.`: localWrapper && !localWrapper.ok- ? `Theme "${localTheme.slug}" module re-exports ${localWrapper.reason}, which does not match ${sourceRelative}. Run \`astryx theme build ${sourceRelative}\` before packing.`- : `Theme "${localTheme.slug}" ${output.kind} does not match ${sourceRelative}. Run \`astryx theme build ${sourceRelative}\` before packing.`,+ ? `Theme "${localTheme.slug}" module re-exports ${localWrapper.reason}, which does not match ${sourceRelative}. Run \`${formatCliCommand(`theme build ${sourceRelative}`, localIntegration.__packageDir)}\` before packing.`+ : `Theme "${localTheme.slug}" ${output.kind} does not match ${sourceRelative}. Run \`${formatCliCommand(`theme build ${sourceRelative}`, localIntegration.__packageDir)}\` before packing.`,),);}@@ -1128,7 +1129,7 @@ async function validatePackedThemeExports(issues.push(error('theme_build_failed',- `Theme "${localTheme.slug}" could not be rebuilt from ${sourceRelative}: ${err instanceof Error ? err.message : String(err)} Run \`astryx theme build ${sourceRelative}\` before packing.`,+ `Theme "${localTheme.slug}" could not be rebuilt from ${sourceRelative}: ${err instanceof Error ? err.message : String(err)} Run \`${formatCliCommand(`theme build ${sourceRelative}`, localIntegration.__packageDir)}\` before packing.`,),);} finally {diff --git a/packages/cli/api/integration/pack-check.test.mjs b/packages/cli/api/integration/pack-check.test.mjsindex a6bc5c0cbe..a6f157fc9f 100644--- a/packages/cli/api/integration/pack-check.test.mjs+++ b/packages/cli/api/integration/pack-check.test.mjs@@ -17,6 +17,7 @@ import {integrationAddComponent,integrationAddTemplate,} from './add-contribution.mjs';+import {formatCliCommand} from '../../foundation/env/package-manager.mjs';let tmpDir;@@ -502,7 +503,7 @@ describe('a theme module that loads its own styles', () => {{code: 'theme_module_stale',severity: 'error',- message: `Theme "ocean" module is not the module \`astryx theme build themes/ocean/oceanTheme.ts\` writes and does not only wrap it: ${reason}. A module that wraps the built module may only import the theme's own stylesheet and font stylesheet for their side effects and re-export from the built module either everything or only its theme, as oceanTheme.`,+ message: `Theme "ocean" module is not the module \`${formatCliCommand('theme build themes/ocean/oceanTheme.ts', tmpDir)}\` writes and does not only wrap it: ${reason}. A module that wraps the built module may only import the theme's own stylesheet and font stylesheet for their side effects and re-export from the built module either everything or only its theme, as oceanTheme.`,},]);});@@ -522,8 +523,7 @@ describe('a theme module that loads its own styles', () => {{code: 'theme_module_stale',severity: 'error',- message:- 'Theme "ocean" module re-exports ../themes/ocean/ocean.js, which does not match themes/ocean/oceanTheme.ts. Run `astryx theme build themes/ocean/oceanTheme.ts` before packing.',+ message: `Theme "ocean" module re-exports ../themes/ocean/ocean.js, which does not match themes/ocean/oceanTheme.ts. Run \`${formatCliCommand('theme build themes/ocean/oceanTheme.ts', tmpDir)}\` before packing.`,},]);});@@ -539,8 +539,7 @@ describe('a theme module that loads its own styles', () => {{code: 'theme_module_stale',severity: 'error',- message:- 'Theme "ocean" module does not match themes/ocean/oceanTheme.ts. Run `astryx theme build themes/ocean/oceanTheme.ts` before packing.',+ message: `Theme "ocean" module does not match themes/ocean/oceanTheme.ts. Run \`${formatCliCommand('theme build themes/ocean/oceanTheme.ts', tmpDir)}\` before packing.`,},]);});@@ -687,8 +686,7 @@ describe('integrationPackCheck', () => {{code: 'theme_exports_missing',severity: 'warning',- message:- 'Theme "ocean" has no declared built exports. The package remains source-compatible. To make it importable, run `astryx theme build themes/ocean/oceanTheme.ts` and export "./themes/ocean" plus "./themes/ocean.css" from package.json; `astryx integration add theme ocean` creates those exports for a new theme.',+ message: `Theme "ocean" has no declared built exports. The package remains source-compatible. To make it importable, run \`${formatCliCommand('theme build themes/ocean/oceanTheme.ts', tmpDir)}\` and export "./themes/ocean" plus "./themes/ocean.css" from package.json; \`${formatCliCommand('integration add theme ocean', tmpDir)}\` creates those exports for a new theme.`,},]);const cli = runCliVerify();@@ -859,8 +857,7 @@ describe('integrationPackCheck', () => {{code: 'theme_stylesheet_stale',severity: 'warning',- message:- 'Theme "ocean" stylesheet does not match themes/ocean/oceanTheme.ts. This incomplete export remains packable, but run `astryx theme build themes/ocean/oceanTheme.ts` before adding its matching export.',+ message: `Theme "ocean" stylesheet does not match themes/ocean/oceanTheme.ts. This incomplete export remains packable, but run \`${formatCliCommand('theme build themes/ocean/oceanTheme.ts', tmpDir)}\` before adding its matching export.`,},]);const cli = runCliVerify();@@ -893,8 +890,7 @@ describe('integrationPackCheck', () => {{code: 'theme_stylesheet_stale',severity: 'warning',- message:- 'Theme "ocean" stylesheet does not match themes/ocean/oceanTheme.ts. This incomplete export remains packable, but run `astryx theme build themes/ocean/oceanTheme.ts` before adding its matching export.',+ message: `Theme "ocean" stylesheet does not match themes/ocean/oceanTheme.ts. This incomplete export remains packable, but run \`${formatCliCommand('theme build themes/ocean/oceanTheme.ts', tmpDir)}\` before adding its matching export.`,},]);const cli = runCliVerify();@@ -967,14 +963,12 @@ describe('integrationPackCheck', () => {{code: 'theme_module_stale',severity: 'error',- message:- 'Theme "ocean" module does not match themes/ocean/oceanTheme.ts. Run `astryx theme build themes/ocean/oceanTheme.ts` before packing.',+ message: `Theme "ocean" module does not match themes/ocean/oceanTheme.ts. Run \`${formatCliCommand('theme build themes/ocean/oceanTheme.ts', tmpDir)}\` before packing.`,},{code: 'theme_stylesheet_stale',severity: 'error',- message:- 'Theme "ocean" stylesheet does not match themes/ocean/oceanTheme.ts. Run `astryx theme build themes/ocean/oceanTheme.ts` before packing.',+ message: `Theme "ocean" stylesheet does not match themes/ocean/oceanTheme.ts. Run \`${formatCliCommand('theme build themes/ocean/oceanTheme.ts', tmpDir)}\` before packing.`,},]);const cli = runCliVerify();diff --git a/packages/cli/api/integration/validate-integration.mjs b/packages/cli/api/integration/validate-integration.mjsindex c340b0d8d8..b72f807ead 100644--- a/packages/cli/api/integration/validate-integration.mjs+++ b/packages/cli/api/integration/validate-integration.mjs@@ -56,11 +56,13 @@ import {// The on-disk contribution validators live in foundation: Project and// integration-warnings need them too, and foundation must not depend on api.import {+ INVALID_CLI_COMMAND,validateLoadedIntegration,issueError as error,issueWarning as warning,rootProblem,} from '../../foundation/integrations/validate-contributions.mjs';+import {formatCliCommand} from '../../foundation/env/package-manager.mjs';export {validateLoadedIntegration};@@ -76,6 +78,8 @@ export {validateLoadedIntegration};* @property {string} [manifestFile] Absolute path to the loaded manifest.* @property {'no_package_json'} [reason] Why nothing was validated (internal).* @property {Issue[]} issues+ * @property {Array<{code: string, message: string}>} [notes] Information that+ * fails nothing, such as `invalid_cli_command` (a malformed `cliCommand`).* @property {import('../../foundation/integrations/integrations.mjs').LoadedIntegration} [integration]*/@@ -125,7 +129,7 @@ function unreadThemeFolderIssues(packageDir, loaded) {let fix;if (THEME_SLUG_RE.test(name)) {const stem = `${name.replace(/-([a-z0-9])/gu, (_, character) => character.toUpperCase())}Theme`;- fix = `if it is a theme, add ${stem}.ts and ${stem}.doc.mjs to it (\`astryx integration add theme ${name}\` writes both) and move its code into ${stem}.ts; if not, ${hide}.`;+ fix = `if it is a theme, add ${stem}.ts and ${stem}.doc.mjs to it (\`${formatCliCommand(`integration add theme ${name}`, packageDir)}\` writes both) and move its code into ${stem}.ts; if not, ${hide}.`;} else {fix = `${hide}; a theme folder needs a lower-kebab name.`;}@@ -284,11 +288,14 @@ async function validateAtPackageDir(let unknownKeys;/** @type {string | undefined} */let agentDocsError;+ /** @type {string | undefined} */+ let cliCommandError;try {- ({manifest, unknownKeys, agentDocsError} = await loadManifest(- manifestFile,- `Integration manifest (${path.basename(manifestFile)})`,- ));+ ({manifest, unknownKeys, agentDocsError, cliCommandError} =+ await loadManifest(+ manifestFile,+ `Integration manifest (${path.basename(manifestFile)})`,+ ));} catch (err) {issues.push(error('invalid_manifest', /** @type {any} */ (err).message));return result;@@ -320,6 +327,8 @@ async function validateAtPackageDir(themes: resolveRoot(manifest.themes),issuesUrl: manifest.issuesUrl,agentDocs: manifest.agentDocs,+ cliCommand: manifest.cliCommand,+ __cliCommandError: cliCommandError,__agentDocsError: agentDocsError,__unknownKeys: unknownKeys,__spec: identity.name,@@ -330,7 +339,17 @@ async function validateAtPackageDir(// Roots + contribution checks are shared with validateLoadedIntegration so// the everyday-command nudge runs the exact same validators.- issues.push(...(await validateLoadedIntegration(loaded)));+ // A malformed `cliCommand` is an info note beside the issues, not an issue:+ // `integration check --strict` fails on any warning, and a new failure code+ // joins only in a minor release (architecture:cli-surface INV35). Doctor's+ // project check still warns about it.+ for (const issue of await validateLoadedIntegration(loaded)) {+ if (issue.code === INVALID_CLI_COMMAND) {+ (result.notes ??= []).push({code: issue.code, message: issue.message});+ } else {+ issues.push(issue);+ }+ }if (loaded.themes && !rootProblem(loaded.themes))issues.push(...unreadThemeFolderIssues(packageDir, loaded));// What the docs say that no reader serves: a prop listed twice, an@@ -485,6 +504,7 @@ export async function validateIntegration(pkg, options = {}) {const docTypes = integration? await integrationDocTypes(integration, cwd): undefined;+ const notes = result.found ? (result.notes ?? []) : [];return {type: 'integration.validate',data: {@@ -504,6 +524,7 @@ export async function validateIntegration(pkg, options = {}) {},]: result.issues,+ ...(notes.length > 0 ? {notes} : {}),...(docTypes ? {docTypes} : {}),},};diff --git a/packages/cli/api/integration/validate-integration.type.mjs b/packages/cli/api/integration/validate-integration.type.mjsindex 29346e935b..aa99b2cd76 100644--- a/packages/cli/api/integration/validate-integration.type.mjs+++ b/packages/cli/api/integration/validate-integration.type.mjs@@ -38,7 +38,9 @@* "healthy" — the two are otherwise byte-identical.* @typedef {object} ValidateIntegrationResponse* @property {'integration.validate'} type- * @property {{validated: boolean, name: string | null, version: string | null, issues: import('../../foundation/integrations/issue').AstryxIntegrationIssue[], docTypes?: DocTypesReport}} data+ * @property {{validated: boolean, name: string | null, version: string | null, issues: import('../../foundation/integrations/issue').AstryxIntegrationIssue[], notes?: Array<{code: string, message: string}>, docTypes?: DocTypesReport}} data+ * `notes`: information beside the issues that fails nothing, such as+ * `invalid_cli_command`, a `cliCommand` that was ignored as malformed*//**diff --git a/packages/cli/api/integration/validate-unread-theme-folders.test.mjs b/packages/cli/api/integration/validate-unread-theme-folders.test.mjsindex 4f549defb5..3322a44b9d 100644--- a/packages/cli/api/integration/validate-unread-theme-folders.test.mjs+++ b/packages/cli/api/integration/validate-unread-theme-folders.test.mjs@@ -15,6 +15,7 @@ import * as fs from 'node:fs';import * as path from 'node:path';import {validateLocalIntegration} from './validate-integration.mjs';import {integrationAddTheme} from './add-theme.mjs';+import {formatCliCommand} from '../../foundation/env/package-manager.mjs';let tmpDir;@@ -76,8 +77,8 @@ describe('unread theme folders', () => {]);expect(issues.map(issue => issue.message)).toEqual(['Folder "themes/Tide_Pool/" holds modules but no <name>Theme source or .doc.mjs descriptor, so Astryx does not read it as a theme. Fix: rename it to .Tide_Pool so Astryx skips it; a theme folder needs a lower-kebab name.',- 'Folder "themes/reef/" holds modules but no <name>Theme source or .doc.mjs descriptor, so Astryx does not read it as a theme. Fix: if it is a theme, add reefTheme.ts and reefTheme.doc.mjs to it (`astryx integration add theme reef` writes both) and move its code into reefTheme.ts; if not, rename it to .reef so Astryx skips it.',- 'Folder "themes/sand/" holds modules but no <name>Theme source or .doc.mjs descriptor, so Astryx does not read it as a theme. Fix: if it is a theme, add sandTheme.ts and sandTheme.doc.mjs to it (`astryx integration add theme sand` writes both) and move its code into sandTheme.ts; if not, rename it to .sand so Astryx skips it.',+ `Folder "themes/reef/" holds modules but no <name>Theme source or .doc.mjs descriptor, so Astryx does not read it as a theme. Fix: if it is a theme, add reefTheme.ts and reefTheme.doc.mjs to it (\`${formatCliCommand('integration add theme reef', tmpDir)}\` writes both) and move its code into reefTheme.ts; if not, rename it to .reef so Astryx skips it.`,+ `Folder "themes/sand/" holds modules but no <name>Theme source or .doc.mjs descriptor, so Astryx does not read it as a theme. Fix: if it is a theme, add sandTheme.ts and sandTheme.doc.mjs to it (\`${formatCliCommand('integration add theme sand', tmpDir)}\` writes both) and move its code into sandTheme.ts; if not, rename it to .sand so Astryx skips it.`,]);});diff --git a/packages/cli/api/integration/validateIntegration.doc.mjs b/packages/cli/api/integration/validateIntegration.doc.mjsindex 928e18f894..3d61249e7a 100644--- a/packages/cli/api/integration/validateIntegration.doc.mjs+++ b/packages/cli/api/integration/validateIntegration.doc.mjs@@ -62,7 +62,7 @@ export const doc = {{type: 'integration.validate',description:- 'The result envelope: `data.validated`, false when nothing was validated — with no `package.json` at all, `data.issues` carries one `no_package` error-severity issue so the command exits 1; with a `package.json` but no integration manifest, `data.issues` is empty, which means "not looked at", not "healthy"; `data.name` and `data.version` of the validated package (both null when `data.validated` is false; `data.name` is `(local package)` when the local package.json has no readable name), plus `data.issues`, an AstryxIntegrationIssue[] of {code, severity: `warning` | `error`, message, fix?, file?, line?}: `fix` is the change that resolves the issue, and `file` and `line` where it is, relative to the package, when the check knows them. When the manifest loads, `data.docTypes` holds the doc type check: `status` (`checked` | `skipped`), `reason` when skipped, `typescript`, `docs` (doc values checked), `findings` ({doc, line, export, type, field, problem: `unknown_field` | `missing_field` | `wrong_type`, severity: `warning`, message, fix}), `unchecked` ({doc, reason}: a doc that could not be fully checked, or a root its reader cannot read), and `fixtures` when the components or docs root holds test fixture docs under `__tests__`: how many, none of them checked.',+ 'The result envelope: `data.validated`, false when nothing was validated — with no `package.json` at all, `data.issues` carries one `no_package` error-severity issue so the command exits 1; with a `package.json` but no integration manifest, `data.issues` is empty, which means "not looked at", not "healthy"; `data.name` and `data.version` of the validated package (both null when `data.validated` is false; `data.name` is `(local package)` when the local package.json has no readable name), plus `data.issues`, an AstryxIntegrationIssue[] of {code, severity: `warning` | `error`, message, fix?, file?, line?}: `fix` is the change that resolves the issue, and `file` and `line` where it is, relative to the package, when the check knows them; and `data.notes` when there are any: {code, message} information that fails nothing, such as `invalid_cli_command` for a `cliCommand` that was ignored as malformed. When the manifest loads, `data.docTypes` holds the doc type check: `status` (`checked` | `skipped`), `reason` when skipped, `typescript`, `docs` (doc values checked), `findings` ({doc, line, export, type, field, problem: `unknown_field` | `missing_field` | `wrong_type`, severity: `warning`, message, fix}), `unchecked` ({doc, reason}: a doc that could not be fully checked, or a root its reader cannot read), and `fixtures` when the components or docs root holds test fixture docs under `__tests__`: how many, none of them checked.',},],examples: [diff --git a/packages/cli/api/search/_adapter.mjs b/packages/cli/api/search/_adapter.mjsnew file mode 100644index 0000000000..597fe701d2--- /dev/null+++ b/packages/cli/api/search/_adapter.mjs@@ -0,0 +1,25 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Environment adapter for search: locating the Core a search reads,+ * including the network install and npm subprocess that fetch a release's+ * own Core outside a project (spec AST-081 FR3; architecture:cli-surface+ * INV21).+ *+ * @input the folder a search runs in+ * @output the Core folder a search reads+ * @position packages/cli/api/search — imported by search.mjs only+ */++import {requireCoreDir} from '../../foundation/fs/paths.mjs';++/**+ * The Core a typed search reads: the project's, else the release's own,+ * installed into the per-user cache first when needed. Throws as+ * requireCoreDir does.+ * @param {string} cwd+ * @returns {string}+ */+export function requireSearchCoreDir(cwd) {+ return requireCoreDir(cwd);+}diff --git a/packages/cli/api/search/search.doc.mjs b/packages/cli/api/search/search.doc.mjsindex 04b57d6df3..3273660f7c 100644--- a/packages/cli/api/search/search.doc.mjs+++ b/packages/cli/api/search/search.doc.mjs@@ -21,7 +21,8 @@ export const doc = {'incidental prose mentions, so an exact match always sorts first. A component\'s ' +'usage guidance (its best practices) is indexed one tier below its description, ' +'so the words a reader types still find it — but a component that IS the answer ' +- 'always outranks one whose advice merely mentions the term.',+ 'always outranks one whose advice merely mentions the term.' ++ " In global mode: with `cwd` outside a project, items from integrations installed next to this CLI package globally are searched too, and theme results name no step that adds a theme to an app; inside a project, only the project's own integrations count. See {@link namespace:global} and {@link generic:computer-integrations}.",importPath: '@astryxdesign/cli/api',signature:'search(query: string, options?: SearchOptions): Promise<SearchResponse>',@@ -48,14 +49,14 @@ export const doc = {name: 'options.cwd',type: 'string',description:- "Directory to resolve @astryxdesign/core from. A docs-only or themes-only search (`type: 'doc'` or `type: 'theme'`) does not need it, and a search with no `type` covers the docs and themes alone when core is missing.",+ "Directory to resolve @astryxdesign/core from: the project's installed Core, else, outside a project or in a project with nothing installed, the Core of the release that answers, installed into the per-user cache first when needed. A docs-only or themes-only search (`type: 'doc'` or `type: 'theme'`) does not need it. A search with no `type` covers the docs and themes alone only when that Core cannot be obtained, and then says so in `meta.partial`.",},],returns: [{type: 'search',description:- 'The query echoed back, `matchCount` (how many candidates matched in total, before `limit`), plus a ranked SearchResultEntry[] bounded by `limit`: each has domain, name, score, reason, description, and follow-up command, plus `import` for components and hooks, `title` for docs, `displayName` and `kind` for templates, and `displayName` for themes. A doc result is the smallest part that answers: one section (with `section`, and a command that reads only it), one docs-tree route, or a topic, whose command lists its sections. `parent` is the command that opens the level above it: the section list of its topic, the namespace a tree node sits in, the Unorganized level for a flat topic, or the topic list for a top-level namespace. Every doc result also carries `package`, the npm package that authored it (for a section, the package its file came from). A theme result is one theme you can import: `name` is its slug, its command is `astryx theme add <slug>`, and `package` is the npm package that ships it (`@astryxdesign/cli` for the CLI\'s own themes).',+ 'The query echoed back, `matchCount` (how many candidates matched in total, before `limit`), plus a ranked SearchResultEntry[] bounded by `limit`: each has domain, name, score, reason, description, and follow-up command, plus `import` for components and hooks, `title` for docs, `displayName` and `kind` for templates, and `displayName` for themes. A doc result is the smallest part that answers: one section (with `section`, and a command that reads only it), one docs-tree route, or a topic, whose command lists its sections. `parent` is the command that opens the level above it: the section list of its topic, the namespace a tree node sits in, the Unorganized level for a flat topic, or the topic list for a top-level namespace. Every doc result also carries `package`, the npm package that authored it (for a section, the package its file came from). A theme result is one theme you can import: `name` is its slug, its command is `astryx theme add <slug>` (outside a project, where there is no app to add it to, `astryx theme eject <slug>`), and `package` is the npm package that ships it (`@astryxdesign/cli` for the CLI\'s own themes). When a search with no `type` could not obtain @astryxdesign/core, `meta.partial` is `{skipped, reason}`: the domains it skipped (`component`, `hook`, `template`) and why; the results are the docs and themes, and text mode prints one line on standard error.',},],throws: [@@ -67,6 +68,10 @@ export const doc = {code: 'ERR_CORE_NOT_FOUND',when: '@astryxdesign/core cannot be found from the cwd, and `type` names a domain that reads it: `component`, `hook`, or `template`',},+ {+ code: 'ERR_VERSIONS_UNAVAILABLE',+ when: "`type` names a domain that reads @astryxdesign/core, and outside a project, or in a project with nothing installed, the Core of the release that answers cannot be installed into the per-user cache; a search with no `type` answers with `meta.partial` instead",+ },],examples: [{label: 'Find a component', code: "const r = await search('button');"},diff --git a/packages/cli/api/search/search.mjs b/packages/cli/api/search/search.mjsindex b77ccc362f..54409ac97a 100644--- a/packages/cli/api/search/search.mjs+++ b/packages/cli/api/search/search.mjs@@ -82,10 +82,9 @@import {withListingCache} from '../../foundation/fs/listing-cache.mjs';import {readDocView} from '../../foundation/doc-compiler/read.mjs';-import {- discoverExternalPackages,- findCoreDir,-} from '../../foundation/fs/paths.mjs';+import {discoverExternalPackages} from '../../foundation/fs/paths.mjs';+import {requireSearchCoreDir} from './_adapter.mjs';+import {isOutsideProject} from '../../foundation/env/project-scope.mjs';import {discoverComponents,discoverValidIntegrationComponents,@@ -126,7 +125,7 @@ import {sectionKey,sectionSummary,} from '../../foundation/discovery/docs-section-key.mjs';-import {AstryxError} from '../error.mjs';+import {AstryxError, coreDirOrThrow} from '../error.mjs';import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';import {setResultCoverage} from './coverage.mjs';import {linkSearchResponse} from '../component/_adapter.mjs';@@ -2128,8 +2127,11 @@ async function gatherThemes(cwd) {* @param {string} reason* @param {number} matchedTerms - Query concepts this result answered.* @param {number} queryTerms - Query concepts there were to answer.+ * @param {boolean} [outside] - The search runs outside a project, where a+ * theme cannot be added to an app, so its command forks the source instead+ * (spec AST-081 FR3).*/-function toResult(c, score, reason, matchedTerms, queryTerms) {+function toResult(c, score, reason, matchedTerms, queryTerms, outside = false) {const base = {domain: c.domain,name: c._resultName ?? c.name,@@ -2178,7 +2180,9 @@ function toResult(c, score, reason, matchedTerms, queryTerms) {result = {...base,displayName: c._displayName,- command: `astryx theme add ${c.name}`,+ command: outside+ ? `astryx theme eject ${c.name}`+ : `astryx theme add ${c.name}`,};break;default:@@ -2245,13 +2249,23 @@ async function searchOnce(query, options) {// name, it is an error without core; an open search then covers the docs// and themes alone.const needsCore = !type || !CORELESS_DOMAINS.includes(type);- const coreDir = needsCore ? findCoreDir(cwd) : null;- if (type && needsCore && !coreDir) {- throw new AstryxError(- 'Could not find @astryxdesign/core package',- undefined,- ERROR_CODES.ERR_CORE_NOT_FOUND,- );+ // A domain that reads Core gets it as `component` does: the project's, else+ // the answering release's own, installed into the per-user cache on first+ // need (spec AST-081 FR3). Asked for by name, a Core that cannot be had is+ // the error; an open search answers from the rest and says what it skipped+ // and why, never silently.+ /** @type {string | null} */+ let coreDir = null;+ /** @type {string | null} */+ let coreSkipped = null;+ if (needsCore && type) {+ coreDir = coreDirOrThrow(requireSearchCoreDir, cwd);+ } else if (needsCore) {+ try {+ coreDir = requireSearchCoreDir(cwd);+ } catch (error) {+ coreSkipped = /** @type {Error} */ (error).message;+ }}// Gather candidates from each requested domain in parallel.@@ -2362,6 +2376,7 @@ async function searchOnce(query, options) {// strongest PAGE, not outrank every component./** @type {{result: any, priority: 0 | 1 | 2, key: number, alias: 'partial' | 'keyword' | false, aliasWords: number, candidate: Candidate, span: [number, number] | null, word: [number, number] | null}[]} */const ranked = [];+ const outside = themes.length > 0 && isOutsideProject(cwd);for (const candidate of all) {const hit = scoreQuery(term, tokens, candidate, words);if (hit)@@ -2372,6 +2387,7 @@ async function searchOnce(query, options) {hit.reason,hit.matched,hit.total,+ outside,),priority: domainPriority(term, tokens, candidate, hit, words),key: hit.score,@@ -2480,6 +2496,14 @@ async function searchOnce(query, options) {),},};+ if (coreSkipped) {+ response.meta = {+ partial: {+ skipped: ['component', 'hook', 'template'],+ reason: coreSkipped,+ },+ };+ }if (wants('component')) {searchedComponentsOf.set(response,diff --git a/packages/cli/api/search/search.test.mjs b/packages/cli/api/search/search.test.mjsindex f82110627b..fe63cbc0b1 100644--- a/packages/cli/api/search/search.test.mjs+++ b/packages/cli/api/search/search.test.mjs@@ -36,6 +36,7 @@ import {tokenizeQuery,SEARCH_DOMAINS,} from './search.mjs';+import {linkThisCliAsProjectCli} from '../../test-utils/release-fixtures.mjs';const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../..');const cwd = REPO;@@ -470,8 +471,10 @@ describe('search leaf — error paths (pinned)', () => {it('searches the docs without @astryxdesign/core, and throws for a domain that needs it', async () => {const empty = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-search-no-core-'));+ // A project whose own CLI answers, with no Core installed.+ linkThisCliAsProjectCli(empty);try {- // An open search outside an app covers the docs, as `astryx docs` does.+ // An open search without Core covers the docs, as `astryx docs` does.const open = await search('make an integration', {cwd: empty});expect(open.data.results.length).toBeGreaterThan(0);expect(new Set(open.data.results.map(r => r.domain))).toEqual(diff --git a/packages/cli/api/search/search.type.mjs b/packages/cli/api/search/search.type.mjsindex 481723e13d..60d25d057c 100644--- a/packages/cli/api/search/search.type.mjs+++ b/packages/cli/api/search/search.type.mjs@@ -20,7 +20,7 @@* @property {number} score - Relevance score (higher is better).* @property {string} reason - Human-readable reason the candidate matched (e.g. `keyword "button"`).* @property {string} description - One-line description, when available.- * @property {string} command - Follow-up command to act on this result (e.g. `astryx component Button`, or `astryx theme add neutral` for a theme).+ * @property {string} command - Follow-up command to act on this result (e.g. `astryx component Button`, or `astryx theme add neutral` for a theme; `astryx theme eject neutral` outside a project).* @property {string} [import] - Import path — present for component and hook results.* @property {string} [title] - Doc title — present for doc results.* @property {string} [section] - Section key — present when a doc result is one section of a topic; `command` reads only that section.@@ -38,6 +38,11 @@* @property {string} data.query* @property {number} data.matchCount - How many candidates matched the query in total, before `limit` was applied. `results` is the bounded slice of that set, so `matchCount > results.length` means the answer was capped.* @property {SearchResultEntry[]} data.results+ * @property {{partial?: {skipped: SearchDomain[], reason: string}}} [meta] -+ * `partial`, when an open search could not get the Core that components,+ * hooks, and templates are read from (such as outside a project, offline,+ * before the release's Core was downloaded): the domains it skipped and why.+ * The results are the docs and themes.*//**diff --git a/packages/cli/api/swizzle/_adapter.mjs b/packages/cli/api/swizzle/_adapter.mjsindex 7e96b779d5..082d0ac0e4 100644--- a/packages/cli/api/swizzle/_adapter.mjs+++ b/packages/cli/api/swizzle/_adapter.mjs@@ -11,7 +11,7 @@* (ERR_CORE_NOT_FOUND) when core can't be located.*/-import {findCoreDir, listComponents} from '../../foundation/fs/paths.mjs';+import {findProjectCoreDir, listComponents} from '../../foundation/fs/paths.mjs';import {resolveComponentReplacements} from '../../foundation/discovery/component-replacement.mjs';import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';import {AstryxError} from '../error.mjs';@@ -44,7 +44,7 @@ export async function resolveComponentReplacement(* @returns {{coreDir: string, components: string[]}}*/export function resolveCore(cwd) {- const coreDir = findCoreDir(cwd);+ const coreDir = findProjectCoreDir(cwd);if (!coreDir) {throw new AstryxError('Could not find @astryxdesign/core package. Make sure you are inside the design system monorepo or have @astryxdesign/core installed.',diff --git a/packages/cli/api/swizzle/copy/copy.mjs b/packages/cli/api/swizzle/copy/copy.mjsindex 3e7adda44a..a77bec1ba5 100644--- a/packages/cli/api/swizzle/copy/copy.mjs+++ b/packages/cli/api/swizzle/copy/copy.mjs@@ -115,7 +115,7 @@ function buildFeedback(component, issuesUrl) {*/async function loadConfigSafely(cwd) {try {- const project = await Project.load(cwd);+ const project = await Project.load(cwd, {core: 'project'});return {loadedIntegrations: project.loadedIntegrations,issuesUrl: project.config.issuesUrl,diff --git a/packages/cli/api/template/template-integration.test.mjs b/packages/cli/api/template/template-integration.test.mjsindex 99f1ec4daa..b3ee43d6dd 100644--- a/packages/cli/api/template/template-integration.test.mjs+++ b/packages/cli/api/template/template-integration.test.mjs@@ -736,7 +736,7 @@ describe('integration template discovery', () => {const command = await runCli(['template', 'shell-side-nav'], tmpDir);expect(command.status).toBe(0);expect(command.stderr).toContain('@acme/extra has 1 integration issue');- expect(command.stderr).toContain('astryx doctor');+ expect(command.stderr).toMatch(/Run: .+ doctor/);const doctor = await runCli(['doctor'], tmpDir);expect(doctor.status).toBe(0);diff --git a/packages/cli/api/theme/_adapter.mjs b/packages/cli/api/theme/_adapter.mjsindex ef79b8d2b1..ac47ad5bce 100644--- a/packages/cli/api/theme/_adapter.mjs+++ b/packages/cli/api/theme/_adapter.mjs@@ -11,6 +11,10 @@import * as fs from 'node:fs';import * as path from 'node:path';+import {+ findCarriedCoreDir,+ requireCoreDir,+} from '../../foundation/fs/paths.mjs';import {Project} from '../../foundation/config/project.mjs';import {BUNDLED_THEME_PACKAGE,@@ -41,6 +45,7 @@ import {stripCopyrightHeader} from '../../foundation/text/copyright-header.mjs';import {loadIntegrations} from '../../foundation/integrations/integrations.mjs';import {importThemeArtifact} from '../../foundation/fs/module-loader.mjs';import {applyWrites} from '../integration/add-helpers.mjs';+import {formatCliCommand} from '../../foundation/env/package-manager.mjs';export {BUNDLED_THEME_PACKAGE, THEMES_DIR};@@ -565,7 +570,7 @@ export function resolveRecordedThemes(state, available) {);if (!theme) {throw new AstryxError(- `Added theme "${slug}" from ${owner} is unavailable. Reinstall the package or restore the local theme, then run \`astryx theme add ${slug} --package ${owner}\`.`,+ `Added theme "${slug}" from ${owner} is unavailable. Reinstall the package or restore the local theme, then run \`${formatCliCommand(`theme add ${slug} --package ${owner}`, state.projectDir)}\`.`,undefined,ERROR_CODES.ERR_UNKNOWN_THEME,);@@ -732,14 +737,14 @@ export async function removeThemeFromApp(slug, options = {}) {const recordedSlug = recordedThemeSlug(state, slug);if (!state.configured || recordedSlug == null) {throw new AstryxError(- `Theme "${slug}" is not added. Run \`astryx theme add ${slug}\` first.`,+ `Theme "${slug}" is not added. Run \`${formatCliCommand(`theme add ${slug}`, state.projectDir)}\` first.`,undefined,ERROR_CODES.ERR_UNKNOWN_THEME,);}if (state.defaultSlug === recordedSlug) {throw new AstryxError(- `Theme "${recordedSlug}" is the default. Run \`astryx theme use <other-slug>\` before removing it.`,+ `Theme "${recordedSlug}" is the default. Run \`${formatCliCommand('theme use <other-slug>', state.projectDir)}\` before removing it.`,undefined,ERROR_CODES.ERR_THEME_INVALID,);@@ -748,7 +753,7 @@ export async function removeThemeFromApp(slug, options = {}) {delete themes[recordedSlug];if (state.defaultSlug == null) {throw new AstryxError(- 'The generated theme module has no default theme. Run `astryx theme use <slug>` first.',+ `The generated theme module has no default theme. Run \`${formatCliCommand('theme use <slug>', state.projectDir)}\` first.`,undefined,ERROR_CODES.ERR_THEME_INVALID,);@@ -776,7 +781,7 @@ export async function useThemeInApp(slug, options = {}) {const recordedSlug = recordedThemeSlug(state, slug);if (!state.configured || recordedSlug == null) {throw new AstryxError(- `Theme "${slug}" is not added. Run \`astryx theme add ${slug}\` first.`,+ `Theme "${slug}" is not added. Run \`${formatCliCommand(`theme add ${slug}`, state.projectDir)}\` first.`,undefined,ERROR_CODES.ERR_UNKNOWN_THEME,);@@ -792,3 +797,25 @@ export async function useThemeInApp(slug, options = {}) {available,);}++/**+ * The Core theme targets are read from: the project's, else the release's+ * own, installed into the per-user cache first when needed (a network install+ * and an npm subprocess; spec AST-081 FR3). Throws as requireCoreDir does.+ * @param {string} cwd+ * @returns {string}+ */+export function requireThemeCoreDir(cwd) {+ return requireCoreDir(cwd);+}++/**+ * The Core a theme build reads outside a project: the one the answering copy+ * carries, installed into the per-user cache first when needed (a network+ * install and an npm subprocess; spec AST-081 FR3); null when there is none.+ * @param {string} cwd+ * @returns {string | null}+ */+export function fetchCarriedThemeCoreDir(cwd) {+ return findCarriedCoreDir(cwd, {fetch: true});+}diff --git a/packages/cli/api/theme/build/build.mjs b/packages/cli/api/theme/build/build.mjsindex f573bccdf0..25692f197c 100644--- a/packages/cli/api/theme/build/build.mjs+++ b/packages/cli/api/theme/build/build.mjs@@ -70,7 +70,11 @@ import {CLI_ROOT,findCoreDir,findInstalledPackage,+ findProjectCoreDir,} from '../../../foundation/fs/paths.mjs';+import {isGlobalCopy} from '../../../foundation/release/choose.mjs';+import {isInReleaseCache} from '../../../foundation/release/cache.mjs';+import {fetchCarriedThemeCoreDir} from '../_adapter.mjs';import {assertWithin,sanitizeName,@@ -306,10 +310,15 @@ function realLocation(target) {** @param {string} cwd* @param {CoreBindings} cliCore - The CLI's own Core, from {@link loadCliCore}.+ * @param {{projectOnly?: boolean}} [options] `projectOnly`: never the+ * carried Core, as for doctor (spec AST-081 FR3)* @returns {Promise<CoreBindings | null>}*/-async function loadProjectCore(cwd, cliCore) {- const dir = findInstalledPackage(cwd, '@astryxdesign/core');+async function loadProjectCore(cwd, cliCore, {projectOnly = false} = {}) {+ // Outside a project, the Core the answering copy carries (spec AST-081 FR3).+ const dir =+ findInstalledPackage(cwd, '@astryxdesign/core') ??+ (projectOnly ? null : fetchCarriedThemeCoreDir(cwd));const themeFile = dir ? importTarget(dir, './theme') : null;if (!dir || !themeFile) return null;if (cliCore.themeModule) {@@ -355,14 +364,54 @@ const _projectCores = new Map();/*** Choose the Core this build generates with: the project's installed one when- * {@link loadProjectCore} finds it, else the CLI's own.+ * {@link loadProjectCore} finds it, else the CLI's own. With `projectOnly`,+ * only the project's installed Core: a build that cannot use it fails rather+ * than read the Core the answering copy carries (spec AST-081 FR3).* @param {string} cwd+ * @param {{projectOnly?: boolean}} [options]*/-async function selectCore(cwd) {+async function selectCore(cwd, {projectOnly = false} = {}) {const cliCore = await loadCliCore();- if (!_projectCores.has(cwd))- _projectCores.set(cwd, await loadProjectCore(cwd, cliCore));- setCore(_projectCores.get(cwd) ?? cliCore);+ const key = `${projectOnly ? 'project' : 'any'}\0${cwd}`;+ if (!_projectCores.has(key))+ _projectCores.set(key, await loadProjectCore(cwd, cliCore, {projectOnly}));+ const projectCore = _projectCores.get(key);+ // A global or cached copy's own Core is the carried one.+ if (projectOnly && !projectCore && carriesCore() && !cliCoreIsProjects(cwd)) {+ throw new AstryxError(+ "The project's Core isn't installed or does not load.",+ undefined,+ ERROR_CODES.ERR_CORE_NOT_FOUND,+ );+ }+ setCore(projectCore ?? cliCore);+}++/**+ * Whether this CLI copy is one installed for the computer or kept in the+ * per-user release cache, whose own Core import is the carried Core.+ * @returns {boolean}+ */+function carriesCore() {+ return isGlobalCopy(CLI_ROOT) || isInReleaseCache(CLI_ROOT);+}++/**+ * Whether the Core the CLI's own import loads is the one the project at+ * `cwd` installed.+ * @param {string} cwd+ * @returns {boolean}+ */+function cliCoreIsProjects(cwd) {+ const dir = findProjectCoreDir(cwd);+ if (!dir) return false;+ try {+ const own = fileURLToPath(import.meta.resolve('@astryxdesign/core/theme'));+ const theirs = importTarget(dir, './theme');+ return theirs != null && realOrSelf(own) === realOrSelf(theirs);+ } catch {+ return false;+ }}/**@@ -401,8 +450,7 @@ function inAstryxRepository(cwd) {* @returns {string}*/export function coreUnavailableMessage(cwd, importError) {- const why =- '`astryx theme build` generates CSS with @astryxdesign/core, the same code the runtime <Theme> uses';+ const why = `\`${formatCliCommand('theme build')}\` generates CSS with @astryxdesign/core, the same code the runtime <Theme> uses`;const detail = importError ? `\n Import error: ${importError.message}` : '';if (inAstryxRepository(cwd)) {return (@@ -2497,13 +2545,14 @@ function validateHeadingTypeAugmentationSupport(themeDef) {* output must stay inside, for a CLI-internal scratch build. `iconsSpecifier` overrides the icon registry import* specifier in the generated module (e.g. `./icons.mjs`); when omitted, the* direct registry specifiers from the theme source are emitted unchanged.- * @param {{cwd?: string}} [ctx]+ * @param {{cwd?: string, projectCore?: boolean}} [ctx] `projectCore`: only the+ * project's installed Core (spec AST-081 FR3)* @returns {Promise<any>}*/async function themeBuildInternal(file,options = {},- {cwd = process.cwd()} = {},+ {cwd = process.cwd(), projectCore = false} = {},/** @type {{compact?: boolean, trailers?: ThemeBuildTrailer[]}} */ report = {},) {const filePath = path.resolve(cwd, file);@@ -2522,7 +2571,14 @@ async function themeBuildInternal(// A compact report has no per-theme heading, so each warning names its file.const source = report.compact ? `${path.relative(cwd, filePath)}: ` : '';- await selectCore(cwd);+ if (projectCore && !findProjectCoreDir(cwd)) {+ throw new AstryxError(+ "The project's Core isn't installed.",+ undefined,+ ERROR_CODES.ERR_CORE_NOT_FOUND,+ );+ }+ await selectCore(cwd, {projectOnly: projectCore});// Standalone builds only need interception when an older Core could erase// adaptations. Family preparation always supplies the same recorder as its@@ -3272,7 +3328,7 @@ export function printCompactTrailer(trailers, {hint = false} = {}) {).join(', ');logger.log(- `[note] Fonts named but not loaded: ${named}. Load them in your app (recipe: astryx docs typography).`,+ `[note] Fonts named but not loaded: ${named}. Load them in your app (recipe: ${formatCliCommand('docs typography')}).`,);}if (hint) {@@ -3327,7 +3383,7 @@ export async function themeBuildForReport(return {receipt, trailer: trailers[0] ?? null};}-/** @param {string} file @param {{out?: string, check?: boolean, iconsSpecifier?: string}} [options] @param {{cwd?: string}} [ctx] @returns {Promise<import('../theme.type.mjs').ThemeBuildResponse | import('../theme.type.mjs').ThemeBuildCheckResponse | null>} */+/** @param {string} file @param {{out?: string, check?: boolean, iconsSpecifier?: string}} [options] @param {{cwd?: string, projectCore?: boolean}} [ctx] `projectCore`: read only the project's installed Core, never the carried one (doctor; spec AST-081 FR3) @returns {Promise<import('../theme.type.mjs').ThemeBuildResponse | import('../theme.type.mjs').ThemeBuildCheckResponse | null>} */export async function themeBuild(file, options = {}, ctx = {}) {return /** @type {any} */ (themeBuildInternal(file, options, ctx));}diff --git a/packages/cli/api/theme/build/build.packed-old-core.test.mjs b/packages/cli/api/theme/build/build.packed-old-core.test.mjsindex c2b52d3fcc..1a6af44f80 100644--- a/packages/cli/api/theme/build/build.packed-old-core.test.mjs+++ b/packages/cli/api/theme/build/build.packed-old-core.test.mjs@@ -37,6 +37,7 @@ import * as path from 'node:path';import {fileURLToPath} from 'node:url';import {findInstalledPackage} from '../../../foundation/fs/paths.mjs';+import {CLI_VERSION} from '../../../test-utils/release-fixtures.mjs';const HERE = path.dirname(fileURLToPath(import.meta.url));const REPO_ROOT = path.resolve(HERE, '../../../../..');@@ -55,8 +56,12 @@ const RUNTIME_DEPS = ['zod',];-const OLD_CORE_VERSION = '0.5.4';-const CURRENT_CORE_VERSION = '0.6.0';+// Both Cores carry the packed CLI's own version: a run through the bin in a+// project whose Core is another release is handed to that release (spec+// AST-081 FR2), so the old surface is told apart by what it exports, not by+// its version.+const OLD_CORE_VERSION = CLI_VERSION;+const CURRENT_CORE_VERSION = CLI_VERSION;const TSC_BIN = path.join(REPO_ROOT, 'node_modules/typescript/bin/tsc');/**@@ -278,8 +283,20 @@ function buildTheme(themeFile, extraArgs = []) {'node_modules/@astryxdesign/cli/clients/cli/bin/astryx.mjs',);try {+ // A packed CLI outside any project's package.json reads as installed for+ // the computer, so it gets a home folder of its own: nothing it keeps for+ // the computer lands in the real one.+ const home = path.join(root, 'home');+ const env = {+ ...process.env,+ HOME: home,+ USERPROFILE: home,+ XDG_CONFIG_HOME: path.join(home, '.config'),+ XDG_CACHE_HOME: path.join(home, '.cache'),+ NO_UPDATE_NOTIFIER: '1',+ };// prettier-ignore- const stdout = execFileSync(process.execPath, [bin, 'theme', 'build', ...(Array.isArray(themeFile) ? themeFile : [themeFile]), ...extraArgs, '--json'], {cwd: consumer, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe']});+ const stdout = execFileSync(process.execPath, [bin, 'theme', 'build', ...(Array.isArray(themeFile) ? themeFile : [themeFile]), ...extraArgs, '--json'], {cwd: consumer, encoding: 'utf8', env, stdio: ['ignore', 'pipe', 'pipe']});return {status: 0, envelope: JSON.parse(stdout)};} catch (error) {const e = /** @type {any} */ (error);diff --git a/packages/cli/api/theme/build/font-warning.mjs b/packages/cli/api/theme/build/font-warning.mjsindex e8af33a7ad..f72f6dc9d9 100644--- a/packages/cli/api/theme/build/font-warning.mjs+++ b/packages/cli/api/theme/build/font-warning.mjs@@ -21,9 +21,11 @@* @output Ordered, case-insensitively deduped family names, and the human* help snippet (<link> pair + @font-face) printed after the install* instructions.- * @position Sits beside build.mjs (api/theme/build/). Pure functions, no IO,- * so the `--json` receipt and the human output share one source of truth.+ * @position Sits beside build.mjs (api/theme/build/). Pure functions, no IO+ * beyond the CLI invocation the human help names (formatCliCommand), so the+ * `--json` receipt and the human output share one source of truth.*/+import {formatCliCommand} from '../../../foundation/env/package-manager.mjs';// font-family values that never need loading: CSS generic families, the ui-*// system keywords, and CSS-wide keywords that can appear in a token value.@@ -254,6 +256,6 @@ function fontLoadingRecipe(families) {font-display: swap;}- Recipe and fallback-stack guidance: astryx docs typography+ Recipe and fallback-stack guidance: ${formatCliCommand('docs typography')}`;}diff --git a/packages/cli/api/theme/build/font-warning.test.mjs b/packages/cli/api/theme/build/font-warning.test.mjsindex ef72ea5644..64eb1bfc62 100644--- a/packages/cli/api/theme/build/font-warning.test.mjs+++ b/packages/cli/api/theme/build/font-warning.test.mjs@@ -15,6 +15,7 @@import {describe, it, expect} from 'vitest';import {collectUnloadedFonts, formatFontLoadingHelp} from './font-warning.mjs';+import {formatCliCommand} from '../../../foundation/env/package-manager.mjs';describe('collectUnloadedFonts', () => {it('returns webfont families from font-family tokens, skipping known fallbacks', () => {@@ -255,7 +256,7 @@ describe('formatFontLoadingHelp', () => {});it('points at the docs recipe', () => {- expect(help).toContain('astryx docs typography');+ expect(help).toContain(formatCliCommand('docs typography'));});it('percent-encodes family names in the css2 URL', () => {diff --git a/packages/cli/api/theme/remove/remove.test.mjs b/packages/cli/api/theme/remove/remove.test.mjsindex ac348dba47..976ac1621a 100644--- a/packages/cli/api/theme/remove/remove.test.mjs+++ b/packages/cli/api/theme/remove/remove.test.mjs@@ -81,14 +81,14 @@ describe('themeRemove', () => {it('refuses to remove the default and names theme use', async () => {await expect(themeRemove('ocean', {cwd: tmpDir})).rejects.toMatchObject({code: 'ERR_THEME_INVALID',- message: expect.stringContaining('astryx theme use'),+ message: expect.stringContaining(' theme use <other-slug>`'),});});it('names theme add when the slug is not added', async () => {await expect(themeRemove('missing', {cwd: tmpDir})).rejects.toMatchObject({code: 'ERR_UNKNOWN_THEME',- message: expect.stringContaining('astryx theme add missing'),+ message: expect.stringContaining(' theme add missing`'),});});});diff --git a/packages/cli/api/theme/targets/targets.mjs b/packages/cli/api/theme/targets/targets.mjsindex 51bb1aaaec..89884fa1f1 100644--- a/packages/cli/api/theme/targets/targets.mjs+++ b/packages/cli/api/theme/targets/targets.mjs@@ -12,10 +12,10 @@*/import * as path from 'node:path';-import {findCoreDir} from '../../../foundation/fs/paths.mjs';+import {requireThemeCoreDir} from '../_adapter.mjs';import {collectThemingTargets} from '../../../foundation/discovery/theming-targets.mjs';import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';-import {AstryxError} from '../../error.mjs';+import {AstryxError, coreDirOrThrow} from '../../error.mjs';/*** Whether a target matches the caller's filter loosely: any target whose key,@@ -46,14 +46,7 @@ function matchesLoosely(target, filter) {* @returns {Promise<import('../theme.type.mjs').ThemeTargetsResponse>}*/export async function themeTargets(filter, {cwd = process.cwd()} = {}) {- const coreDir = findCoreDir(cwd);- if (!coreDir) {- throw new AstryxError(- 'Could not find @astryxdesign/core package',- undefined,- ERROR_CODES.ERR_CORE_NOT_FOUND,- );- }+ const coreDir = coreDirOrThrow(requireThemeCoreDir, cwd);const all = await collectThemingTargets(path.join(coreDir, 'src'));const needle = filter ? String(filter).toLowerCase() : null;diff --git a/packages/cli/api/theme/themeTargets.doc.mjs b/packages/cli/api/theme/themeTargets.doc.mjsindex f1e5767b46..820f8267ab 100644--- a/packages/cli/api/theme/themeTargets.doc.mjs+++ b/packages/cli/api/theme/themeTargets.doc.mjs@@ -62,6 +62,10 @@ export const doc = {code: 'ERR_CORE_NOT_FOUND',when: '@astryxdesign/core cannot be resolved from cwd',},+ {+ code: 'ERR_VERSIONS_UNAVAILABLE',+ when: 'outside a project, or in a project with nothing installed, the Core of the release that answers is not beside it or cached, and cannot be installed into the per-user cache (offline, a registry without it, or an unwritable cache)',+ },{code: 'ERR_UNKNOWN_COMPONENT', when: 'a filter matches no target'},],examples: [diff --git a/packages/cli/api/theme/use/use.test.mjs b/packages/cli/api/theme/use/use.test.mjsindex c27af6fa7b..e34acd3925 100644--- a/packages/cli/api/theme/use/use.test.mjs+++ b/packages/cli/api/theme/use/use.test.mjs@@ -92,7 +92,7 @@ describe('themeUse', () => {it('names theme add when the slug is not added', async () => {await expect(themeUse('missing', {cwd: tmpDir})).rejects.toMatchObject({code: 'ERR_UNKNOWN_THEME',- message: expect.stringContaining('astryx theme add missing'),+ message: expect.stringContaining(' theme add missing`'),});});});diff --git a/packages/cli/api/upgrade/_adapter.mjs b/packages/cli/api/upgrade/_adapter.mjsindex 974eb3be0e..5a535acdd3 100644--- a/packages/cli/api/upgrade/_adapter.mjs+++ b/packages/cli/api/upgrade/_adapter.mjs@@ -478,7 +478,7 @@ export async function loadProjectContext(cwd, extraIntegrationSpecs = []) {// The CLI debug preflight may already have imported this config before core// CONFIG codemods run. Upgrade needs the bytes now on disk, not that module// cache entry; ordinary Project discovery remains cached by default.- const project = await Project.load(cwd, {fresh: true});+ const project = await Project.load(cwd, {fresh: true, core: 'project'});const postCodemodHooks = project.config.hooks?.postCodemod ?? [];const configuredSpecs = new Set(project.integrations ?? []);// Configured packages come from Project, which has already resolved providerdiff --git a/packages/cli/api/upgrade/run/run.mjs b/packages/cli/api/upgrade/run/run.mjsindex d1115559bd..1fac4e94e7 100644--- a/packages/cli/api/upgrade/run/run.mjs+++ b/packages/cli/api/upgrade/run/run.mjs@@ -52,6 +52,7 @@ import {} from '../status/status.mjs';import {semverGte} from '../../../foundation/env/semver.mjs';import {getCliInvocation} from '../../../foundation/env/package-manager.mjs';+import {isOutsideProject} from '../../../foundation/env/project-scope.mjs';import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';import {AstryxError} from '../../error.mjs';import {logger} from '../../logger.mjs';@@ -153,7 +154,10 @@ export async function run(options = {}, {cwd = process.cwd()} = {}) {const currentVersion = /** @type {string} */ (options.from);const installed = detectInstalledTargetVersion(cwd);if (!installed) {- const msg = `Could not find installed @astryxdesign/core (or legacy @xds/core). Install the target version first, then rerun \`${getCliInvocation()} upgrade --from <old-version>\`.`;+ // Outside a project there is no version to install (spec AST-081 FR3).+ const msg = isOutsideProject(cwd)+ ? 'Could not find installed @astryxdesign/core (or legacy @xds/core). This folder is outside a project; upgrade migrates the code of an app project that installs @astryxdesign/core.'+ : `Could not find installed @astryxdesign/core (or legacy @xds/core). Install the target version first, then rerun \`${getCliInvocation()} upgrade --from <old-version>\`.`;logger.error(msg);logger.log('Aborted\n');throw new AstryxError(msg, undefined, ERROR_CODES.ERR_VERSION_DETECT);diff --git a/packages/cli/api/upgrade/upgrade.doc.mjs b/packages/cli/api/upgrade/upgrade.doc.mjsindex 6a41994e6f..a073f26f35 100644--- a/packages/cli/api/upgrade/upgrade.doc.mjs+++ b/packages/cli/api/upgrade/upgrade.doc.mjs@@ -24,7 +24,8 @@ export const doc = {'and conflicts are left untouched. `list` only lists codemods; `registry` only updates ' +'copied compositions. Core codemods ship inside the CLI, so a CLI older than the installed ' +'Core has none for the releases after its own version: the result then carries ' +- '`cliBehindCore` with the command that runs the same upgrade on the matching CLI.',+ '`cliBehindCore` with the command that runs the same upgrade on the matching CLI.' ++ " In global mode: in a project, the CLI runs `upgrade` with the project's own CLI, whichever astryx command started it (in a project with no CLI of its own, the one you started); this function runs the codemods of the package it is imported from. With `cwd` outside a project, `list` lists this release's codemods, `registry` finds no copied compositions, and a migration writes nothing and fails with `ERR_VERSION_DETECT`. See {@link namespace:global} and {@link generic:who-answers}.",importPath: '@astryxdesign/cli/api',signature:'upgrade(options?: UpgradeOptions, ctx?: {cwd?: string}): Promise<UpgradeListResponse | UpgradeRegistryResponse | UpgradeStatusResponse | UpgradeRunResponse>',diff --git a/packages/cli/api/upgrade/upgrade.mjs b/packages/cli/api/upgrade/upgrade.mjsindex cc59fd6a8a..b95f428172 100644--- a/packages/cli/api/upgrade/upgrade.mjs+++ b/packages/cli/api/upgrade/upgrade.mjs@@ -26,6 +26,7 @@ import {registryUpgrade} from './registry/registry.mjs';import {run} from './run/run.mjs';import {isValidSemver} from '../../foundation/env/semver.mjs';import {getCliInvocation} from '../../foundation/env/package-manager.mjs';+import {isOutsideProject} from '../../foundation/env/project-scope.mjs';import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';import {AstryxError} from '../error.mjs';import {logger} from '../logger.mjs';@@ -91,7 +92,10 @@ export async function upgrade(options = {}, {cwd = process.cwd()} = {}) {}if (!options.list && !options.from) {- const msg = `Missing required --from. Install the target version first, then run \`${getCliInvocation()} upgrade --from <old-version>\`.`;+ // Outside a project there is no version to install (spec AST-081 FR3).+ const msg = isOutsideProject(cwd)+ ? 'Missing required --from. This folder is outside a project; upgrade migrates the code of an app project that installs @astryxdesign/core.'+ : `Missing required --from. Install the target version first, then run \`${getCliInvocation()} upgrade --from <old-version>\`.`;logger.error(msg);logger.log('Aborted\n');throw new AstryxError(msg, undefined, ERROR_CODES.ERR_INVALID_ARGUMENT);diff --git a/packages/cli/assets/docs/getting-started.doc.mjs b/packages/cli/assets/docs/getting-started.doc.mjsindex 3c8a11bce1..7b6e3b26a4 100644--- a/packages/cli/assets/docs/getting-started.doc.mjs+++ b/packages/cli/assets/docs/getting-started.doc.mjs@@ -21,7 +21,7 @@ export const docs = {type: 'code',lang: 'text',label: 'Set up the design system',- code: 'Install @astryxdesign/core, @stylexjs/stylex, @astryxdesign/theme-neutral, and @astryxdesign/cli in this project, then run `npx @astryxdesign/cli init` to set up agent docs. Read the generated files to learn the conventions.',+ code: 'Install @astryxdesign/core, @stylexjs/stylex, @astryxdesign/theme-neutral, and @astryxdesign/cli in this project, then run `astryx init` to set up agent docs. Read the generated files to learn the conventions.',},{type: 'prose',@@ -31,7 +31,7 @@ export const docs = {type: 'code',lang: 'text',label: 'Give it a look',- code: 'Ask me what look and feel this app should have. Run `npx @astryxdesign/cli theme list`, install the closest theme package, and run `theme add <slug>`; use `--package` when owners share a slug. Import `themes` and `defaultThemeSlug` from the generated module once and pass `themes[defaultThemeSlug]` to `<Theme>`. Customize with `defineTheme({extends: importedTheme, ...})`. Use `theme eject` only when I ask for an independent source fork. Default to neutral if I have no preference, and show me the result before moving on.',+ code: 'Ask me what look and feel this app should have. Run `astryx theme list`, install the closest theme package, and run `theme add <slug>`; use `--package` when owners share a slug. Import `themes` and `defaultThemeSlug` from the generated module once and pass `themes[defaultThemeSlug]` to `<Theme>`. Customize with `defineTheme({extends: importedTheme, ...})`. Use `theme eject` only when I ask for an independent source fork. Default to neutral if I have no preference, and show me the result before moving on.',},],},@@ -60,7 +60,27 @@ export const docs = {type: 'code',lang: 'bash',label: 'Terminal',- code: `npx astryx init`,+ code: `astryx init`,+ },+ ],+ },+ {+ id: 'install-once',+ title: 'Install once, use everywhere',+ content: [+ {+ type: 'prose',+ text: "Install the CLI once for your computer too, and the astryx command works in any folder, for you and for any coding agent, even before a project exists. Inside a project, the project's own version still answers, so a global install never changes what your team and CI get. Keep it in the project as well; that is the recommended setup.",+ },+ {+ type: 'code',+ lang: 'bash',+ label: 'Terminal',+ code: `npm i -g @astryxdesign/cli`,+ },+ {+ type: 'prose',+ text: 'Project, global, or both: {@link generic:project-global-or-both}. Everything else about global mode: {@link namespace:global}.',},],},diff --git a/packages/cli/assets/docs/tree/add-a-component.doc.mjs b/packages/cli/assets/docs/tree/add-a-component.doc.mjsindex 936d4a483b..ecd95e73aa 100644--- a/packages/cli/assets/docs/tree/add-a-component.doc.mjs+++ b/packages/cli/assets/docs/tree/add-a-component.doc.mjs@@ -45,7 +45,7 @@ export const docs = {{type: 'code',lang: 'bash',- code: 'npx astryx integration add component AcmeCarousel',+ code: 'astryx integration add component AcmeCarousel',},{type: 'code',@@ -81,5 +81,15 @@ Declare component root ./components in astryx.integration.mjs.},],},+ {+ id: 'global-mode',+ title: 'In global mode',+ content: [+ {+ type: 'prose',+ text: "In global mode: when users install your package for their computer, beside the global CLI, your components show up in folders outside any project; inside a project, only if the project installs your package. See {@link namespace:global} and {@link generic:global-integrations}.",+ },+ ],+ },],};diff --git a/packages/cli/assets/docs/tree/add-a-theme.doc.mjs b/packages/cli/assets/docs/tree/add-a-theme.doc.mjsindex dbbeefe66c..2a363824df 100644--- a/packages/cli/assets/docs/tree/add-a-theme.doc.mjs+++ b/packages/cli/assets/docs/tree/add-a-theme.doc.mjs@@ -26,7 +26,7 @@ export const docs = {{type: 'code',lang: 'bash',- code: 'npx astryx integration add theme ocean',+ code: 'astryx integration add theme ocean',},{type: 'code',@@ -63,7 +63,7 @@ Declare theme root ./themes in astryx.integration.mjs.{type: 'code',lang: 'bash',- code: 'npx astryx integration add theme ocean --from neutral',+ code: 'astryx integration add theme ocean --from neutral',},{type: 'prose',@@ -85,5 +85,15 @@ Declare theme root ./themes in astryx.integration.mjs.},],},+ {+ id: 'global-mode',+ title: 'In global mode',+ content: [+ {+ type: 'prose',+ text: 'In global mode: when users install your package for their computer, beside the global CLI, your themes are listed in folders outside any project, where `theme add` lists but writes nothing; inside a project, only if the project installs your package. See {@link namespace:global} and {@link generic:global-integrations}.',+ },+ ],+ },],};diff --git a/packages/cli/assets/docs/tree/add-a-topic.doc.mjs b/packages/cli/assets/docs/tree/add-a-topic.doc.mjsindex b2ff1d6372..20851d5d47 100644--- a/packages/cli/assets/docs/tree/add-a-topic.doc.mjs+++ b/packages/cli/assets/docs/tree/add-a-topic.doc.mjs@@ -27,7 +27,7 @@ export const docs = {{type: 'code',lang: 'bash',- code: 'npx astryx integration add doc deploying\n# Read it the way an app will\nnpx astryx docs deploying',+ code: 'astryx integration add doc deploying\n# Read it the way an app will\nastryx docs deploying',},{type: 'code',@@ -73,6 +73,38 @@ export const docs = {},],},+ {+ id: 'write-commands-without-a-runner',+ title: 'Write commands without a runner',+ content: [+ {+ type: 'prose',+ text: 'Start every CLI command in a doc with the word astryx alone, with no runner such as npx or pnpm exec in front. The CLI prefixes each one when it prints the doc, with the command the reader runs: `pnpm exec astryx` or `yarn astryx` from their package manager, or the `cliCommand` an integration sets. See {@link generic:cli-command}.',+ },+ {+ type: 'code',+ lang: 'javascript',+ label: 'docs/deploying.doc.mjs',+ code: "{type: 'prose', text: 'Check the app with `astryx doctor` before you ship.'},\n{type: 'code', lang: 'bash', code: 'astryx doctor'},",+ },+ {+ type: 'code',+ lang: 'text',+ label:+ "Read in an app whose integration sets cliCommand: 'acme astryx'",+ code: 'Check the app with `acme astryx doctor` before you ship.\n\n```bash\nacme astryx doctor\n```',+ },+ {+ type: 'list',+ style: 'unordered',+ items: [+ 'The CLI prefixes an inline code span that starts with the word astryx, a command at the start of a line, or after `&&`, `||`, `;` or `|`, in a `bash`, `sh`, `shell`, `zsh`, `console`, `text` or `markdown` code block or one with no language, and a table cell that holds only a command.',+ 'Code in other languages, such as a `js` example, and the word astryx in plain prose stay as written.',+ '`--json` returns the doc as written, so a reader that shows it prefixes the commands itself.',+ ],+ },+ ],+ },{id: 'pick-the-doc-kind',title: 'Pick the doc kind',@@ -143,5 +175,15 @@ export const docs = {},],},+ {+ id: 'global-mode',+ title: 'In global mode',+ content: [+ {+ type: 'prose',+ text: 'In global mode: when users install your package for their computer, beside the global CLI, your doc topics show up in folders outside any project; inside a project, only if the project installs your package. See {@link namespace:global} and {@link generic:global-integrations}.',+ },+ ],+ },],};diff --git a/packages/cli/assets/docs/tree/agent-guidance.doc.mjs b/packages/cli/assets/docs/tree/agent-guidance.doc.mjsindex 32cc603a36..fdf4b25331 100644--- a/packages/cli/assets/docs/tree/agent-guidance.doc.mjs+++ b/packages/cli/assets/docs/tree/agent-guidance.doc.mjs@@ -27,7 +27,7 @@ export const docs = {{type: 'code',lang: 'bash',- code: "npx astryx integration add agent-doc 'Use AcmeCarousel for rotating content.'",+ code: "astryx integration add agent-doc 'Use AcmeCarousel for rotating content.'",},{type: 'prose',@@ -80,6 +80,10 @@ export default {type: 'prose',text: 'A line is one line of plain text. Line breaks, control characters, spaces at either end, and managed-block markers such as `<!-- ASTRYX:START -->` are rejected.',},+ {+ type: 'prose',+ text: 'Start a command in a line with the word astryx alone, with no runner in front, as in: Run astryx doctor before finishing. The block names the command the app runs once, at its top, for every command below it, so your line works in every app. See {@link generic:cli-command}.',+ },],},{@@ -93,7 +97,7 @@ export default {{type: 'code',lang: 'bash',- code: 'npx astryx init --features agents',+ code: 'astryx init --features agents',},{type: 'code',@@ -119,9 +123,9 @@ export default {{type: 'code',lang: 'bash',- code: `npx astryx init --features agents+ code: `astryx init --features agents# Or: --from takes the Core version the app had before-npx astryx upgrade --from <version> --apply`,+astryx upgrade --from <version> --apply`,},{type: 'code',@@ -134,5 +138,15 @@ npx astryx upgrade --from <version> --apply`,},],},+ {+ id: 'global-mode',+ title: 'In global mode',+ content: [+ {+ type: 'prose',+ text: "In global mode: the agent guide the CLI keeps for the computer carries no integration's guidance, because it serves every folder; your guidance reaches agents through the agent docs `init` writes in an app that installs your package. See {@link namespace:global} and {@link generic:computer-agent-guide}.",+ },+ ],+ },],};diff --git a/packages/cli/assets/docs/tree/building-blocks.doc.mjs b/packages/cli/assets/docs/tree/building-blocks.doc.mjsindex 5a788561bd..1d6b6cd452 100644--- a/packages/cli/assets/docs/tree/building-blocks.doc.mjs+++ b/packages/cli/assets/docs/tree/building-blocks.doc.mjs@@ -23,6 +23,10 @@ export const docs = {},},blocks: [+ {+ type: 'prose',+ text: 'In global mode: every kind your package adds also applies outside projects when users install it for their computer, beside the global CLI; inside a project, only if the project installs it. See {@link namespace:global} and {@link generic:global-integrations}.',+ },{type: 'prose',text: 'These are everything you can add to an integration. Mix them however you like. You are not limited to any one thing.',diff --git a/packages/cli/assets/docs/tree/check-the-props.doc.mjs b/packages/cli/assets/docs/tree/check-the-props.doc.mjsindex 5ac047d1c2..fb2d63f656 100644--- a/packages/cli/assets/docs/tree/check-the-props.doc.mjs+++ b/packages/cli/assets/docs/tree/check-the-props.doc.mjs@@ -37,7 +37,7 @@ export const docs = {{type: 'code',lang: 'bash',- code: 'npx astryx doctor integration components',+ code: 'astryx doctor integration components',},{type: 'code',diff --git a/packages/cli/assets/docs/tree/check-your-docs.doc.mjs b/packages/cli/assets/docs/tree/check-your-docs.doc.mjsindex 90a95b80eb..bf8dfa84f5 100644--- a/packages/cli/assets/docs/tree/check-your-docs.doc.mjs+++ b/packages/cli/assets/docs/tree/check-your-docs.doc.mjs@@ -27,7 +27,7 @@ export const docs = {{type: 'code',lang: 'bash',- code: 'npx astryx doctor integration docs\n# In an app, check an installed package\nnpx astryx doctor integration docs @acme/astryx-widgets',+ code: 'astryx doctor integration docs\n# In an app, check an installed package\nastryx doctor integration docs @acme/astryx-widgets',},{type: 'code',@@ -109,7 +109,7 @@ export const docs = {{type: 'code',lang: 'bash',- code: 'npx astryx doctor integration validate',+ code: 'astryx doctor integration validate',},{type: 'code',@@ -144,12 +144,12 @@ fix: Remove \`summary\`: SingleComponentDoc has no field \`summary\`.`,content: [{type: 'prose',- text: '`npx astryx doctor` also measures every read and warns on one over 32 KB. Run it in your package or in an app that installs it; `doctor integration docs` does not check size.',+ text: '`astryx doctor` also measures every read and warns on one over 32 KB. Run it in your package or in an app that installs it; `doctor integration docs` does not check size.',},{type: 'code',lang: 'bash',- code: 'npx astryx doctor',+ code: 'astryx doctor',},{type: 'code',@@ -173,7 +173,7 @@ fix: Remove \`summary\`: SingleComponentDoc has no field \`summary\`.`,{type: 'code',lang: 'bash',- code: 'npx astryx integration verify',+ code: 'astryx integration verify',},{type: 'code',diff --git a/packages/cli/assets/docs/tree/checks.doc.mjs b/packages/cli/assets/docs/tree/checks.doc.mjsindex eb1509c23f..99ac9cd401 100644--- a/packages/cli/assets/docs/tree/checks.doc.mjs+++ b/packages/cli/assets/docs/tree/checks.doc.mjs@@ -29,37 +29,37 @@ export const docs = {headers: ['Command', 'Proves', 'Exits 1 when', 'Only warns when'],rows: [[- '`npx astryx doctor integration validate`',+ '`astryx doctor integration validate`','The manifest loads, each root holds contributions the CLI can read, and each doc matches its authoring type','A declared root is missing (`missing_root`), a contribution does not load (`invalid_doc`, `invalid_component`, `invalid_theme`), or two templates in the package replace one Core id (`ambiguous_template_replacement`)',"The manifest has a key this CLI does not know (`unknown_manifest_key`), or a doc field does not match the doc's authoring type: a field the type does not have, a missing required field, or a value outside the field's type. It also warns on what no reader can serve: a prop listed twice (`duplicate_prop`), a `propDescriptions` key that names no documented prop (`unknown_translated_prop`), a section with no content (`empty_section`), two sections of a topic with one key (`duplicate_section_key`), or a `.doc.zh.mjs` or `.doc.dense.mjs` overlay beside no topic file (`orphan_doc_overlay`). It checks docs with your installed `typescript`, or, where that is missing or has no JavaScript compiler API (TypeScript 7), with an installed `@typescript/typescript6`; without either, it prints `[skip] Docs not type-checked`. With no `astryx.integration.mjs` it prints a hint and exits 0",],[- '`npx astryx doctor integration components`',+ '`astryx doctor integration components`',"No component name clashes with a Core component, each `replaces` names one Core component, and each component doc's props match the component's TypeScript props",'Core is not installed (`core_not_found`). In a package that declares the CLI range that turns replacement on, a `replaces` target is missing (`missing_component_replacement_target`) or invalid (`invalid_component_replacement`), or two components replace one Core component (`ambiguous_component_replacement`)','A name clashes with Core, a component sets `replaces` in a package without that range (`inactive_component_replacement`, plus any missing, invalid, or duplicate `replaces` reported as a warning), or a documented prop differs from the code: it is missing there (`not_in_code`), the doc omits a prop the package declares (`not_in_doc`), or its `required` (`required_mismatch`), type (`type_mismatch`), or literal `default` (`default_mismatch`) disagrees, or a `{@link}` in a component doc names no doc (`invalid_doc_graph`). It reads props with your installed `typescript`; without it, it prints `[skip] Props not compared`',],[- '`npx astryx doctor integration templates`',+ '`astryx doctor integration templates`','Each `replaces` names a Core template of the same type','A `replaces` target is missing (`missing_template_replacement_target`) or of the other type (`invalid_template_replacement`), or two templates replace one id (`ambiguous_template_replacement`)','A template id matches a Core id without `replaces`',],[- '`npx astryx doctor integration docs`',+ '`astryx doctor integration docs`','Your docs tree, every link, topic names against Core, passages two topics repeat word for word, padding phrases and low-density topics, and written pointers to docs','A topic takes a Core topic name without `replaces` or `extends`, a doc is invalid (`invalid_doc`), or a namespace or placement fails, which hides the doc (`invalid_doc_graph`)','A link names no doc (`invalid_doc_graph`), two topics repeat a passage word for word (`copied_passage`), prose pads with a listed phrase or falls under the density floor (`doc_fluff`), or prose, a description or summary, or the text of a component doc writes `astryx docs <name>` where a link would be checked (`stray_doc_pointer`)',],[- '`npx astryx integration check`',+ '`astryx integration check`','Everything the four `doctor integration` checks prove, in one command, for your build','Any of the four would exit 1 on its own. With `--strict`, also any warning, and any check that did not run, such as a package with no `astryx.integration.*`','Anything the four warn about, unless you pass `--strict`',],[- '`npx astryx integration verify`',+ '`astryx integration verify`','The packed package holds every file, shows the same contributions, resolves every public import, and declares the CLI it needs','Anything `validate` fails on, no manifest, a file left out of the `.tgz` file, an import that does not resolve, or a missing CLI peer','Anything `validate` warns about, or a component sets `replaces` and the package does not declare the CLI range that turns it on (`component_replaces_needs_cli`)',@@ -68,7 +68,7 @@ export const docs = {},{type: 'prose',- text: 'Pass a package name, such as `npx astryx doctor integration validate @acme/astryx-widgets`, to check an installed copy from an app instead. To fix a props finding, see {@link generic:check-the-props}.',+ text: 'Pass a package name, such as `astryx doctor integration validate @acme/astryx-widgets`, to check an installed copy from an app instead. To fix a props finding, see {@link generic:check-the-props}.',},],},@@ -92,8 +92,8 @@ export const docs = {'`integration check` runs `validate`, `components`, `templates`, and `docs` in that order, prints each result, then a summary, and exits 1 when any of them would.','`--strict` also exits 1 on any warning and on any check that did not run. Without it, warnings keep exit code 0: use that while you fix the warnings a package already has.','Its exit codes and JSON are a contract for your build: a new check, or a new failure code, joins only in a minor release that names it in the release notes. A patch can still ship a Core component, template, or CLI topic whose name conflicts with one of yours.',- '`integration verify` runs `validate` but none of the other three: a Core name clash, a `replaces` that names no Core template, a topic that takes a Core name, or a hidden guide still passes it. Run both before you publish: `npx astryx integration check --strict && npx astryx integration verify`.',- 'Bare `npx astryx doctor` in the package also warns about a doc section over 32 KB, which no check above measures.',+ '`integration verify` runs `validate` but none of the other three: a Core name clash, a `replaces` that names no Core template, a topic that takes a Core name, or a hidden guide still passes it. Run both before you publish: `astryx integration check --strict && astryx integration verify`.',+ 'Bare `astryx doctor` in the package also warns about a doc section over 32 KB, which no check above measures.',],},],diff --git a/packages/cli/assets/docs/tree/ci-and-containers.doc.mjs b/packages/cli/assets/docs/tree/ci-and-containers.doc.mjsnew file mode 100644index 0000000000..5a118506b7--- /dev/null+++ b/packages/cli/assets/docs/tree/ci-and-containers.doc.mjs@@ -0,0 +1,88 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `astryx docs global/ci-and-containers`: Astryx in CI and containers: no+ * update checks, caching versions, read-only home folders (spec AST-081 FR6,+ * FR7, FR10).+ */++/** @type {import('@astryxdesign/cli/authoring').ReferenceDoc} */+export const docs = {+ type: 'generic',+ name: 'ci-and-containers',+ placement: {+ parent: 'namespace:global',+ slot: 'guides',+ order: 8,+ },+ title: 'CI and containers',+ category: 'guide',+ keywords: [+ 'ci',+ 'github actions',+ 'container',+ 'docker',+ 'read-only home',+ 'cache the release cache',+ ],+ description:+ "What Astryx does in CI and containers: no update checks or notices, the project's version as always, and how to cache versions or work with a read-only home folder.",+ sections: [+ {+ id: 'in-ci',+ title: 'In CI',+ content: [+ {+ type: 'list',+ style: 'unordered',+ items: [+ 'Most CI services set `CI=true`. When `CI` is set to anything but empty, `0`, or `false`, Astryx never checks for updates and never prints a notice; `CI=false`, `CI=0`, and an empty `CI` do not count. `NO_UPDATE_NOTIFIER`, set to anything, does the same anywhere.',+ "Add `@astryxdesign/cli` to the project as a devDependency at the same version as `@astryxdesign/core`; then CI runs the version pinned in the repo, and nothing is fetched. A global install in a CI image also works: in a project, it runs the project's version.",+ 'Use `--json` for output a script reads; it never carries the answered-by line or a notice.',+ ],+ },+ ],+ },+ {+ id: 'cache',+ title: 'Cache project versions',+ content: [+ {+ type: 'prose',+ text: "When the project installs its own CLI and you install the project's dependencies first, there is nothing to cache. Astryx downloads into its cache only the CLI version a project whose own CLI cannot start needs, and, outside a project, the Core of a global install for commands that read components. In CI it downloads nothing in the background, so a global install in a CI image fetches that Core on its first component command. To skip those downloads on every run, cache this folder between runs:",+ },+ {+ type: 'table',+ headers: ['Linux', 'macOS', 'Windows'],+ rows: [+ [+ '`~/.cache/astryx` (or `$XDG_CACHE_HOME/astryx`)',+ '`~/Library/Caches/astryx`',+ '`%LOCALAPPDATA%\\astryx\\Cache`',+ ],+ ],+ },+ ],+ },+ {+ id: 'read-only',+ title: 'Read-only home folders',+ content: [+ {+ type: 'prose',+ text: "When the cache cannot be written, a project whose own CLI cannot start is answered by the global install, with a warning naming the folder. Point `XDG_CACHE_HOME` at a writable absolute path, or reinstall the project's dependencies. The global install's daily check and agent guide are skipped quietly when they cannot be written.",+ },+ ],+ },+ {+ id: 'more',+ title: 'More on global mode',+ content: [+ {+ type: 'prose',+ text: 'This page is part of {@link namespace:global}, which explains what global mode is and how each part works.',+ },+ ],+ },+ ],+};diff --git a/packages/cli/assets/docs/tree/cli-command.doc.mjs b/packages/cli/assets/docs/tree/cli-command.doc.mjsnew file mode 100644index 0000000000..fda721f78c--- /dev/null+++ b/packages/cli/assets/docs/tree/cli-command.doc.mjs@@ -0,0 +1,142 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `astryx docs cli/integrations/building-blocks/configuration/cli-command`:+ * name the command an integration's users run the CLI with, so every command+ * the CLI prints in their apps starts with it.+ */++/** @type {import('@astryxdesign/cli/authoring').ReferenceDoc} */+export const docs = {+ type: 'generic',+ name: 'cli-command',+ placement: {parent: 'namespace:configuration', slot: 'guides', order: 15},+ title: 'CLI command',+ category: 'guide',+ keywords: [+ 'cliCommand',+ 'command name',+ 'wrapper',+ 'printed commands',+ 'pnpm exec astryx',+ ],+ description:+ 'Name the command your users run the CLI with, so every command the CLI prints in their apps starts with it.',+ sections: [+ {+ id: 'when-to-set-it',+ title: 'When to set it',+ content: [+ {+ type: 'prose',+ text: "The CLI ends most answers with the next command to run: a hint, an error fix, a Doctor fix, or a doc example. By default each one starts with a command that reaches the release that answered: what the app's package manager runs, such as `pnpm exec astryx` or `yarn astryx`, when the app's own CLI answered, and otherwise the CLI package pinned to that release, such as `npx @astryxdesign/[email protected]`.",+ },+ {+ type: 'prose',+ text: 'Set `cliCommand` only when your users run the CLI some other way, such as a wrapper your company ships that runs it with your package loaded. Otherwise the commands the CLI prints send them, and their agents, to a CLI that answers without your package. Most packages leave it out.',+ },+ ],+ },+ {+ id: 'set-it',+ title: 'Set it',+ content: [+ {+ type: 'prose',+ text: 'Add `cliCommand` to `astryx.integration.mjs`: the command, without a subcommand.',+ },+ {+ type: 'code',+ lang: 'js',+ code: `// astryx.integration.mjs+export default {+ components: './components',+ cliCommand: 'acme astryx',+};`,+ },+ {+ type: 'prose',+ text: 'In an app that installs your package, the CLI then prints every command with it:',+ },+ {+ type: 'code',+ lang: 'text',+ code: 'Error: Theme "ocean" is not added. Run `acme astryx theme add ocean` first.',+ },+ {+ type: 'prose',+ text: 'That covers hints, errors, suggestions, Doctor fixes, `--help`, the setup reminder, the agent block `init` writes, and doc text. `--json` output keeps every command without a runner, as in `"command": "astryx theme add ocean"`, so a script reads the same fields in every app.',+ },+ ],+ },+ {+ id: 'how-the-cli-picks',+ title: 'How the CLI picks the command',+ content: [+ {+ type: 'list',+ style: 'ordered',+ items: [+ 'The `cliCommand` of the packages the app loads, when they name one command.',+ 'The command a host tool names when it runs the CLI for the app. Nothing in a plain project names one.',+ "A command that reaches the release that answered: what the app's package manager runs when the app's own CLI answered, such as `pnpm exec astryx` or `yarn astryx`; `astryx` outside a project when the CLI installed for the computer answered; otherwise the CLI package pinned to that release, such as `npx @astryxdesign/[email protected]` (see {@link generic:who-answers}).",+ ],+ },+ {+ type: 'prose',+ text: 'Two packages that set the same command agree, and the CLI uses it.',+ },+ ],+ },+ {+ id: 'when-two-packages-disagree',+ title: 'When two packages disagree',+ content: [+ {+ type: 'prose',+ text: "If two packages an app loads set different commands, the CLI uses neither: it prints commands with what the app's package manager runs, even when a host tool named a command. `astryx doctor` warns in its `cli-command` check and names both packages:",+ },+ {+ type: 'code',+ lang: 'text',+ code: `status: [warn]+label: CLI command+message: Loaded integrations declare different CLI commands: @acme/astryx-widgets (\`acme astryx\`), @other/kit (\`other astryx\`). Neither is used, so printed commands start with \`pnpm exec astryx\`.`,+ },+ {+ type: 'prose',+ text: 'The app fixes it by removing the package that does not belong, or the packages agree on one command.',+ },+ ],+ },+ {+ id: 'check-it',+ title: 'Check it',+ content: [+ {+ type: 'prose',+ text: 'An invalid value is ignored, and the rest of your manifest still loads. `astryx doctor integration validate` reports it as `invalid_cli_command`. A valid `cliCommand` is one line of plain text without spaces at either end, at most 120 characters.',+ },+ {+ type: 'prose',+ text: "In an app that installs your package, `astryx doctor` passes its `cli-command` check and names your package as the one that set the command. A CLI released before this field reports `cliCommand` as an unknown key and prints the package manager's command.",+ },+ {+ type: 'code',+ lang: 'bash',+ code: 'astryx doctor integration validate\n# In an app that installs the package\nastryx doctor',+ },+ ],+ },+ {+ id: 'global-mode',+ title: 'In global mode',+ content: [+ {+ type: 'prose',+ text: "In global mode: outside a project, the `cliCommand` of integrations installed for the computer applies; when none is declared, commands start with the plain command of the CLI installed for the computer. Inside a project, only the project's integrations count, so a `cliCommand` from a package installed for the computer never changes the project's printed commands. See {@link namespace:global} and {@link generic:global-integrations}.",+ },+ ],+ },+ ],+};diff --git a/packages/cli/assets/docs/tree/cli.doc.mjs b/packages/cli/assets/docs/tree/cli.doc.mjsindex 1c1903bb91..21279b192f 100644--- a/packages/cli/assets/docs/tree/cli.doc.mjs+++ b/packages/cli/assets/docs/tree/cli.doc.mjs@@ -20,4 +20,10 @@ export const docs = {guides: {title: 'Guides', accepts: {kinds: ['generic', 'namespace']}},reference: {title: 'Reference', accepts: {kinds: ['namespace']}},},+ blocks: [+ {+ type: 'prose',+ text: 'Use the CLI in any folder: install it once for your computer, and every project still gets the release that matches its Core. See {@link namespace:global}.',+ },+ ],};diff --git a/packages/cli/assets/docs/tree/codemods.doc.mjs b/packages/cli/assets/docs/tree/codemods.doc.mjsindex 17db365f86..de4fcd48a1 100644--- a/packages/cli/assets/docs/tree/codemods.doc.mjs+++ b/packages/cli/assets/docs/tree/codemods.doc.mjs@@ -27,7 +27,7 @@ export const docs = {{type: 'code',lang: 'bash',- code: 'npx astryx integration add codemod rename-delay --to 0.7.0',+ code: 'astryx integration add codemod rename-delay --to 0.7.0',},{type: 'code',@@ -116,9 +116,9 @@ export default {type: 'code',lang: 'bash',code: `# Preview each codemod and the files it would change-npx astryx upgrade --from 0.6.3 --integration @acme/astryx-widgets+astryx upgrade --from 0.6.3 --integration @acme/astryx-widgets# Write the changes-npx astryx upgrade --from 0.6.3 --integration @acme/astryx-widgets --apply`,+astryx upgrade --from 0.6.3 --integration @acme/astryx-widgets --apply`,},{type: 'code',@@ -143,5 +143,15 @@ Applying integration codemods...},],},+ {+ id: 'global-mode',+ title: 'In global mode',+ content: [+ {+ type: 'prose',+ text: "In global mode: inside an app, `upgrade` runs with the release equal to the app's Core, whichever copy of the CLI the user starts, and only the codemods of integrations the app installs run. Outside a project, `upgrade` lists codemods and migrates nothing. See {@link namespace:global} and {@link command:upgrade}.",+ },+ ],+ },],};diff --git a/packages/cli/assets/docs/tree/commands.doc.mjs b/packages/cli/assets/docs/tree/commands.doc.mjsindex bff46a102d..4305d1b226 100644--- a/packages/cli/assets/docs/tree/commands.doc.mjs+++ b/packages/cli/assets/docs/tree/commands.doc.mjs@@ -13,7 +13,7 @@ export const docs = {name: 'commands',title: 'Commands',summary:- 'Every command and subcommand: usage, options, examples, and exit codes.',+ 'Every command and subcommand: usage, options, examples, exit codes, and what it does outside a project.',keywords: ['commands', 'usage', 'options', 'flags'],placement: {parent: 'namespace:cli', slot: 'reference', order: 10},slots: {@@ -22,4 +22,10 @@ export const docs = {adopts: [{source: {group: 'cli/commands', kinds: ['command']}, into: 'commands'},],+ blocks: [+ {+ type: 'prose',+ text: "In global mode: each command declares its behavior outside projects (`outsideProject`). Most answer like a new project; some write nothing and name the project they need; `doctor`, `init`, and `upgrade` behave differently. Commands with different behavior describe it in their `In global mode:` note, and CLI tests run each command in an empty folder against its declared value. Inside a project, the project's Astryx release runs every command, whichever astryx command you type. See {@link namespace:global}.",+ },+ ],};diff --git a/packages/cli/assets/docs/tree/component-imports.doc.mjs b/packages/cli/assets/docs/tree/component-imports.doc.mjsindex 4cdb621ac9..016a835d5d 100644--- a/packages/cli/assets/docs/tree/component-imports.doc.mjs+++ b/packages/cli/assets/docs/tree/component-imports.doc.mjs@@ -56,7 +56,7 @@ export const docs = {{type: 'code',lang: 'bash',- code: 'npx astryx integration verify',+ code: 'astryx integration verify',},{type: 'list',@@ -73,5 +73,15 @@ export const docs = {},],},+ {+ id: 'global-mode',+ title: 'In global mode',+ content: [+ {+ type: 'prose',+ text: "In global mode: outside a project, imports the CLI prints name packages installed for the computer, which a new app must install before it can build them; inside a project, only packages the project installs are printed. See {@link namespace:global} and {@link generic:global-integrations}.",+ },+ ],+ },],};diff --git a/packages/cli/assets/docs/tree/components.doc.mjs b/packages/cli/assets/docs/tree/components.doc.mjsindex 553bc493ca..8dd93cd8e7 100644--- a/packages/cli/assets/docs/tree/components.doc.mjs+++ b/packages/cli/assets/docs/tree/components.doc.mjs@@ -20,4 +20,10 @@ export const docs = {accepts: {kinds: ['generic', 'namespace']},},},+ blocks: [+ {+ type: 'prose',+ text: 'In global mode: components from an integration installed for the computer show up outside projects; inside a project, only components from integrations the project installs. See {@link namespace:global} and {@link generic:global-integrations}.',+ },+ ],};diff --git a/packages/cli/assets/docs/tree/computer-agent-guide.doc.mjs b/packages/cli/assets/docs/tree/computer-agent-guide.doc.mjsnew file mode 100644index 0000000000..03a2391a07--- /dev/null+++ b/packages/cli/assets/docs/tree/computer-agent-guide.doc.mjs@@ -0,0 +1,160 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `astryx docs global/computer-agent-guide`: the one skill file the global+ * install keeps for the whole computer, its links, and `init --user` (spec+ * AST-081 FR8).+ */++/** @type {import('@astryxdesign/cli/authoring').ReferenceDoc} */+export const docs = {+ type: 'generic',+ name: 'computer-agent-guide',+ placement: {+ parent: 'namespace:global',+ slot: 'guides',+ order: 5,+ },+ title: 'The agent guide on your computer',+ category: 'guide',+ keywords: [+ 'agent guide',+ 'init --user',+ 'SKILL.md',+ 'skills',+ 'remove-agents',+ 'claude',+ 'codex',+ 'cursor',+ 'agents',+ 'other agents',+ 'symlink',+ 'link skills',+ ],+ description:+ 'Your global install keeps one short Astryx skill in your home folder and links it into the folders agent tools read, so agents anywhere know Astryx is there. `astryx init --user` writes it now or turns it off.',+ sections: [+ {+ id: 'what',+ title: 'What it is',+ content: [+ {+ type: 'prose',+ text: "A project's agent docs reach only agents working in that project. Your global install also keeps one skill file, `~/.agents/skills/astryx/SKILL.md`, which most coding agents read. It tells agents that Astryx is on this computer, when it is relevant (building or changing UI), and to start with `astryx search`. It names no version, so it never goes stale. Inside a project, the project's own agent docs come first.",+ },+ {+ type: 'prose',+ text: 'It is written in the background on the first run and again after you upgrade, so no command waits for it. Installing the package does not write it, because some package managers skip install scripts.',+ },+ ],+ },+ {+ id: 'where',+ title: 'Where agents find it',+ content: [+ {+ type: 'prose',+ text: "Agents that read only their own skills folder get a link to the skill's folder, so they read the same one file: a folder symlink with a relative target (a junction on Windows, or a copy where neither can be made). Continue's scanner skips links, so it gets a copy, refreshed with the file:",+ },+ {+ type: 'table',+ headers: ['Folder', 'When'],+ rows: [+ ['`~/.claude/skills/astryx`', 'Always'],+ ['`~/.kiro/skills/astryx`', 'When `~/.kiro` exists'],+ [+ '`~/.codeium/windsurf/skills/astryx`',+ 'When `~/.codeium/windsurf` exists',+ ],+ ['`~/.letta/skills/astryx`', 'When `~/.letta` exists'],+ [+ '`~/Library/Developer/Xcode/CodingAssistant/ClaudeAgentConfig/skills/astryx`',+ "When Xcode's coding assistant folder exists",+ ],+ [+ '`~/.config/agents/skills/astryx`',+ 'When `~/.config/agents/skills` exists',+ ],+ [+ '`~/.continue/skills/astryx` (a copy)',+ 'When `~/.continue` exists',+ ],+ ],+ },+ {+ type: 'prose',+ text: "Astryx never replaces anything it did not create at one of these folders, and never writes a folder another tool manages; `astryx doctor` names any it skipped, and any link whose skill folder is missing, as in a container that mounts only one agent's folder.",+ },+ ],+ },+ {+ id: 'cloud-and-apps',+ title: 'Cloud agents and apps',+ content: [+ {+ type: 'list',+ style: 'unordered',+ items: [+ "Cloud and background agents read only the repository, so the project's own agent docs, the block `astryx init` writes into AGENTS.md or CLAUDE.md, are what reach them.",+ 'Apps that take an uploaded skill: upload `~/.agents/skills/astryx/SKILL.md`, or a zip of its folder.',+ ],+ },+ ],+ },+ {+ id: 'other-agents',+ title: 'Other agents',+ content: [+ {+ type: 'prose',+ text: 'If your agent reads skills from another folder, link it to the skill:',+ },+ {+ type: 'code',+ lang: 'bash',+ code: "ln -s ~/.agents/skills/astryx <your agent's skills folder>/astryx",+ },+ {+ type: 'prose',+ text: 'On Windows, in PowerShell:',+ },+ {+ type: 'code',+ lang: 'powershell',+ code: 'New-Item -ItemType Junction -Path "<your agent\'s skills folder>\\astryx" -Target "$HOME\\.agents\\skills\\astryx"',+ },+ ],+ },+ {+ id: 'choose',+ title: 'Write it now, or turn it off',+ content: [+ {+ type: 'code',+ lang: 'bash',+ code: 'astryx init --user\nastryx init --user --remove-agents',+ },+ {+ type: 'list',+ style: 'unordered',+ items: [+ '`init --user` writes the file and the links now.',+ '`--remove-agents` removes the file and every link Astryx made, and turns it off until you run `astryx init --user` again.',+ 'A file you edited is never overwritten or removed; delete it to get the current text.',+ 'Outside a project, `astryx doctor` says whether the skill is there, current, edited, or turned off, and where it is linked.',+ ],+ },+ ],+ },+ {+ id: 'more',+ title: 'More on global mode',+ content: [+ {+ type: 'prose',+ text: "This page is part of {@link namespace:global}, which explains what global mode is and how each part works. A project's own agent docs: {@link command:init}.",+ },+ ],+ },+ ],+};diff --git a/packages/cli/assets/docs/tree/computer-integrations.doc.mjs b/packages/cli/assets/docs/tree/computer-integrations.doc.mjsnew file mode 100644index 0000000000..392e2cf1e4--- /dev/null+++ b/packages/cli/assets/docs/tree/computer-integrations.doc.mjs@@ -0,0 +1,93 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `astryx docs global/computer-integrations`: integrations installed next to the+ * global install, where they work, and how to see them (spec AST-081 FR12).+ */++/** @type {import('@astryxdesign/cli/authoring').ReferenceDoc} */+export const docs = {+ type: 'generic',+ name: 'computer-integrations',+ placement: {+ parent: 'namespace:global',+ slot: 'guides',+ order: 6,+ },+ title: 'Integrations installed globally',+ category: 'guide',+ keywords: [+ 'global integration',+ 'install an integration globally',+ 'npm i -g integration',+ 'integration outside a project',+ 'installed for this computer',+ ],+ description:+ 'Integrations installed next to your global install work in folders outside any project. Inside a project, only the integrations the project installs work, and the others are listed as ones you could add.',+ sections: [+ {+ id: 'install',+ title: 'Install one globally',+ content: [+ {+ type: 'prose',+ text: 'Install the integration the same way you installed the CLI, so the two sit side by side:',+ },+ {+ type: 'code',+ lang: 'bash',+ code: 'npm i -g @astryxdesign/cli @acme/widgets\n# or: pnpm add -g · yarn global add · bun add -g',+ },+ {+ type: 'prose',+ text: 'A tool that installs the CLI together with integrations in one folder, and runs the CLI from there, counts the same way. `npx` and the cache of project versions never count.',+ },+ ],+ },+ {+ id: 'outside',+ title: 'Outside a project, they work',+ content: [+ {+ type: 'prose',+ text: 'In a folder outside any project, Astryx loads each integration installed next to your global install the way a project loads its own: its components, templates, docs, themes, and discover source show up, and a command name it declares starts the commands Astryx prints. One whose `@astryxdesign/core` or `@astryxdesign/cli` peer range leaves out your global version is skipped, and `astryx doctor` says why.',+ },+ ],+ },+ {+ id: 'inside',+ title: "Inside a project, only the project's",+ content: [+ {+ type: 'prose',+ text: "A project's answers must match what it installs: a component from a package it does not install would not build. So inside a project, an integration installed only globally adds nothing. `astryx discover` lists it among the packages the project could add, with the project's install command, when it supports the project's version and loads. When the project installs the same integration, the project's copy is the one used.",+ },+ ],+ },+ {+ id: 'check',+ title: 'See which ones work',+ content: [+ {+ type: 'list',+ style: 'unordered',+ items: [+ 'Outside a project, `astryx doctor` lists the global integrations it uses and warns about each it skips.',+ 'Inside a project, `astryx doctor` and `astryx discover` list the ones the project could add.',+ ],+ },+ ],+ },+ {+ id: 'more',+ title: 'More on global mode',+ content: [+ {+ type: 'prose',+ text: 'This page is part of {@link namespace:global}, which explains what global mode is and how each part works. Building an integration: {@link generic:global-integrations}.',+ },+ ],+ },+ ],+};diff --git a/packages/cli/assets/docs/tree/configuration.doc.mjs b/packages/cli/assets/docs/tree/configuration.doc.mjsindex 4b57c9e334..4b58452f5f 100644--- a/packages/cli/assets/docs/tree/configuration.doc.mjs+++ b/packages/cli/assets/docs/tree/configuration.doc.mjs@@ -9,15 +9,19 @@ export const docs = {placement: {parent: 'namespace:building-blocks', slot: 'guides', order: 60},title: 'Configuration',summary:- 'Set how your integration behaves in an app: agent guidance, debug and gap reports, and more as it grows.',- keywords: ['configuration', 'agent guidance', 'debug', 'gap reports'],+ 'Set how your integration behaves in an app: agent guidance, the command your users run, debug and gap reports, and more as it grows.',+ keywords: ['configuration', 'agent guidance', 'cliCommand', 'debug', 'gap reports'],slots: {guides: {title: 'Configuration', accepts: {kinds: ['generic', 'namespace']}},},blocks: [{type: 'prose',- text: 'Beyond the things you ship, an integration can set how it behaves in an app: the guidance it gives the AI agents working there, and the record it keeps of each CLI run. Open one below to set it up.',+ text: "In global mode: installed for the computer, beside the global CLI, your package's manifest is read as it is in a project and applies in folders outside any project; peer ranges are checked against the global CLI's release. See {@link namespace:global} and {@link generic:global-integrations}.",+ },+ {+ type: 'prose',+ text: 'Beyond the things you ship, an integration can set how it behaves in an app: the guidance it gives the AI agents working there, the command its users run the CLI with, and the record it keeps of each CLI run. Open one below to set it up.',},],};diff --git a/packages/cli/assets/docs/tree/debug-and-gap-reports.doc.mjs b/packages/cli/assets/docs/tree/debug-and-gap-reports.doc.mjsindex 5ee7e8ff5e..fe531be76f 100644--- a/packages/cli/assets/docs/tree/debug-and-gap-reports.doc.mjs+++ b/packages/cli/assets/docs/tree/debug-and-gap-reports.doc.mjs@@ -127,7 +127,7 @@ export const gapReport = {{type: 'code',lang: 'bash',- code: "npx astryx gap-report AcmeCarousel --category missing_variant --reason 'Need a vertical layout'",+ code: "astryx gap-report AcmeCarousel --category missing_variant --reason 'Need a vertical layout'",},{type: 'code',@@ -187,5 +187,15 @@ message: Rerun with --confirm-public to file this report.`,},],},+ {+ id: 'global-mode',+ title: 'In global mode',+ content: [+ {+ type: 'prose',+ text: 'In global mode: when users install your package for their computer, beside the global CLI, its `debug` function receives runs in folders outside any project too; inside a project, only if the project installs it. See {@link namespace:global} and {@link generic:global-integrations}.',+ },+ ],+ },],};diff --git a/packages/cli/assets/docs/tree/define-the-theme.doc.mjs b/packages/cli/assets/docs/tree/define-the-theme.doc.mjsindex e28d662747..dc5f30c500 100644--- a/packages/cli/assets/docs/tree/define-the-theme.doc.mjs+++ b/packages/cli/assets/docs/tree/define-the-theme.doc.mjs@@ -45,7 +45,7 @@ export const oceanTheme = defineTheme({},{type: 'prose',- text: 'Local imports must stay inside the theme folder. One that leaves it, such as `../../shared/colors`, fails with `invalid_theme`, and every theme in the package disappears from `theme list`. `npx astryx theme template` writes a file that explains every `defineTheme` field. For the full token set and component theming, read {@link generic:author-a-theme}.',+ text: 'Local imports must stay inside the theme folder. One that leaves it, such as `../../shared/colors`, fails with `invalid_theme`, and every theme in the package disappears from `theme list`. `astryx theme template` writes a file that explains every `defineTheme` field. For the full token set and component theming, read {@link generic:author-a-theme}.',},],},diff --git a/packages/cli/assets/docs/tree/describe-the-component.doc.mjs b/packages/cli/assets/docs/tree/describe-the-component.doc.mjsindex c72c7bc504..c7076e8915 100644--- a/packages/cli/assets/docs/tree/describe-the-component.doc.mjs+++ b/packages/cli/assets/docs/tree/describe-the-component.doc.mjs@@ -51,7 +51,7 @@ export const docs = {{type: 'code',lang: 'bash',- code: 'npx astryx component AcmeCarousel',+ code: 'astryx component AcmeCarousel',},],};diff --git a/packages/cli/assets/docs/tree/docs.doc.mjs b/packages/cli/assets/docs/tree/docs.doc.mjsindex 4551f109ae..5174a591ef 100644--- a/packages/cli/assets/docs/tree/docs.doc.mjs+++ b/packages/cli/assets/docs/tree/docs.doc.mjs@@ -18,4 +18,10 @@ export const docs = {slots: {guides: {title: 'Guides', accepts: {kinds: ['generic']}},},+ blocks: [+ {+ type: 'prose',+ text: 'In global mode: docs from an integration installed for the computer show up outside projects; inside a project, only docs from integrations the project installs. See {@link namespace:global} and {@link generic:global-integrations}.',+ },+ ],};diff --git a/packages/cli/assets/docs/tree/extend-or-replace.doc.mjs b/packages/cli/assets/docs/tree/extend-or-replace.doc.mjsindex 38ab35a7b1..cdf5b53d2a 100644--- a/packages/cli/assets/docs/tree/extend-or-replace.doc.mjs+++ b/packages/cli/assets/docs/tree/extend-or-replace.doc.mjs@@ -26,7 +26,7 @@ export const docs = {{type: 'code',lang: 'bash',- code: 'npx astryx integration add doc acme-getting-started --replaces getting-started\n# The old name now opens your topic\nnpx astryx docs getting-started',+ code: 'astryx integration add doc acme-getting-started --replaces getting-started\n# The old name now opens your topic\nastryx docs getting-started',},{type: 'code',@@ -51,7 +51,7 @@ export const docs = {{type: 'code',lang: 'bash',- code: 'npx astryx integration add doc acme-theming --extends theme\nnpx astryx docs theme --index',+ code: 'astryx integration add doc acme-theming --extends theme\nastryx docs theme --index',},{type: 'code',@@ -82,7 +82,7 @@ export const docs = {{type: 'code',lang: 'bash',- code: 'npx astryx doctor integration docs',+ code: 'astryx doctor integration docs',},{type: 'code',@@ -99,5 +99,15 @@ export const docs = {},],},+ {+ id: 'global-mode',+ title: 'In global mode',+ content: [+ {+ type: 'prose',+ text: 'In global mode: a doc that extends or replaces a topic from a package installed for the computer applies in folders outside any project; inside a project, only those from packages the project installs apply. See {@link namespace:global} and {@link generic:global-integrations}.',+ },+ ],+ },],};diff --git a/packages/cli/assets/docs/tree/generate-a-palette.doc.mjs b/packages/cli/assets/docs/tree/generate-a-palette.doc.mjsindex 0ac5958567..47ebc55367 100644--- a/packages/cli/assets/docs/tree/generate-a-palette.doc.mjs+++ b/packages/cli/assets/docs/tree/generate-a-palette.doc.mjs@@ -40,9 +40,9 @@ export const docs = {type: 'code',lang: 'bash',code: `# Print the palette without writing files-npx astryx theme palette generate themes/ocean/palette.config.json+astryx theme palette generate themes/ocean/palette.config.json# Write the palette and its receipt-npx astryx theme palette generate themes/ocean/palette.config.json \\+astryx theme palette generate themes/ocean/palette.config.json \\--out themes/ocean/tokens/ocean.palette.ts`,},{diff --git a/packages/cli/assets/docs/tree/global-integrations.doc.mjs b/packages/cli/assets/docs/tree/global-integrations.doc.mjsnew file mode 100644index 0000000000..340088a2d5--- /dev/null+++ b/packages/cli/assets/docs/tree/global-integrations.doc.mjs@@ -0,0 +1,124 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `astryx docs cli/integrations/global-integrations`: make an+ * integration work when people install it next to their global Astryx+ * install; a checklist and the commands to try it (spec AST-081 FR12).+ */++/** @type {import('@astryxdesign/cli/authoring').ReferenceDoc} */+export const docs = {+ type: 'generic',+ name: 'global-integrations',+ placement: {+ parent: 'namespace:integrations',+ slot: 'guides',+ order: 25,+ },+ title: 'Make your integration work globally',+ category: 'guide',+ keywords: [+ 'global integration',+ 'global mode',+ 'npm i -g',+ 'installed for this computer',+ 'outside a project',+ 'peer range',+ 'peerDependencies',+ 'cliCommand conflict',+ 'try it globally',+ ],+ description:+ "People can install your integration next to their global Astryx install, where it works in every folder outside a project; inside a project, only the project's own integrations work. A checklist, with the exact commands to try it.",+ sections: [+ {+ id: 'peer-range',+ title: "First: your peer ranges must include the global CLI's version",+ content: [+ {+ type: 'prose',+ text: 'Your `@astryxdesign/core` (and, if you use it, `@astryxdesign/cli`) `peerDependencies` ranges must include the version of the CLI installed globally. If they do not, Astryx skips your package outside projects, and `astryx doctor` warns and names the range.',+ },+ {+ type: 'prose',+ text: "Inside a project that does not install your package, `astryx discover` offers it, with the command that adds it to that project, once your peer range admits the project's release.",+ },+ ],+ },+ {+ id: 'where-it-works',+ title: 'Where your integration works',+ content: [+ {+ type: 'list',+ style: 'unordered',+ items: [+ "Installed in an app: it works in that app, as always, whichever `astryx` the person runs, because the app's version of Astryx answers there.",+ 'Installed next to the global install (`npm i -g @astryxdesign/cli your-package`), or in the same folder as the CLI by a tool that installs them together: it works in every folder outside a project. People and agents there see its components, templates, docs, themes, codemods, and discover source.',+ "Installed only globally, inside an app that does not install it: it adds nothing there. When it supports the app's version and loads, `astryx discover` lists it as one the app could add, with the app's install command.",+ "Installed both ways: the app's copy is the one used in that app. In your own package folder, your working copy is used.",+ ],+ },+ {+ type: 'prose',+ text: "Astryx loads a global integration with the same loader and checks as an app's, so nothing extra goes in your manifest.",+ },+ ],+ },+ {+ id: 'checklist',+ title: 'Checklist',+ content: [+ {+ type: 'list',+ style: 'unordered',+ items: [+ 'Declare the `@astryxdesign/core` (and, if you use it, `@astryxdesign/cli`) `peerDependencies` range your package really supports. Outside a project, Astryx skips your package when that range leaves out the global version, and `astryx doctor` says why: too narrow, and global users lose it after an upgrade; too wide, and it loads against a Core it may not build with.',+ 'Keep imports in your docs and templates to packages an app installs with yours, since outside a project there is no app to check them against.',+ "If you set `cliCommand`, know that outside a project it starts every command Astryx prints, and that two global integrations naming different commands cancel out, falling back to `astryx` ({@link generic:cli-command}). Inside an app, only the app's integrations count.",+ 'Try it globally before you publish, with the steps below.',+ ],+ },+ ],+ },+ {+ id: 'try-it',+ title: 'Try it globally',+ content: [+ {+ type: 'prose',+ text: 'Pack your package, install it next to a global CLI, and look at it from an empty folder:',+ },+ {+ type: 'code',+ lang: 'bash',+ code: 'npm pack\nnpm i -g @astryxdesign/cli ./your-package-1.0.0.tgz\nmkdir -p /tmp/try-global && cd /tmp/try-global\nastryx discover\nastryx docs\nastryx doctor',+ },+ {+ type: 'list',+ style: 'unordered',+ items: [+ '`astryx discover` lists your package as installed, with what it adds.',+ '`astryx docs` lists your topics, and `astryx search <one of your component names>` finds them.',+ "`astryx doctor`'s `computer-integrations` check lists your package as used, with no warning.",+ "In an app that does not install it, `astryx discover` lists it as one the app could add, with the app's install command, and none of its components or docs show up.",+ ],+ },+ {+ type: 'prose',+ text: 'Remove it again with `npm uninstall -g your-package`.',+ },+ ],+ },+ {+ id: 'more',+ title: 'More on global mode',+ content: [+ {+ type: 'prose',+ text: 'How global mode works for the people who install your package: {@link namespace:global}. Their side of global integrations: {@link generic:computer-integrations}.',+ },+ ],+ },+ ],+};diff --git a/packages/cli/assets/docs/tree/global.doc.mjs b/packages/cli/assets/docs/tree/global.doc.mjsnew file mode 100644index 0000000000..11afee6304--- /dev/null+++ b/packages/cli/assets/docs/tree/global.doc.mjs@@ -0,0 +1,131 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `astryx docs global`: global mode. What it is, how to install it, what you get,+ * and which version runs where; the parent of every global-mode page+ * (spec AST-081).+ */++/** @type {import('@astryxdesign/cli/authoring').NamespaceDoc} */+export const docs = {+ type: 'namespace',+ name: 'global',+ title: 'Global mode',+ summary:+ 'Install Astryx once on your computer and use it in any folder. Each project still runs its own version of Astryx, so a global install never changes what a project gets.',+ keywords: [+ 'global',+ 'global mode',+ 'globally',+ 'global install',+ 'npm i -g',+ 'install globally',+ 'install once',+ 'any folder',+ 'outside a project',+ 'which version',+ 'computer',+ ],+ slots: {+ guides: {+ title: 'Global mode, question by question',+ accepts: {+ kinds: ['generic'],+ },+ },+ },+ blocks: [+ {+ type: 'prose',+ text: "Global mode means installing the Astryx CLI once for your computer, so the astryx command works everywhere: in your projects, in an empty folder, and for every coding agent. Inside a project, the project's own version of Astryx answers, so your global install never changes what a project gets.",+ },+ {+ type: 'code',+ lang: 'bash',+ code: 'npm i -g @astryxdesign/cli',+ },+ {+ type: 'heading',+ level: 3,+ text: 'What you get',+ },+ {+ type: 'list',+ style: 'unordered',+ items: [+ 'Docs, components, templates, and search in any folder, before you have a project.',+ 'Every coding agent on your computer knows Astryx, through a short guide the CLI keeps where agent tools look.',+ "Each project keeps its own version: in a project, the project's version answers, whichever astryx command you run.",+ ],+ },+ {+ type: 'heading',+ level: 3,+ text: 'Which version runs',+ },+ {+ type: 'table',+ headers: ['Where you run it', 'Which version answers'],+ rows: [+ [+ 'Inside a project',+ "The project's own CLI. In a project that installs only `@astryxdesign/core`, the astryx command you started, with a hint once a day to add the CLI.",+ ],+ ['Outside any project', 'Your global version.'],+ [+ 'Commands for your computer, such as `astryx init --user`',+ 'Your global version, in any folder.',+ ],+ ],+ },+ {+ type: 'prose',+ text: 'Not sure whether you want a project install, a global one, or both: {@link generic:project-global-or-both}. The details: {@link generic:who-answers}.',+ },+ {+ type: 'heading',+ level: 3,+ text: 'Updates',+ },+ {+ type: 'prose',+ text: 'Your global install never upgrades itself or a project. When a newer version is out, a command that succeeds ends with a two-line notice, at most once a day: {@link generic:updates}.',+ },+ {+ type: 'heading',+ level: 3,+ text: 'Agents',+ },+ {+ type: 'prose',+ text: 'The CLI keeps a short Astryx guide where agent tools look in your home folder, so an agent working anywhere knows Astryx is there: {@link generic:computer-agent-guide}.',+ },+ {+ type: 'heading',+ level: 3,+ text: 'Integrations',+ },+ {+ type: 'prose',+ text: "Integrations you install next to your global install work outside projects. Inside a project, only the project's own integrations do: {@link generic:computer-integrations}. Building one: {@link generic:global-integrations}.",+ },+ {+ type: 'heading',+ level: 3,+ text: 'More',+ },+ {+ type: 'list',+ style: 'unordered',+ items: [+ 'Install, and work offline: {@link generic:install-once}.',+ 'Monorepos and nested folders: {@link generic:monorepos}.',+ 'CI and containers: {@link generic:ci-and-containers}.',+ 'Something looks wrong: {@link generic:problems}.',+ 'Uninstall and reset: {@link generic:uninstall}.',+ 'Every path, setting, JSON field, and error code: {@link generic:reference}.',+ 'What each command does outside a project: {@link namespace:commands}.',+ ],+ },+ ],+};diff --git a/packages/cli/assets/docs/tree/grade-template-with-agent.doc.mjs b/packages/cli/assets/docs/tree/grade-template-with-agent.doc.mjsindex c9e223a1f1..99fdb1b946 100644--- a/packages/cli/assets/docs/tree/grade-template-with-agent.doc.mjs+++ b/packages/cli/assets/docs/tree/grade-template-with-agent.doc.mjs@@ -36,11 +36,11 @@ export const docs = {code: `Grade integration template <id> from <package> at <revision>.Before scoring:-1. Read \`npx astryx docs cli/integrations/building-blocks/templates/write-good-templates --full\`.-2. Read \`npx astryx docs cli/integrations/building-blocks/templates/write-good-templates/template-grading-rubric --full\` and every guide it links.+1. Read \`astryx docs cli/integrations/building-blocks/templates/write-good-templates --full\`.+2. Read \`astryx docs cli/integrations/building-blocks/templates/write-good-templates/template-grading-rubric --full\` and every guide it links.3. Inspect the template source, its matching .doc.mjs file, package.json exports and files, and astryx.integration.mjs.-4. Run \`npx astryx integration verify\` in the package.-5. Follow \`npx astryx docs cli/integrations/building-blocks/templates/build-the-template/package-and-test/test-template-in-app --full\`: install the packed package in the clean app, copy the template, build the app, and render the behavior matrix.+4. Run \`astryx integration verify\` in the package.+5. Follow \`astryx docs cli/integrations/building-blocks/templates/build-the-template/package-and-test/test-template-in-app --full\`: install the packed package in the clean app, copy the template, build the app, and render the behavior matrix.Score all seven rubric categories. Cite file and line evidence for every deduction. Do not award points for a state you did not inspect. If browser or build evidence is unavailable, say so and mark the template not publishable.diff --git a/packages/cli/assets/docs/tree/install-once.doc.mjs b/packages/cli/assets/docs/tree/install-once.doc.mjsnew file mode 100644index 0000000000..024456773b--- /dev/null+++ b/packages/cli/assets/docs/tree/install-once.doc.mjs@@ -0,0 +1,105 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `astryx docs global/install-once`: install the CLI for the computer with each+ * package manager; the cache of versions projects need; offline (spec AST-081).+ */++/** @type {import('@astryxdesign/cli/authoring').ReferenceDoc} */+export const docs = {+ type: 'generic',+ name: 'install-once',+ placement: {+ parent: 'namespace:global',+ slot: 'guides',+ order: 2,+ },+ title: 'Install Astryx globally',+ category: 'guide',+ keywords: [+ 'pnpm add -g',+ 'yarn global add',+ 'bun add -g',+ 'volta install',+ 'npx',+ 'offline',+ 'cache',+ 'per-user cache',+ 'EACCES',+ 'permission denied',+ 'sudo',+ 'npm prefix',+ ],+ description:+ 'Install the Astryx CLI once for your computer with npm, pnpm, Yarn, Bun, or Volta, and what happens when you are offline.',+ sections: [+ {+ id: 'install',+ title: 'Install it',+ content: [+ {+ type: 'prose',+ text: 'Install the CLI package with your package manager. One astryx command then works in every folder.',+ },+ {+ type: 'code',+ lang: 'bash',+ code: 'npm i -g @astryxdesign/cli\n# or: pnpm add -g @astryxdesign/cli · yarn global add @astryxdesign/cli · bun add -g @astryxdesign/cli · volta install @astryxdesign/cli',+ },+ {+ type: 'prose',+ text: "Keep the CLI installed in each project too: that pins its version for teammates and CI ({@link generic:project-global-or-both}). Inside a project, whichever astryx command you type, the project's version answers. Outside a project, your global install answers with its own version, and a version you name, such as `npx @astryxdesign/[email protected]`, answers as exactly that version.",+ },+ ],+ },+ {+ id: 'eacces',+ title: 'Permission denied (EACCES)',+ content: [+ {+ type: 'prose',+ text: 'If `npm i -g` fails with `EACCES`, do not use `sudo`. Give npm a global folder you own, then add its `bin` folder to your PATH, or use a Node version manager such as nvm, fnm, or Volta:',+ },+ {+ type: 'code',+ lang: 'bash',+ code: 'npm config set prefix ~/.npm-global\nexport PATH="$HOME/.npm-global/bin:$PATH"\nnpm i -g @astryxdesign/cli',+ },+ {+ type: 'prose',+ text: "Astryx's update notice then names that folder in its upgrade command.",+ },+ ],+ },+ {+ id: 'versions-for-projects',+ title: 'Versions for your projects',+ content: [+ {+ type: 'prose',+ text: "When a project's own CLI is installed but cannot start, Astryx runs the CLI version equal to the project's Core instead, installing it once into a cache in your home folder and reusing it. It uses npm for that, so your npm registry, proxy, and offline settings apply. Deleting the cache is safe: versions come back when a project needs them. Where it lives: {@link generic:reference}.",+ },+ ],+ },+ {+ id: 'offline',+ title: 'Offline',+ content: [+ {+ type: 'prose',+ text: "Your global install answers offline in a project with only Core, and so does any project that installs its own CLI. Outside a project, commands that read components, such as `astryx component Button`, need your global version's Core: after any command you run online, your global install downloads it once into the cache in the background, so they work offline from then on (not in CI, where nothing downloads by itself: {@link generic:ci-and-containers}; and not on Windows, where the first component command downloads it). Only a project whose own CLI cannot start needs a version installed or cached; when it is neither and cannot be fetched, your global install answers with a one-line warning, and Astryx waits 2 minutes before trying to download it again (10 minutes after a second failure in a row). {@link generic:problems} has the exact message.",+ },+ ],+ },+ {+ id: 'more',+ title: 'More on global mode',+ content: [+ {+ type: 'prose',+ text: 'This page is part of {@link namespace:global}, which explains what global mode is and how each part works. Next: {@link generic:who-answers}.',+ },+ ],+ },+ ],+};diff --git a/packages/cli/assets/docs/tree/integrations.doc.mjs b/packages/cli/assets/docs/tree/integrations.doc.mjsindex 47e4accaf1..05283d6eed 100644--- a/packages/cli/assets/docs/tree/integrations.doc.mjs+++ b/packages/cli/assets/docs/tree/integrations.doc.mjs@@ -24,13 +24,17 @@ export const docs = {},},blocks: [+ {+ type: 'prose',+ text: 'In global mode: users can install your integration for their computer, beside the global CLI. It then applies in folders outside any project, and inside a project only if the project installs it. See {@link namespace:global} and {@link generic:global-integrations}.',+ },{type: 'prose',text: 'An integration is a way to share things with Astryx users: a package you own and maintain, built on a framework Astryx gives you. Publish one, many, or any mix, and people install it in one step. It works with the Astryx CLI alongside Core. See each kind under {@link namespace:building-blocks}.',},{type: 'prose',- text: 'For example, ship a carousel as an integration. Any app that installs it can find it with `npx astryx search carousel`, and the CLI uses it like any Astryx Core component.',+ text: 'For example, ship a carousel as an integration. Any app that installs it can find it with `astryx search carousel`, and the CLI uses it like any Astryx Core component.',},{type: 'prose',diff --git a/packages/cli/assets/docs/tree/layout.doc.mjs b/packages/cli/assets/docs/tree/layout.doc.mjsindex 68e02dcaf1..8d52e44782 100644--- a/packages/cli/assets/docs/tree/layout.doc.mjs+++ b/packages/cli/assets/docs/tree/layout.doc.mjs@@ -46,7 +46,7 @@ export const docs = {},{type: 'prose',- text: 'This guide decides layout, not component APIs. Run `npx astryx build "<idea>"` to start from the closest template for your app type, and `npx astryx component <Name>` for a component\'s props.',+ text: 'This guide decides layout, not component APIs. Run `astryx build "<idea>"` to start from the closest template for your app type, and `astryx component <Name>` for a component\'s props.',},],slots: {diff --git a/packages/cli/assets/docs/tree/links.doc.mjs b/packages/cli/assets/docs/tree/links.doc.mjsindex 2052123ed1..5a6611ea07 100644--- a/packages/cli/assets/docs/tree/links.doc.mjs+++ b/packages/cli/assets/docs/tree/links.doc.mjs@@ -78,7 +78,7 @@ export const docs = {{type: 'code',lang: 'bash',- code: 'npx astryx doctor integration docs',+ code: 'astryx doctor integration docs',},{type: 'code',diff --git a/packages/cli/assets/docs/tree/monorepos.doc.mjs b/packages/cli/assets/docs/tree/monorepos.doc.mjsnew file mode 100644index 0000000000..a88802af2c--- /dev/null+++ b/packages/cli/assets/docs/tree/monorepos.doc.mjs@@ -0,0 +1,84 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `astryx docs global/monorepos`: how a folder's project is found, in+ * workspaces and nested folders (spec AST-081 FR2).+ */++/** @type {import('@astryxdesign/cli/authoring').ReferenceDoc} */+export const docs = {+ type: 'generic',+ name: 'monorepos',+ placement: {+ parent: 'namespace:global',+ slot: 'guides',+ order: 7,+ },+ title: 'Monorepos and nested folders',+ category: 'guide',+ keywords: [+ 'monorepo',+ 'workspace',+ 'nested folder',+ 'nested project',+ 'subfolder',+ 'packages folder',+ 'which project',+ 'yarn pnp',+ 'hoisting',+ ],+ description:+ 'How Astryx finds the project a folder belongs to, and which version answers in a monorepo, a nested app, or a cloned repository inside another project.',+ sections: [+ {+ id: 'find',+ title: 'How a project is found',+ content: [+ {+ type: 'prose',+ text: 'Astryx searches upward from the current folder: `@astryxdesign/core` or `@astryxdesign/cli` installed there or a few folders above, else the nearest `package.json` declaring either, up to the repository root. Folders without any are outside projects.',+ },+ ],+ },+ {+ id: 'workspaces',+ title: 'Workspaces',+ content: [+ {+ type: 'list',+ style: 'unordered',+ items: [+ 'A workspace member declaring Astryx is its own project, even with packages hoisted to the repository root. A root CLI answers it, as always; a member with its own Core and no CLI anywhere gets answered by the astryx command you started.',+ 'A folder without its own `package.json`, such as `src/` or `scripts/`, belongs to the project above it.',+ 'A repository that builds the CLI itself, with the CLI in `packages/cli` next to Core in `packages/core`, runs that CLI.',+ ],+ },+ ],+ },+ {+ id: 'nested',+ title: 'Nested folders',+ content: [+ {+ type: 'list',+ style: 'unordered',+ items: [+ "Folders inside another project, such as nested apps or cloned repositories, answer with the enclosing project's release.",+ 'Folder names compare as your file system compares them: a folder reached through a link, or typed in different letter case on macOS or Windows, answers like the folder itself.',+ "In a Yarn Plug'n'Play project, Astryx cannot see the project's own CLI, so the astryx command you started answers. Run the project's CLI through Yarn (`yarn astryx`) to use it directly.",+ ],+ },+ ],+ },+ {+ id: 'more',+ title: 'More on global mode',+ content: [+ {+ type: 'prose',+ text: 'Part of {@link namespace:global}: what global mode is and how each part works.',+ },+ ],+ },+ ],+};diff --git a/packages/cli/assets/docs/tree/problems.doc.mjs b/packages/cli/assets/docs/tree/problems.doc.mjsnew file mode 100644index 0000000000..3a3be3ec96--- /dev/null+++ b/packages/cli/assets/docs/tree/problems.doc.mjs@@ -0,0 +1,205 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `astryx docs global/problems`: every line global mode prints, with its+ * cause and fix, quoted from the CLI's own strings (test/global-mode-docs.test.mjs+ * fails when they differ); install problems package managers cause.+ */++/** @type {import('@astryxdesign/cli/authoring').ReferenceDoc} */+export const docs = {+ type: 'generic',+ name: 'problems',+ placement: {+ parent: 'namespace:global',+ slot: 'guides',+ order: 9,+ },+ title: 'Troubleshooting global mode',+ category: 'guide',+ keywords: [+ 'troubleshooting',+ 'error',+ 'not working',+ 'command not found',+ 'ERR_VERSIONS_UNAVAILABLE',+ 'ERR_PROJECT_REQUIRED',+ 'proxy',+ 'registry',+ 'corepack',+ 'windows',+ 'PATH',+ 'wrong astryx',+ 'fallback',+ 'could not get Astryx',+ ],+ description:+ 'Every line Astryx prints in global mode, what it means, and what to do. Plus the install problems package managers cause: permissions, PATH, Corepack, and Windows.',+ sections: [+ {+ id: 'answered-by',+ title: '"astryx: answered by …"',+ content: [+ {+ type: 'code',+ lang: 'text',+ code: 'astryx: answered by CLI 0.7.2 with Core 0.7.2, outside a project',+ },+ {+ type: 'prose',+ text: 'Information, not an error: it names the version that answered and why. It prints in text mode only, never with `--json`. The other forms: {@link generic:who-answers}.',+ },+ ],+ },+ {+ id: 'installing',+ title: '"installing CLI release … into the per-user cache"',+ content: [+ {+ type: 'code',+ lang: 'text',+ code: 'astryx: installing CLI release 0.6.8 into the per-user cache (once)...\nastryx: waiting for another run to finish installing CLI release 0.6.8...',+ },+ {+ type: 'prose',+ text: "The project's own CLI cannot start, so Astryx is installing the CLI version equal to its Core into its cache once. The second line means another run is installing it; this one waits, up to 15 minutes. To avoid the wait, install the project's dependencies.",+ },+ ],+ },+ {+ id: 'notices',+ title: '"A new release of Astryx is available"',+ content: [+ {+ type: 'code',+ lang: 'text',+ code: 'A new release of Astryx is available: 0.7.2 → 0.7.3\nTo upgrade, run: npm i -g @astryxdesign/cli@latest\nTo upgrade, install Node >=22 (this computer runs Node 20.11.0), then run: npm i -g @astryxdesign/cli@latest',+ },+ {+ type: 'prose',+ text: 'A newer version is out; run the command shown. When the newest version needs a newer Node, the second line names it first. To stop notices, set `NO_UPDATE_NOTIFIER`: {@link generic:updates}.',+ },+ ],+ },+ {+ id: 'old-astryx',+ title: '"The astryx command on this computer runs CLI …"',+ content: [+ {+ type: 'code',+ lang: 'text',+ code: 'The astryx command on this computer runs CLI 0.6.4, which answers every folder itself.\nTo upgrade, run: npm i -g @astryxdesign/cli@latest',+ },+ {+ type: 'prose',+ text: "The first astryx command on your PATH is a version from before global mode, so it ignores your projects' versions. Run the command shown, or remove that install. `astryx doctor` lists every astryx command on your PATH in its `cli-on-path` check.",+ },+ ],+ },+ {+ id: 'fallback',+ title: '"could not get Astryx … to match this project\'s Core"',+ content: [+ {+ type: 'code',+ lang: 'text',+ code: "astryx: could not get Astryx 0.6.8 to match this project's Core (the registry could not be reached); answering with CLI 0.7.2 instead\nastryx: could not get Astryx 0.6.8 to match this project's Core (the registry does not have it); answering with CLI 0.7.2 instead\nastryx: could not get Astryx 0.6.8 to match this project's Core (the release cache /home/me/.cache/astryx/releases cannot be written (EACCES)); answering with CLI 0.7.2 instead",+ },+ {+ type: 'prose',+ text: "The project's own CLI cannot start, so Astryx needs the CLI version equal to its Core, and could not get it, so the command still runs: the astryx command you started answers, as before global mode. Its answers may not match the project's Core until you fix the cause. With `--json`, `meta.answeredBy.copy` is `fallback`. Astryx waits 2 minutes before trying the download again, and 10 minutes after a second failure in a row; reinstalling the project's dependencies fixes the project's own CLI.",+ },+ {+ type: 'list',+ style: 'unordered',+ items: [+ "The registry could not be reached: you are offline, or a proxy blocks it. Astryx installs with npm, so set npm's `proxy`, `https-proxy`, or `registry` in your `.npmrc`, or add the CLI to the project and install its dependencies.",+ "The registry does not have it: a private registry without the Astryx packages. Point npm's registry for `@astryxdesign` at one that has them.",+ 'The cache cannot be written: a read-only home folder, as in some containers. Point `XDG_CACHE_HOME` at a writable folder: {@link generic:ci-and-containers}.',+ ],+ },+ ],+ },+ {+ id: 'not-global',+ title: 'A global install that gets no update notice or agent guide',+ content: [+ {+ type: 'prose',+ text: "Astryx treats a copy as installed for your computer only when your package manager's own settings name its folder: npm's global prefix, Bun's `BUN_INSTALL`, Yarn's `global-folder`, pnpm's `PNPM_HOME`, or their defaults. A folder chosen only with a one-off flag, such as `yarn global add --global-folder ~/mine`, is not in any setting, so Astryx treats that copy like a project's: no daily update check and no agent guide. Save the folder in your settings so Astryx knows it is a global install:",+ },+ {+ type: 'code',+ lang: 'bash',+ code: 'yarn config set global-folder ~/mine # writes ~/.yarnrc\nexport BUN_INSTALL=~/mybun # in your shell profile, for Bun',+ },+ ],+ },+ {+ id: 'core-offline',+ title: '"Core … could not be installed" outside a project',+ content: [+ {+ type: 'prose',+ text: "Outside a project, commands that read components (`component`, `search`, `template`, `build`, and the like) use your global version's Core. It ships beside the CLI only for some installs; otherwise your global install downloads it once into its cache in the background after a command you run online (on Windows, the first component command downloads it), and a component command before that, offline, fails with `ERR_VERSIONS_UNAVAILABLE`. Reinstalling the CLI does not help: run any command once online, and component reads work offline from then on. In CI nothing downloads in the background, so the first component command there needs the registry. The global-mode pages ({@link namespace:global}) read offline either way.",+ },+ {+ type: 'prose',+ text: "In a project with nothing installed yet, such as a fresh clone, the same commands use that Core too, and offline the error reads `This project has no Core installed, and Core <version> could not be downloaded`: install the project's dependencies (`npm install`, or your package manager's), and the project's own Core answers from then on.",+ },+ ],+ },+ {+ id: 'unavailable',+ title: 'ERR_VERSIONS_UNAVAILABLE',+ content: [+ {+ type: 'prose',+ text: 'A run fails with `ERR_VERSIONS_UNAVAILABLE` only when nothing can answer: a command that needs Core outside a project cannot install it, or a version you requested exactly cannot be found.',+ },+ ],+ },+ {+ id: 'needs-a-project',+ title: 'Commands that need a project',+ content: [+ {+ type: 'code',+ lang: 'text',+ code: 'Error: No package.json found. Run this command inside an app project.\nError: No package.json found. Run this command inside an integration package.\nError: Could not find @astryxdesign/core package. Make sure you are inside the design system monorepo or have @astryxdesign/core installed.\nError: Could not find installed @astryxdesign/core (or legacy @xds/core). This folder is outside a project; upgrade migrates the code of an app project that installs @astryxdesign/core.',+ },+ {+ type: 'prose',+ text: "Commands that change an app or a package, such as `theme use`, `integration add`, `swizzle`, and `upgrade`, write nothing outside a project and say what they need. Run them in that project. Each command's doc says what it does outside a project ({@link namespace:commands}); a newer command that refuses uses `ERR_PROJECT_REQUIRED`.",+ },+ ],+ },+ {+ id: 'install-problems',+ title: 'Install problems',+ content: [+ {+ type: 'list',+ style: 'unordered',+ items: [+ '`npm i -g` fails with `EACCES` (permission denied): do not use `sudo`. Use a Node version manager, or give npm a global folder you own: `npm config set prefix ~/.npm-global`, then add `~/.npm-global/bin` to your PATH.',+ "`astryx: command not found` after installing: your package manager's global bin folder is not on your PATH. `npm prefix -g` shows npm's (its `bin` folder on macOS and Linux); `pnpm setup` adds pnpm's.",+ '`pnpm add -g` stops with `ERR_PNPM_NO_GLOBAL_BIN_DIR`, often with Corepack: run `pnpm setup`, open a new terminal, and try again. Yarn 2 and later have no `yarn global`; use `npm i -g` instead.',+ 'Windows: npm puts `astryx.cmd` in `%APPDATA%\\npm`, which must be on your PATH. If PowerShell says running scripts is disabled, run `astryx.cmd`, or allow scripts for your user with `Set-ExecutionPolicy -Scope CurrentUser RemoteSigned`.',+ 'Two installs, and the wrong one runs: `astryx doctor` outside a project lists every astryx command on your PATH, in the order your shell tries them.',+ ],+ },+ ],+ },+ {+ id: 'more',+ title: 'More on global mode',+ content: [+ {+ type: 'prose',+ text: 'This page is part of {@link namespace:global}, which explains what global mode is and how each part works.',+ },+ ],+ },+ ],+};diff --git a/packages/cli/assets/docs/tree/project-global-or-both.doc.mjs b/packages/cli/assets/docs/tree/project-global-or-both.doc.mjsnew file mode 100644index 0000000000..0a830dddcb--- /dev/null+++ b/packages/cli/assets/docs/tree/project-global-or-both.doc.mjs@@ -0,0 +1,131 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `astryx docs global/project-global-or-both`: which setup to use, project,+ * global, or both (recommended), with what each costs and how to set it up.+ */++/** @type {import('@astryxdesign/cli/authoring').ReferenceDoc} */+export const docs = {+ type: 'generic',+ name: 'project-global-or-both',+ placement: {+ parent: 'namespace:global',+ slot: 'guides',+ order: 1,+ },+ title: 'Project, global, or both',+ category: 'guide',+ keywords: [+ 'which setup',+ 'project or global',+ 'global or project',+ 'both',+ 'install in project',+ 'npx @astryxdesign/cli',+ 'dev dependency',+ 'recommended setup',+ 'should i install globally',+ ],+ description:+ 'Install Astryx in each project and once for your computer: both is the recommended setup, and the two never conflict. What each side gives you, and how to set it up.',+ sections: [+ {+ id: 'both',+ title: 'Both (recommended)',+ content: [+ {+ type: 'prose',+ text: 'Install the CLI in each project and once for your computer. Each side does something the other cannot, and they never conflict:',+ },+ {+ type: 'list',+ style: 'unordered',+ items: [+ '**In the project**, the CLI version is pinned in `package.json` and the lockfile, so teammates and CI run exactly that version, with nothing fetched at run time.',+ '**Globally**, the astryx command works in every folder, including an empty one before a project exists, and every coding agent on your computer knows Astryx through its agent guide.',+ "**Together**, in a project the project's version always answers, even when you type the global astryx command; outside a project your global version does. Global mode never makes the project's CLI unnecessary.",+ ],+ },+ ],+ },+ {+ id: 'compare',+ title: 'At a glance',+ content: [+ {+ type: 'table',+ headers: ['Setup', 'What you get', 'What it costs', 'Who it is for'],+ rows: [+ [+ 'Both',+ 'A pinned version in each project, plus docs, components, and search in any folder, and an agent guide for every agent',+ 'Two installs to keep current',+ 'Most people',+ ],+ [+ 'Project only',+ 'A version pinned in the repo, the same for the team and CI',+ "No astryx command outside the project; agents elsewhere don't know Astryx",+ 'CI machines and build servers',+ ],+ [+ 'Global only',+ 'Docs, components, and search in any folder; every agent knows Astryx',+ 'Nothing pinned for a team; a project without its own CLI gets whatever version you started',+ 'Agents, prototypes, and quick lookups',+ ],+ ],+ },+ ],+ },+ {+ id: 'set-up',+ title: 'How to set up each',+ content: [+ {+ type: 'prose',+ text: 'In the project folder (the getting-started guide lists the other packages an app installs):',+ },+ {+ type: 'code',+ lang: 'bash',+ code: 'npm install @astryxdesign/core @astryxdesign/cli\nastryx init',+ },+ {+ type: 'prose',+ text: 'Once for your computer:',+ },+ {+ type: 'code',+ lang: 'bash',+ code: 'npm i -g @astryxdesign/cli',+ },+ {+ type: 'prose',+ text: 'For both, do both, in either order.',+ },+ ],+ },+ {+ id: 'what-happens',+ title: 'What happens when you have both',+ content: [+ {+ type: 'prose',+ text: "In a project, the project's version always answers, even when you type the global astryx command; outside a project, your global version does. {@link generic:who-answers}",+ },+ ],+ },+ {+ id: 'more',+ title: 'More on global mode',+ content: [+ {+ type: 'prose',+ text: 'This page is part of {@link namespace:global}, which explains what global mode is and how each part works. To start an app: {@link generic:getting-started}.',+ },+ ],+ },+ ],+};diff --git a/packages/cli/assets/docs/tree/publishing.doc.mjs b/packages/cli/assets/docs/tree/publishing.doc.mjsindex 3fb3ea55f0..1a95eab262 100644--- a/packages/cli/assets/docs/tree/publishing.doc.mjs+++ b/packages/cli/assets/docs/tree/publishing.doc.mjs@@ -27,7 +27,7 @@ export const docs = {{type: 'code',lang: 'bash',- code: 'npx astryx doctor integration validate && npx astryx doctor integration components && npx astryx doctor integration templates && npx astryx doctor integration docs && npx astryx integration verify\nnpm publish --dry-run --access public',+ code: 'astryx doctor integration validate && astryx doctor integration components && astryx doctor integration templates && astryx doctor integration docs && astryx integration verify\nnpm publish --dry-run --access public',},{type: 'code',@@ -99,7 +99,7 @@ export const docs = {{type: 'code',lang: 'bash',- code: 'mkdir check-release && cd check-release\nnpm init -y\nnpm install @astryxdesign/core @astryxdesign/cli @acme/[email protected]\nnpx astryx component AcmeCarousel\nnpx astryx doctor integration validate @acme/astryx-widgets',+ code: 'mkdir check-release && cd check-release\nnpm init -y\nnpm install @astryxdesign/core @astryxdesign/cli @acme/[email protected]\nastryx component AcmeCarousel\nastryx doctor integration validate @acme/astryx-widgets',},{type: 'prose',diff --git a/packages/cli/assets/docs/tree/quick-start.doc.mjs b/packages/cli/assets/docs/tree/quick-start.doc.mjsindex 3c4ab176e6..7eaae541da 100644--- a/packages/cli/assets/docs/tree/quick-start.doc.mjs+++ b/packages/cli/assets/docs/tree/quick-start.doc.mjs@@ -47,7 +47,7 @@ export const docs = {items: ['Set `"type": "module"`: the `.js` files the CLI generates, such as a built theme, are ES modules, and Node fails to load them in a package marked `"type": "commonjs"`, which `npm init -y` writes on npm 11.','Start with `"exports": {}`: each component and template you add then writes the public import that `integration verify` resolves.',- 'Run the CLI as `npx astryx`, which runs the `@astryxdesign/cli` you installed as a devDependency.',+ 'Run the CLI as `astryx`, which runs the `@astryxdesign/cli` you installed as a devDependency.','Component commands read Core, so they need `@astryxdesign/core` installed.',"The checks compare your docs with your code through TypeScript's JavaScript compiler API, which `typescript` 5.0 through 6 has. TypeScript 7 does not ship that API: on TypeScript 7, also install `@typescript/typescript6`, its TypeScript 6 API package, and the checks use it.",],@@ -64,7 +64,7 @@ export const docs = {{type: 'code',lang: 'bash',- code: 'npx astryx integration add component AcmeCarousel',+ code: 'astryx integration add component AcmeCarousel',},{type: 'code',@@ -82,7 +82,7 @@ export const docs = {{type: 'code',lang: 'bash',- code: 'npx astryx component AcmeCarousel',+ code: 'astryx component AcmeCarousel',},{type: 'prose',@@ -127,7 +127,7 @@ export const docs = {{type: 'code',lang: 'bash',- code: 'npx astryx integration verify\nnpm pack --pack-destination ..',+ code: 'astryx integration verify\nnpm pack --pack-destination ..',},{type: 'code',@@ -150,7 +150,7 @@ export const docs = {{type: 'code',lang: 'bash',- code: 'cd ..\nmkdir my-app && cd my-app\nnpm init -y\nnpm install @astryxdesign/core @astryxdesign/cli ../acme-astryx-widgets-1.0.0.tgz\nnpx astryx component AcmeCarousel',+ code: 'cd ..\nmkdir my-app && cd my-app\nnpm init -y\nnpm install @astryxdesign/core @astryxdesign/cli ../acme-astryx-widgets-1.0.0.tgz\nastryx component AcmeCarousel',},{type: 'code',@@ -284,5 +284,15 @@ export const docs = {},],},+ {+ id: 'global-mode',+ title: 'In global mode',+ content: [+ {+ type: 'prose',+ text: 'In global mode: users can also install your package for their computer, beside the global CLI (`npm i -g @astryxdesign/cli your-package`). It then applies in folders outside any project, and inside a project only if the project installs it. See {@link namespace:global} and {@link generic:global-integrations}.',+ },+ ],+ },],};diff --git a/packages/cli/assets/docs/tree/reference.doc.mjs b/packages/cli/assets/docs/tree/reference.doc.mjsnew file mode 100644index 0000000000..783fa2ac36--- /dev/null+++ b/packages/cli/assets/docs/tree/reference.doc.mjs@@ -0,0 +1,192 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `astryx docs global/reference`: every folder, environment variable, JSON+ * field, and error code of global mode, and a short glossary (spec AST-081).+ */++/** @type {import('@astryxdesign/cli/authoring').ReferenceDoc} */+export const docs = {+ type: 'generic',+ name: 'reference',+ placement: {+ parent: 'namespace:global',+ slot: 'guides',+ order: 11,+ },+ title: 'Global mode reference',+ category: 'guide',+ keywords: [+ 'reference',+ 'paths',+ 'folders',+ 'environment variables',+ 'env vars',+ 'XDG_CACHE_HOME',+ 'XDG_CONFIG_HOME',+ 'LOCALAPPDATA',+ 'APPDATA',+ 'meta.available',+ 'error codes',+ 'glossary',+ 'state.json',+ 'settings.json',+ ],+ description:+ 'Every folder global mode uses on each system, the environment variables it reads, the JSON fields it adds, its error codes, and a short glossary.',+ sections: [+ {+ id: 'paths',+ title: 'Folders and files',+ content: [+ {+ type: 'table',+ headers: ['What', 'Linux', 'macOS', 'Windows'],+ rows: [+ [+ 'Cache folder',+ '`~/.cache/astryx` (or `$XDG_CACHE_HOME/astryx`)',+ '`~/Library/Caches/astryx`',+ '`%LOCALAPPDATA%\\astryx\\Cache`',+ ],+ [+ 'Versions for projects',+ '`<cache>/releases/<version>`',+ '`<cache>/releases/<version>`',+ '`<cache>\\releases\\<version>`',+ ],+ [+ 'Settings folder',+ '`~/.config/astryx` (or `$XDG_CONFIG_HOME/astryx`)',+ '`~/Library/Application Support/astryx`',+ '`%APPDATA%\\astryx`',+ ],+ [+ 'Update checks and notices, and why the last notice or check did not happen (for `astryx doctor` only)',+ '`<settings>/state.json`',+ '`<settings>/state.json`',+ '`<settings>\\state.json`',+ ],+ [+ 'Agent guide setting, and the links Astryx made',+ '`<settings>/settings.json`',+ '`<settings>/settings.json`',+ '`<settings>\\settings.json`',+ ],+ [+ 'Agent guide',+ '`~/.agents/skills/astryx/SKILL.md`, linked from `~/.claude/skills/astryx` and others',+ 'the same',+ 'the same, under `%USERPROFILE%`',+ ],+ ],+ },+ {+ type: 'prose',+ text: 'Every folder the agent guide is linked into: {@link generic:computer-agent-guide}.',+ },+ ],+ },+ {+ id: 'env',+ title: 'Environment variables',+ content: [+ {+ type: 'table',+ headers: ['Variable', 'Effect'],+ rows: [+ [+ '`CI`',+ 'Set to anything but empty, `0`, or `false`: no update check and no notice.',+ ],+ [+ '`NO_UPDATE_NOTIFIER`',+ 'Set to anything: no update check and no notice.',+ ],+ [+ '`XDG_CACHE_HOME`, `XDG_CONFIG_HOME`',+ 'On Linux, move the cache and settings folders; used only when absolute.',+ ],+ [+ '`LOCALAPPDATA`, `APPDATA`',+ 'On Windows, the cache and settings folders; used only when absolute.',+ ],+ ],+ },+ {+ type: 'prose',+ text: "Astryx reads no environment variable of its own. npm's own settings, such as its registry and proxy, apply to the versions it installs for projects.",+ },+ ],+ },+ {+ id: 'json',+ title: 'JSON fields',+ content: [+ {+ type: 'list',+ style: 'unordered',+ items: [+ "`meta.answeredBy` on every successful `--json` result: `cli` (the version that answered), `core` (the Core it used, or `null`), and `copy`: `project` (the project's own CLI), `starting` (the astryx command you started, in a project with no CLI of its own), `matched` (the CLI version equal to the project's Core, when the project's own CLI cannot start), `carried` (outside a project), or `fallback` (that version could not be obtained, so the astryx command you started answered instead).",+ '`meta.available` entries from `astryx discover` with `source: "installed for this computer"`: an integration installed next to your global install that the project could add, with its install command in `install`.',+ ],+ },+ ],+ },+ {+ id: 'errors',+ title: 'Error codes',+ content: [+ {+ type: 'list',+ style: 'unordered',+ items: [+ '`ERR_VERSIONS_UNAVAILABLE`: nothing can answer, such as a command that needs Core outside a project that cannot install it. When only the matching version is missing, the run answers anyway, with a warning. {@link generic:problems}',+ '`ERR_PROJECT_REQUIRED`: a command that only works in a project ran outside one. Commands released before global mode keep the codes they already used: `theme use`, `theme remove`, and `theme add <slug>` use `ERR_THEME_INVALID`, `integration add` uses `ERR_FILE_NOT_FOUND`, `swizzle` uses `ERR_CORE_NOT_FOUND`, and `upgrade` uses `ERR_VERSION_DETECT`.',+ ],+ },+ ],+ },+ {+ id: 'changes',+ title: 'What changes in global mode',+ content: [+ {+ type: 'list',+ style: 'unordered',+ items: [+ "Which version answers: in a project, the project's own CLI (with only Core, the astryx command you started); outside one, your global version. {@link generic:who-answers}",+ 'Commands that change a project write nothing outside one; `doctor`, `init`, and `theme add` do something else there. {@link namespace:commands}',+ 'Integrations installed globally work only outside projects. {@link generic:computer-integrations}',+ 'The programmatic API runs in your process with the package you import and never hands off to another version; with `cwd` outside a project, its functions answer as the commands do there. {@link namespace:api}',+ ],+ },+ ],+ },+ {+ id: 'glossary',+ title: 'Glossary',+ content: [+ {+ type: 'list',+ style: 'unordered',+ items: [+ '**Global install**: the CLI installed for your computer with `npm i -g` or another package manager.',+ "**The project's version**: the project's own CLI; it answers every command in that project. A project with only Core has none, so the astryx command you started answers.",+ '**Cache**: the folder where Astryx keeps versions projects need but do not install.',+ ],+ },+ ],+ },+ {+ id: 'more',+ title: 'More on global mode',+ content: [+ {+ type: 'prose',+ text: 'This page is part of {@link namespace:global}, which explains what global mode is and how each part works.',+ },+ ],+ },+ ],+};diff --git a/packages/cli/assets/docs/tree/replace-a-core-component.doc.mjs b/packages/cli/assets/docs/tree/replace-a-core-component.doc.mjsindex 6d39f182d9..0d8a521bc8 100644--- a/packages/cli/assets/docs/tree/replace-a-core-component.doc.mjs+++ b/packages/cli/assets/docs/tree/replace-a-core-component.doc.mjs@@ -103,7 +103,7 @@ export default {{type: 'code',lang: 'bash',- code: 'npx astryx doctor integration components\nnpx astryx component SideNav\nnpx astryx component AcmeSideNav\nnpx astryx component SideNav --package @astryxdesign/core',+ code: 'astryx doctor integration components\nastryx component SideNav\nastryx component AcmeSideNav\nastryx component SideNav --package @astryxdesign/core',},{type: 'list',@@ -115,5 +115,15 @@ export default {},],},+ {+ id: 'global-mode',+ title: 'In global mode',+ content: [+ {+ type: 'prose',+ text: 'In global mode: a replacement from a package installed for the computer applies in folders outside any project; inside a project, only replacements from packages the project installs apply. See {@link namespace:global} and {@link generic:global-integrations}.',+ },+ ],+ },],};diff --git a/packages/cli/assets/docs/tree/replace-a-core-template.doc.mjs b/packages/cli/assets/docs/tree/replace-a-core-template.doc.mjsindex 70caf89eb3..d955056305 100644--- a/packages/cli/assets/docs/tree/replace-a-core-template.doc.mjs+++ b/packages/cli/assets/docs/tree/replace-a-core-template.doc.mjs@@ -48,7 +48,7 @@ export const docs = {{type: 'code',lang: 'bash',- code: 'npx astryx --json template --list --package @astryxdesign/core',+ code: 'astryx --json template --list --package @astryxdesign/core',},{type: 'code',@@ -113,10 +113,10 @@ export default {type: 'code',lang: 'bash',code: `# Receives the active replacement-npx astryx template shell-side-nav src/app+astryx template shell-side-nav src/app# Receives the original Core template-npx astryx template shell-side-nav --package @astryxdesign/core src/app`,+astryx template shell-side-nav --package @astryxdesign/core src/app`,},{type: 'prose',@@ -140,7 +140,7 @@ npx astryx template shell-side-nav --package @astryxdesign/core src/app`,{type: 'code',lang: 'bash',- code: 'npx astryx doctor integration templates',+ code: 'astryx doctor integration templates',},{type: 'table',diff --git a/packages/cli/assets/docs/tree/scaffold.doc.mjs b/packages/cli/assets/docs/tree/scaffold.doc.mjsindex 6feb9661fa..e37eee99d4 100644--- a/packages/cli/assets/docs/tree/scaffold.doc.mjs+++ b/packages/cli/assets/docs/tree/scaffold.doc.mjs@@ -132,7 +132,7 @@ export const docs = {},{type: 'prose',- text: 'Verify: you can state the reason in one sentence, and the choice still holds if the nav doubles in size. `npx astryx build "<idea>"` names the template to start from; scaffold it and the pairing is already wired up.',+ text: 'Verify: you can state the reason in one sentence, and the choice still holds if the nav doubles in size. `astryx build "<idea>"` names the template to start from; scaffold it and the pairing is already wired up.',},],},diff --git a/packages/cli/assets/docs/tree/sections-and-placement.doc.mjs b/packages/cli/assets/docs/tree/sections-and-placement.doc.mjsindex 00c0542ed7..cb18d0dbf6 100644--- a/packages/cli/assets/docs/tree/sections-and-placement.doc.mjs+++ b/packages/cli/assets/docs/tree/sections-and-placement.doc.mjs@@ -26,7 +26,7 @@ export const docs = {{type: 'code',lang: 'bash',- code: 'npx astryx integration add doc deploying --parent acme\n# Open your section\nnpx astryx docs acme',+ code: 'astryx integration add doc deploying --parent acme\n# Open your section\nastryx docs acme',},{type: 'code',@@ -69,7 +69,7 @@ export const docs = {{type: 'code',lang: 'bash',- code: 'npx astryx docs acme/deploying',+ code: 'astryx docs acme/deploying',},],},@@ -84,7 +84,7 @@ export const docs = {{type: 'code',lang: 'bash',- code: 'npx astryx doctor integration docs',+ code: 'astryx doctor integration docs',},{type: 'code',diff --git a/packages/cli/assets/docs/tree/see-it-in-an-app.doc.mjs b/packages/cli/assets/docs/tree/see-it-in-an-app.doc.mjsindex a73fc54a51..f64c9fdc3f 100644--- a/packages/cli/assets/docs/tree/see-it-in-an-app.doc.mjs+++ b/packages/cli/assets/docs/tree/see-it-in-an-app.doc.mjs@@ -26,9 +26,9 @@ export const docs = {{type: 'code',lang: 'bash',- code: `npx astryx component AcmeCarousel-npx astryx component --list-npx astryx search carousel`,+ code: `astryx component AcmeCarousel+astryx component --list+astryx search carousel`,},{type: 'code',@@ -57,5 +57,15 @@ Cycles through slides one at a time. Use it for a small set of related cards.},],},+ {+ id: 'global-mode',+ title: 'In global mode',+ content: [+ {+ type: 'prose',+ text: 'In global mode: to check your package in an app, install it in that app; a copy installed for your computer is not used inside a project. To check it outside projects, install it for your computer beside the CLI. See {@link namespace:global} and {@link generic:global-integrations}.',+ },+ ],+ },],};diff --git a/packages/cli/assets/docs/tree/short-and-findable.doc.mjs b/packages/cli/assets/docs/tree/short-and-findable.doc.mjsindex 9987d6e30a..3241753599 100644--- a/packages/cli/assets/docs/tree/short-and-findable.doc.mjs+++ b/packages/cli/assets/docs/tree/short-and-findable.doc.mjs@@ -21,7 +21,7 @@ export const docs = {content: [{type: 'prose',- text: 'Readers open one section at a time, so give each section one idea and keep it to about 30 lines. `npx astryx doctor` warns on any read over 32 KB.',+ text: 'Readers open one section at a time, so give each section one idea and keep it to about 30 lines. `astryx doctor` warns on any read over 32 KB.',},{type: 'list',@@ -35,7 +35,7 @@ export const docs = {{type: 'code',lang: 'bash',- code: '# The section list\nnpx astryx docs acme/deploying\n# One section\nnpx astryx docs acme/deploying check-before-you-ship\n# Everything\nnpx astryx docs acme/deploying --full',+ code: '# The section list\nastryx docs acme/deploying\n# One section\nastryx docs acme/deploying check-before-you-ship\n# Everything\nastryx docs acme/deploying --full',},],},@@ -93,7 +93,7 @@ export const docs = {{type: 'code',lang: 'bash',- code: 'npx astryx search "place a doc" --type doc',+ code: 'astryx search "place a doc" --type doc',},{type: 'list',diff --git a/packages/cli/assets/docs/tree/single-component.doc.mjs b/packages/cli/assets/docs/tree/single-component.doc.mjsindex 2e8674259c..83be60e434 100644--- a/packages/cli/assets/docs/tree/single-component.doc.mjs+++ b/packages/cli/assets/docs/tree/single-component.doc.mjs@@ -93,7 +93,7 @@ export default {{type: 'code',lang: 'bash',- code: 'npx astryx search "rotating cards" --type component',+ code: 'astryx search "rotating cards" --type component',},],},@@ -130,7 +130,7 @@ export default {'Set `required: true` only when every caller must pass the prop.','Write `default` exactly as the value should appear in documentation.','Skip styling escape hatches such as `xstyle`, `className`, and `style`.',- '`npx astryx doctor integration components` lists a documented prop the code lacks, a public prop the doc misses, and a wrong `required`. See {@link generic:check-the-props}.',+ '`astryx doctor integration components` lists a documented prop the code lacks, a public prop the doc misses, and a wrong `required`. See {@link generic:check-the-props}.',],},],@@ -166,7 +166,7 @@ export default {{type: 'code',lang: 'bash',- code: 'npx astryx component AcmeCarousel\nnpx astryx doctor integration components\nnpx astryx integration verify',+ code: 'astryx component AcmeCarousel\nastryx doctor integration components\nastryx integration verify',},],},diff --git a/packages/cli/assets/docs/tree/start-a-template.doc.mjs b/packages/cli/assets/docs/tree/start-a-template.doc.mjsindex f6d9702f65..dc38f33bef 100644--- a/packages/cli/assets/docs/tree/start-a-template.doc.mjs+++ b/packages/cli/assets/docs/tree/start-a-template.doc.mjs@@ -38,8 +38,8 @@ export const docs = {type: 'code',lang: 'bash',code: `# How an app finds a template and copies it-npx astryx template --list-npx astryx template acme-dashboard src/app/dashboard`,+astryx template --list+astryx template acme-dashboard src/app/dashboard`,},],},@@ -97,7 +97,7 @@ npx astryx template acme-dashboard src/app/dashboard`,{type: 'code',lang: 'bash',- code: '# See the Core ids\nnpx astryx --json template --list --package @astryxdesign/core',+ code: '# See the Core ids\nastryx --json template --list --package @astryxdesign/core',},],},@@ -112,8 +112,8 @@ npx astryx template acme-dashboard src/app/dashboard`,{type: 'code',lang: 'bash',- code: `npx astryx integration add template acme-dashboard-npx astryx integration add template acme-stat-card --type block`,+ code: `astryx integration add template acme-dashboard+astryx integration add template acme-stat-card --type block`,},{type: 'code',@@ -139,5 +139,15 @@ Declare template root ./templates in astryx.integration.mjs.},],},+ {+ id: 'global-mode',+ title: 'In global mode',+ content: [+ {+ type: 'prose',+ text: 'In global mode: when users install your package for their computer, beside the global CLI, your templates show up in folders outside any project; inside a project, only if the project installs your package. See {@link namespace:global} and {@link generic:global-integrations}.',+ },+ ],+ },],};diff --git a/packages/cli/assets/docs/tree/template-doc-overview.doc.mjs b/packages/cli/assets/docs/tree/template-doc-overview.doc.mjsindex ea86d3355a..3f82278f68 100644--- a/packages/cli/assets/docs/tree/template-doc-overview.doc.mjs+++ b/packages/cli/assets/docs/tree/template-doc-overview.doc.mjs@@ -88,7 +88,7 @@ export const docs = {{type: 'code',lang: 'bash',- code: 'npx astryx --json template --list --package @acme/astryx-templates',+ code: 'astryx --json template --list --package @acme/astryx-templates',},{type: 'code',diff --git a/packages/cli/assets/docs/tree/templates.doc.mjs b/packages/cli/assets/docs/tree/templates.doc.mjsindex 8f79829109..17325e19e1 100644--- a/packages/cli/assets/docs/tree/templates.doc.mjs+++ b/packages/cli/assets/docs/tree/templates.doc.mjs@@ -31,4 +31,10 @@ export const docs = {accepts: {kinds: ['namespace']},},},+ blocks: [+ {+ type: 'prose',+ text: 'In global mode: templates from an integration installed for the computer show up outside projects; inside a project, only templates from integrations the project installs. See {@link namespace:global} and {@link generic:global-integrations}.',+ },+ ],};diff --git a/packages/cli/assets/docs/tree/test-in-an-app.doc.mjs b/packages/cli/assets/docs/tree/test-in-an-app.doc.mjsindex 07ca363619..185b557d68 100644--- a/packages/cli/assets/docs/tree/test-in-an-app.doc.mjs+++ b/packages/cli/assets/docs/tree/test-in-an-app.doc.mjs@@ -33,7 +33,7 @@ export const docs = {type: 'list',style: 'unordered',items: [- "Install the CLI in the app too: `npx astryx` runs the CLI from the app's `node_modules`.",+ "Install the CLI in the app too: `astryx` runs the CLI from the app's `node_modules`.",'The app holds a copy, not a link. After each change, pack again and run the same `npm install`.','Reading your work inside the package shows your source. The app shows what npm would publish.',],@@ -51,7 +51,7 @@ export const docs = {{type: 'code',lang: 'bash',- code: 'npx astryx component AcmeCarousel\nnpx astryx template --list --package @acme/astryx-widgets\nnpx astryx theme list --package @acme/astryx-widgets\nnpx astryx docs acme\nnpx astryx search deploying --type doc',+ code: 'astryx component AcmeCarousel\nastryx template --list --package @acme/astryx-widgets\nastryx theme list --package @acme/astryx-widgets\nastryx docs acme\nastryx search deploying --type doc',},{type: 'table',@@ -88,12 +88,12 @@ export const docs = {content: [{type: 'prose',- text: '`npx astryx doctor` checks the whole app, including every package it loaded. `doctor integration validate` checks your package as the app installed it.',+ text: '`astryx doctor` checks the whole app, including every package it loaded. `doctor integration validate` checks your package as the app installed it.',},{type: 'code',lang: 'bash',- code: 'npx astryx doctor\nnpx astryx doctor integration validate @acme/astryx-widgets',+ code: 'astryx doctor\nastryx doctor integration validate @acme/astryx-widgets',},{type: 'code',diff --git a/packages/cli/assets/docs/tree/test-template-in-app.doc.mjs b/packages/cli/assets/docs/tree/test-template-in-app.doc.mjsindex b32a808b31..c61d2be148 100644--- a/packages/cli/assets/docs/tree/test-template-in-app.doc.mjs+++ b/packages/cli/assets/docs/tree/test-template-in-app.doc.mjs@@ -38,14 +38,14 @@ export const docs = {type: 'code',lang: 'bash',code: `# Confirm discovery and metadata-npx astryx --json template --list --package @acme/astryx-widgets+astryx --json template --list --package @acme/astryx-widgets# Inspect source without writing-npx astryx template acme-dashboard --package @acme/astryx-widgets+astryx template acme-dashboard --package @acme/astryx-widgets# Copy a page and a block to their real app locations-npx astryx template acme-dashboard --package @acme/astryx-widgets src/app/acme-dashboard-npx astryx template acme-stat-card --package @acme/astryx-widgets src/components`,+astryx template acme-dashboard --package @acme/astryx-widgets src/app/acme-dashboard+astryx template acme-stat-card --package @acme/astryx-widgets src/components`,},{type: 'list',diff --git a/packages/cli/assets/docs/tree/themes.doc.mjs b/packages/cli/assets/docs/tree/themes.doc.mjsindex e301f85e69..237d21d5c6 100644--- a/packages/cli/assets/docs/tree/themes.doc.mjs+++ b/packages/cli/assets/docs/tree/themes.doc.mjs@@ -21,6 +21,10 @@ export const docs = {'extend a theme',],blocks: [+ {+ type: 'prose',+ text: 'In global mode: outside projects, the theme list includes themes from integrations installed for the computer, and `theme add` there only shows them; inside a project, it lists only themes from integrations the project installs. See {@link namespace:global} and {@link generic:global-integrations}.',+ },{type: 'prose',text: 'A theme contribution has editable `defineTheme` source plus a built module and production CSS. `integration add theme` scaffolds the source and declares the package exports; `theme build` writes the built outputs. An app installs the package, runs `theme add`, applies the theme from its generated app module, and customizes it with `extends` instead of copying source.',diff --git a/packages/cli/assets/docs/tree/troubleshooting.doc.mjs b/packages/cli/assets/docs/tree/troubleshooting.doc.mjsindex 098d9e08dd..6e670ae99a 100644--- a/packages/cli/assets/docs/tree/troubleshooting.doc.mjs+++ b/packages/cli/assets/docs/tree/troubleshooting.doc.mjs@@ -47,7 +47,7 @@ export const docs = {],['Note: `integration pack --check` is deprecated.',- 'The old name still runs the same check. Switch to `npx astryx integration verify`; the old name will be removed in a later release.',+ 'The old name still runs the same check. Switch to `astryx integration verify`; the old name will be removed in a later release.',],],},@@ -59,7 +59,7 @@ export const docs = {content: [{type: 'prose',- text: '`npx astryx integration verify` prints each failure as a `[fail]` line. Add `--json` to see its issue code, such as `component_export_missing`.',+ text: '`astryx integration verify` prints each failure as a `[fail]` line. Add `--json` to see its issue code, such as `component_export_missing`.',},{type: 'table',@@ -130,12 +130,12 @@ export const docs = {"Its doc still names its file. Set `name` to the export, such as `name: 'AcmeCarousel'` in `acme-carousel.doc.mjs`. A family member is listed only when the module its family doc imports exports it ({@link generic:component-family}).",],[- "`npx astryx component Dialog` opens Core's `Dialog`, not yours.",- "A name that Core, a legacy docs package, or another package's file already has stays theirs. Run `npx astryx component Dialog --package @acme/astryx-widgets`, or give your component a name of its own.",+ "`astryx component Dialog` opens Core's `Dialog`, not yours.",+ "A name that Core, a legacy docs package, or another package's file already has stays theirs. Run `astryx component Dialog --package @acme/astryx-widgets`, or give your component a name of its own.",],['`Error: Template "dashboard" is ambiguous — narrow it with --type and/or --package.`',- "Your template id matches a Core id. Rename it, such as `acme-dashboard`, or set `replaces: 'dashboard'` to take its place. `npx astryx doctor integration templates` warns about this before you publish.",+ "Your template id matches a Core id. Rename it, such as `acme-dashboard`, or set `replaces: 'dashboard'` to take its place. `astryx doctor integration templates` warns about this before you publish.",],['`invalid_doc_graph`: `placement.parent "namespace:nope" names no namespace; @acme/astryx-widgets declares "acme".`',@@ -143,10 +143,18 @@ export const docs = {],['Error: Unknown topic "acme". The docs of @acme/astryx-widgets did not load; run `astryx doctor integration docs` in that package to see why.',- 'One invalid doc hides all of your docs. Run `npx astryx doctor integration docs` in the package and fix the `invalid_doc` it names.',+ 'One invalid doc hides all of your docs. Run `astryx doctor integration docs` in the package and fix the `invalid_doc` it names.',],[- '`npx astryx upgrade` runs none of your codemods',+ '`cli-command` warns: `Loaded integrations declare different CLI commands`',+ "Two packages the app loads set different `cliCommand` values, so the CLI prints the package manager's command. Agree on one command, or remove the package that does not belong. See {@link generic:cli-command}.",+ ],+ [+ '`invalid_cli_command`',+ 'Your `cliCommand` is not one line of plain text of at most 120 characters, so it is ignored. Fix the value; the rest of the manifest still loads.',+ ],+ [+ '`astryx upgrade` runs none of your codemods','The app must list your package in `integrations` in `astryx.config`, or pass `--integration @acme/astryx-widgets`. It runs a codemod folder only when its version is after `--from` and at most the installed `@astryxdesign/core`.',],[diff --git a/packages/cli/assets/docs/tree/uninstall.doc.mjs b/packages/cli/assets/docs/tree/uninstall.doc.mjsnew file mode 100644index 0000000000..fa36026973--- /dev/null+++ b/packages/cli/assets/docs/tree/uninstall.doc.mjs@@ -0,0 +1,109 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `astryx docs global/uninstall`: uninstall the global install with each package+ * manager, remove the agent guide, and reset the cache and settings folders.+ */++/** @type {import('@astryxdesign/cli/authoring').ReferenceDoc} */+export const docs = {+ type: 'generic',+ name: 'uninstall',+ placement: {+ parent: 'namespace:global',+ slot: 'guides',+ order: 10,+ },+ title: 'Uninstall and reset',+ category: 'guide',+ keywords: [+ 'uninstall',+ 'remove',+ 'reset astryx',+ 'clear cache',+ 'delete cache',+ 'npm uninstall -g',+ 'remove agent guide',+ 'start over',+ ],+ description:+ 'Remove your global install, the agent guide it keeps, and the folders it uses, or reset them to start over.',+ sections: [+ {+ id: 'agent-guide',+ title: 'First, remove the agent guide',+ content: [+ {+ type: 'prose',+ text: 'While the CLI is still installed, remove the agent guide from your home folder:',+ },+ {+ type: 'code',+ lang: 'bash',+ code: 'astryx init --user --remove-agents',+ },+ {+ type: 'prose',+ text: 'Or delete `~/.agents/skills/astryx` and the links to it listed in {@link generic:computer-agent-guide}.',+ },+ ],+ },+ {+ id: 'uninstall',+ title: 'Uninstall',+ content: [+ {+ type: 'code',+ lang: 'bash',+ code: 'npm uninstall -g @astryxdesign/cli\n# or: pnpm remove -g @astryxdesign/cli · yarn global remove @astryxdesign/cli · bun remove -g @astryxdesign/cli · volta uninstall @astryxdesign/cli',+ },+ {+ type: 'prose',+ text: 'Projects are unaffected: each keeps the CLI it installs, if any.',+ },+ ],+ },+ {+ id: 'reset',+ title: 'Reset',+ content: [+ {+ type: 'prose',+ text: 'Delete either folder to reset it; Astryx recreates what it needs on the next run.',+ },+ {+ type: 'table',+ headers: ['Folder', 'Linux', 'macOS', 'Windows'],+ rows: [+ [+ 'Cache: versions for projects, saved discover answers',+ '`~/.cache/astryx`',+ '`~/Library/Caches/astryx`',+ '`%LOCALAPPDATA%\\astryx\\Cache`',+ ],+ [+ 'Settings: update checks, the agent guide setting, and its links',+ '`~/.config/astryx`',+ '`~/Library/Application Support/astryx`',+ '`%APPDATA%\\astryx`',+ ],+ ],+ },+ {+ type: 'prose',+ text: 'On Linux, `XDG_CACHE_HOME` and `XDG_CONFIG_HOME` move them when set to absolute paths.',+ },+ ],+ },+ {+ id: 'more',+ title: 'More on global mode',+ content: [+ {+ type: 'prose',+ text: 'This page is part of {@link namespace:global}, which explains what global mode is and how each part works.',+ },+ ],+ },+ ],+};diff --git a/packages/cli/assets/docs/tree/updates.doc.mjs b/packages/cli/assets/docs/tree/updates.doc.mjsnew file mode 100644index 0000000000..867c08fd2d--- /dev/null+++ b/packages/cli/assets/docs/tree/updates.doc.mjs@@ -0,0 +1,92 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `astryx docs global/updates`: how the global install learns of newer+ * versions, and the notice it prints (spec AST-081 FR6, FR10).+ */++/** @type {import('@astryxdesign/cli/authoring').ReferenceDoc} */+export const docs = {+ type: 'generic',+ name: 'updates',+ placement: {+ parent: 'namespace:global',+ slot: 'guides',+ order: 4,+ },+ title: 'Updates and notices',+ category: 'guide',+ keywords: [+ 'update',+ 'upgrade',+ 'upgrade astryx',+ 'update notice',+ 'new release',+ 'new version',+ 'NO_UPDATE_NOTIFIER',+ 'latest',+ ],+ description:+ 'Your global install checks for a newer version once a day and prints a two-line notice after a command succeeds. It never upgrades itself or a project.',+ sections: [+ {+ id: 'notice',+ title: 'The notice',+ content: [+ {+ type: 'prose',+ text: "Once a day, never in your first day, your global install checks the registry's `latest` version in the background, without slowing the command. When a newer one exists, a command that succeeds prints two lines on standard error, at most once a day:",+ },+ {+ type: 'code',+ lang: 'text',+ code: 'A new release of Astryx is available: 0.7.2 → 0.7.3\nTo upgrade, run: npm i -g @astryxdesign/cli@latest',+ },+ {+ type: 'list',+ style: 'unordered',+ items: [+ "The command is the one for the package manager that installed your global install: `npm i -g`, `pnpm add -g`, `yarn global add`, `bun add -g`, or `volta install`. A global folder moved with the package manager's own setting (`BUN_INSTALL`, Yarn's `global-folder`, `PNPM_HOME`, or npm's prefix) counts while that setting names it; an app's own copy never runs the update check.",+ 'When the newest version needs a newer Node than your computer runs, the second line says which Node to install first.',+ "Inside a project, the notice is about the project's version, and names the project's install and `upgrade` commands. The install command always adds the CLI next to Core, so a project that installed only Core gets its own CLI too, as recommended.",+ ],+ },+ ],+ },+ {+ id: 'project-notice',+ title: 'In a project',+ content: [+ {+ type: 'code',+ lang: 'text',+ code: 'A new release of Astryx is available: 0.7.1 → 0.7.3\nTo upgrade, run: pnpm add @astryxdesign/[email protected] @astryxdesign/[email protected], then pnpm exec astryx upgrade --from 0.7.1 --apply',+ },+ ],+ },+ {+ id: 'turn-off',+ title: 'Turn it off',+ content: [+ {+ type: 'prose',+ text: 'No notice prints with `--json`, after a failed command, when the `CI` environment variable is set, or when `NO_UPDATE_NOTIFIER` is set; with either variable set, the CLI does not check the registry either. Unlike some CLIs, a notice prints even when standard error is not a terminal, because agents run the CLI without one.',+ },+ {+ type: 'prose',+ text: '`astryx doctor` shows the same thing at any time, in its `newest-release` check, along with why the last notice did not print, if one did not. When the last check ran, and when each notice printed, are kept in `state.json` in the settings folder ({@link generic:reference}).',+ },+ ],+ },+ {+ id: 'more',+ title: 'More on global mode',+ content: [+ {+ type: 'prose',+ text: 'This page is part of {@link namespace:global}, which explains what global mode is and how each part works. Upgrading a project: {@link command:upgrade}.',+ },+ ],+ },+ ],+};diff --git a/packages/cli/assets/docs/tree/upgrading.doc.mjs b/packages/cli/assets/docs/tree/upgrading.doc.mjsindex 3c2603d916..6b5cd357b9 100644--- a/packages/cli/assets/docs/tree/upgrading.doc.mjs+++ b/packages/cli/assets/docs/tree/upgrading.doc.mjs@@ -28,7 +28,7 @@ export const docs = {{type: 'code',lang: 'bash',- code: "# 1. Build and test against the new release\nnpm install -D @astryxdesign/cli@latest @astryxdesign/core@latest\n# 2. Rerun the checks\nnpx astryx doctor integration validate\nnpx astryx doctor integration docs\nnpx astryx integration verify\n# 3. Admit the new Core once the checks pass\nnpm pkg set 'peerDependencies.@astryxdesign/core=^0.6.0 || ^0.7.0'\n# 4. Migrate apps across a change that breaks them\nnpx astryx integration add codemod rename-delay --to 0.7.0",+ code: "# 1. Build and test against the new release\nnpm install -D @astryxdesign/cli@latest @astryxdesign/core@latest\n# 2. Rerun the checks\nastryx doctor integration validate\nastryx doctor integration docs\nastryx integration verify\n# 3. Admit the new Core once the checks pass\nnpm pkg set 'peerDependencies.@astryxdesign/core=^0.6.0 || ^0.7.0'\n# 4. Migrate apps across a change that breaks them\nastryx integration add codemod rename-delay --to 0.7.0",},{type: 'list',@@ -52,7 +52,7 @@ export const docs = {{type: 'code',lang: 'bash',- code: '# Preview what would change; nothing is written\nnpx astryx upgrade --from 0.6.3 --integration @acme/astryx-widgets\n# Write the changes\nnpx astryx upgrade --from 0.6.3 --integration @acme/astryx-widgets --apply',+ code: '# Preview what would change; nothing is written\nastryx upgrade --from 0.6.3 --integration @acme/astryx-widgets\n# Write the changes\nastryx upgrade --from 0.6.3 --integration @acme/astryx-widgets --apply',},{type: 'code',diff --git a/packages/cli/assets/docs/tree/use-a-theme-in-an-app.doc.mjs b/packages/cli/assets/docs/tree/use-a-theme-in-an-app.doc.mjsindex e93f44533b..1d3541ba99 100644--- a/packages/cli/assets/docs/tree/use-a-theme-in-an-app.doc.mjs+++ b/packages/cli/assets/docs/tree/use-a-theme-in-an-app.doc.mjs@@ -26,7 +26,7 @@ export const docs = {{type: 'code',lang: 'bash',- code: 'npm install @acme/astryx-widgets\nnpx astryx theme add ocean --package @acme/astryx-widgets',+ code: 'npm install @acme/astryx-widgets\nastryx theme add ocean --package @acme/astryx-widgets',},{type: 'code',@@ -66,5 +66,15 @@ export const productTheme = defineTheme({},],},+ {+ id: 'global-mode',+ title: 'In global mode',+ content: [+ {+ type: 'prose',+ text: 'In global mode: install the theme package in each app that uses the theme; inside a project, the CLI ignores packages installed for the computer. See {@link namespace:global} and {@link generic:global-integrations}.',+ },+ ],+ },],};diff --git a/packages/cli/assets/docs/tree/verify-packed-template.doc.mjs b/packages/cli/assets/docs/tree/verify-packed-template.doc.mjsindex 872474b285..db795c6b92 100644--- a/packages/cli/assets/docs/tree/verify-packed-template.doc.mjs+++ b/packages/cli/assets/docs/tree/verify-packed-template.doc.mjs@@ -27,7 +27,7 @@ export const docs = {{type: 'code',lang: 'bash',- code: 'npx astryx integration verify',+ code: 'astryx integration verify',},{type: 'prose',@@ -67,7 +67,7 @@ export const docs = {'Whether the copied file type-checks in every supported app toolchain.','Whether package-owned CSS, fonts, icons, images, or media load in a browser.','Whether layout, color modes, keyboard and pointer input, and real content work.',- 'Whether a template id collides with Core, or whether a `replaces` target exists. Run `npx astryx doctor integration templates` for those.',+ 'Whether a template id collides with Core, or whether a `replaces` target exists. Run `astryx doctor integration templates` for those.','How the template scores on quality.',],},diff --git a/packages/cli/assets/docs/tree/versioning.doc.mjs b/packages/cli/assets/docs/tree/versioning.doc.mjsindex 3a7bce28d5..4c63ad41d9 100644--- a/packages/cli/assets/docs/tree/versioning.doc.mjs+++ b/packages/cli/assets/docs/tree/versioning.doc.mjs@@ -54,13 +54,13 @@ export const docs = {rows: [['A component name, such as `AcmeCarousel`',- 'Imports, and `npx astryx component AcmeCarousel`',+ 'Imports, and `astryx component AcmeCarousel`',],['A template id, such as `acme-dashboard`',- '`npx astryx template acme-dashboard`',+ '`astryx template acme-dashboard`',],- ['A theme slug, such as `ocean`', '`npx astryx theme add ocean`'],+ ['A theme slug, such as `ocean`', '`astryx theme add ocean`'],['A topic name or route, such as `acme/deploying`','Reads of the old name, and links to it from other docs',diff --git a/packages/cli/assets/docs/tree/who-answers.doc.mjs b/packages/cli/assets/docs/tree/who-answers.doc.mjsnew file mode 100644index 0000000000..25a671d281--- /dev/null+++ b/packages/cli/assets/docs/tree/who-answers.doc.mjs@@ -0,0 +1,119 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file `astryx docs global/who-answers`: which version answers in each folder, the+ * hand-off, and how to see who answered (spec AST-081 FR2, FR3, FR5, FR9).+ */++/** @type {import('@astryxdesign/cli/authoring').ReferenceDoc} */+export const docs = {+ type: 'generic',+ name: 'who-answers',+ placement: {+ parent: 'namespace:global',+ slot: 'guides',+ order: 3,+ },+ title: 'Which version runs, and why',+ category: 'guide',+ keywords: [+ 'which release',+ 'wrong version',+ 'different version',+ 'answered by',+ 'answeredBy',+ 'hand-off',+ 'handed over',+ 'project version',+ ],+ description:+ "Inside a project, the project's own CLI answers, whichever astryx command you start; in a project with only Core, the astryx command you started answers. Outside a project, your global install answers. How to see which one did.",+ sections: [+ {+ id: 'in-a-project',+ title: "In a project, the project's version",+ content: [+ {+ type: 'list',+ style: 'unordered',+ items: [+ "The project installs the CLI, as recommended: that CLI answers, whatever its version, as it always has. When you type the global astryx command instead, it passes the run to the project's CLI, with the same arguments, input, output, and exit status, so either command gives the same answer.",+ "The project installs only Core, or nothing is installed yet, as in a fresh clone: the astryx command you started answers, as it always has. When its version differs from the project's Core, a hint after the command, once a day, names the command that adds the CLI at Core's version.",+ "The project's CLI is installed but cannot start: the CLI version equal to the project's Core answers instead (from the installed Core, else the lockfile, else the newest one the declared range allows), installed once into a cache.",+ ],+ },+ {+ type: 'prose',+ text: "Components come from `@astryxdesign/core`, and templates, docs, and agent guides come from the CLI. In a project, that Core is the one the project installs, so component commands work offline once the project's dependencies are installed. Outside a project, or in a project with nothing installed yet (a fresh clone), they use the answering version's own Core, from beside the CLI or the cache; when that Core cannot be downloaded, the error says to install the project's dependencies. When the project's CLI and Core are different versions, `astryx doctor` warns and prints the command that brings them to one version.",+ },+ ],+ },+ {+ id: 'outside',+ title: 'Outside a project, your global install',+ content: [+ {+ type: 'prose',+ text: 'In a folder that belongs to no project, your global install answers as a brand-new project on its version would, so you and your agents can read every component and doc. It never installs a newer version by itself.',+ },+ {+ type: 'prose',+ text: 'A few commands work on your computer rather than a folder, such as `astryx init --user`: your global install answers them in any folder.',+ },+ ],+ },+ {+ id: 'see-it',+ title: 'See which version answered',+ content: [+ {+ type: 'prose',+ text: 'In a project with only Core, the hint looks like this, after the command, at most once a day per project:',+ },+ {+ type: 'code',+ lang: 'text',+ code: 'astryx: this project has no Astryx CLI installed; answered by CLI 0.7.2 while its Core is 0.6.8. To match, run: npm install @astryxdesign/[email protected]',+ },+ {+ type: 'prose',+ text: "Otherwise, in text mode, one line on standard error names the version, unless the project's own CLI answered directly:",+ },+ {+ type: 'code',+ lang: 'text',+ code: "astryx: answered by this project's CLI 0.6.8, handed over from CLI 0.7.2\nastryx: answered by CLI 0.6.8 with Core 0.6.8, the release that matches this project's Core\nastryx: answered by CLI 0.7.2 with Core 0.7.2, outside a project\nastryx: answered by CLI 0.7.2 with Core 0.7.2, for this computer",+ },+ {+ type: 'prose',+ text: 'With `--json` nothing extra prints; every result carries `meta.answeredBy` instead ({@link generic:reference}):',+ },+ {+ type: 'code',+ lang: 'json',+ code: '{"meta": {"answeredBy": {"cli": "0.7.2", "core": "0.6.8", "copy": "starting"}}}',+ },+ ],+ },+ {+ id: 'printed-commands',+ title: 'Commands Astryx prints',+ content: [+ {+ type: 'prose',+ text: "Commands the CLI prints for you to run start with a name that reaches the same version: the project's runner (such as `pnpm exec astryx`) in a project, `astryx` outside a project when your global install answered, and otherwise the CLI pinned to the version, such as `npx @astryxdesign/[email protected]`. An integration can name its own command: {@link generic:cli-command}.",+ },+ ],+ },+ {+ id: 'more',+ title: 'More on global mode',+ content: [+ {+ type: 'prose',+ text: 'This page is part of {@link namespace:global}, which explains what global mode is and how each part works. To check your computer, run `astryx doctor` outside any project ({@link command:doctor}). Monorepos: {@link generic:monorepos}.',+ },+ ],+ },+ ],+};diff --git a/packages/cli/assets/docs/tree/write-the-template-file.doc.mjs b/packages/cli/assets/docs/tree/write-the-template-file.doc.mjsindex b0400a7eb3..9869d2fc3d 100644--- a/packages/cli/assets/docs/tree/write-the-template-file.doc.mjs+++ b/packages/cli/assets/docs/tree/write-the-template-file.doc.mjs@@ -44,13 +44,13 @@ export const docs = {type: 'code',lang: 'bash',code: `# Page: src/app/account/page.tsx-npx astryx template acme-account src/app/account+astryx template acme-account src/app/account# Block: src/features/account/acme-stat-card.tsx-npx astryx template acme-stat-card src/features/account+astryx template acme-stat-card src/features/account# Exact destination for either kind-npx astryx template acme-stat-card src/features/account/StatusCard.tsx`,+astryx template acme-stat-card src/features/account/StatusCard.tsx`,},{type: 'prose',diff --git a/packages/cli/assets/docs/working-with-ai.doc.mjs b/packages/cli/assets/docs/working-with-ai.doc.mjsindex c67ca99375..1b27b2c98a 100644--- a/packages/cli/assets/docs/working-with-ai.doc.mjs+++ b/packages/cli/assets/docs/working-with-ai.doc.mjs@@ -36,7 +36,7 @@ export const docs = {type: 'code',lang: 'text',label: 'Paste this into your AI',- code: 'Install @astryxdesign/cli and run `npx @astryxdesign/cli init --features agents` to set up your Astryx context. Read the generated file.',+ code: 'Install @astryxdesign/cli and run `astryx init --features agents` to set up your Astryx context. Read the generated file.',},{type: 'prose',@@ -50,12 +50,16 @@ export const docs = {type: 'code',lang: 'bash',label: 'Manual options',- code: `npx @astryxdesign/cli init --features agents --agent claude # CLAUDE.md if present, else .claude/CLAUDE.md-npx @astryxdesign/cli init --features agents --agent cursor # .cursorrules if present, else AGENTS.md-npx @astryxdesign/cli init --features agents --agent codex # AGENTS.md (Copilot, Codex, etc.)-npx @astryxdesign/cli init --features agents --agent hermes # .hermes.md or HERMES.md if present, else AGENTS.md-npx @astryxdesign/cli init --features agents --agent muse # AGENTS.md (Muse)-npx @astryxdesign/cli init --features agents --agent all # every agent file present, else AGENTS.md and .claude/CLAUDE.md`,+ code: `astryx init --features agents --agent claude # CLAUDE.md if present, else .claude/CLAUDE.md+astryx init --features agents --agent cursor # .cursorrules if present, else AGENTS.md+astryx init --features agents --agent codex # AGENTS.md (Copilot, Codex, etc.)+astryx init --features agents --agent hermes # .hermes.md or HERMES.md if present, else AGENTS.md+astryx init --features agents --agent muse # AGENTS.md (Muse)+astryx init --features agents --agent all # every agent file present, else AGENTS.md and .claude/CLAUDE.md`,+ },+ {+ type: 'prose',+ text: "For agents that work outside any one project, your global install keeps one short Astryx skill, `~/.agents/skills/astryx/SKILL.md`, linked into the skill folders agent tools read, such as `~/.claude/skills/astryx`. It tells agents Astryx is there and when to use it; `astryx init --user` writes it now or, with `--remove-agents`, turns it off. Inside a project, agents follow that project's own agent docs. See {@link generic:computer-agent-guide}.",},],},@@ -92,7 +96,7 @@ npx @astryxdesign/cli init --features agents --agent all # every agent filtype: 'code',lang: 'bash',label: 'Install as a Cursor project rule',- code: `npx @astryxdesign/cli init --features agents --agent-docs-path .cursor/rules/astryx.mdc`,+ code: `astryx init --features agents --agent-docs-path .cursor/rules/astryx.mdc`,},{type: 'prose',@@ -117,7 +121,7 @@ npx @astryxdesign/cli init --features agents --agent all # every agent fil2. How do you make a Dialog non-dismissible?3. What prop does Selector use for its items?-If you don't know all three, run \`npx @astryxdesign/cli init --features agents\` to generate agent docs, then read the generated file.`,+If you don't know all three, run \`astryx init --features agents\` to generate agent docs, then read the generated file.`,},],},@@ -242,5 +246,15 @@ astryx docs principles --dense`,},],},+ {+ id: 'global-mode',+ title: 'In global mode',+ content: [+ {+ type: 'prose',+ text: "In global mode: your global install keeps one Astryx skill in your home folder, linked into the folders agent tools read, so agents outside any project know Astryx is there; inside a project, its own agent docs come first. See {@link namespace:global} and {@link generic:computer-agent-guide}.",+ },+ ],+ },],};diff --git a/packages/cli/authoring/discover/discover.doc.mjs b/packages/cli/authoring/discover/discover.doc.mjsindex 8f1cbf0881..c7b0d6d2ff 100644--- a/packages/cli/authoring/discover/discover.doc.mjs+++ b/packages/cli/authoring/discover/discover.doc.mjs@@ -135,4 +135,10 @@ export const doc = {'};',},],+ notes: [+ {+ type: 'prose',+ text: "In global mode: the discover source of an integration installed for the computer is called in folders outside any project; inside a project, only the sources of integrations the project installs are. See {@link namespace:global} and {@link generic:global-integrations}.",+ },+ ],};diff --git a/packages/cli/authoring/doctypes/_schema.mjs b/packages/cli/authoring/doctypes/_schema.mjsindex 809dadd7e1..bb332cef97 100644--- a/packages/cli/authoring/doctypes/_schema.mjs+++ b/packages/cli/authoring/doctypes/_schema.mjs@@ -574,6 +574,7 @@ export const CommandDocKindSchema = zexitCodes: z.array(z.object({code: z.number(), when: z.string()}).passthrough()).optional(),+ outsideProject: z.enum(['same', 'refuse', 'own']).optional(),related: z.array(z.string()).optional(),notes: z.array(ReferenceContentBlockSchema).optional(),})diff --git a/packages/cli/authoring/doctypes/command/command.doc.mjs b/packages/cli/authoring/doctypes/command/command.doc.mjsindex 0dbaae802f..6e231bd1dd 100644--- a/packages/cli/authoring/doctypes/command/command.doc.mjs+++ b/packages/cli/authoring/doctypes/command/command.doc.mjs@@ -198,6 +198,12 @@ export const doc = {},],},+ {+ name: 'outsideProject',+ type: "'same' | 'refuse' | 'own'",+ description:+ 'What the command does outside a project. `same`: the answer it gives in a new project. `refuse`: it writes nothing and fails, naming the app project or integration package it needs. `own`: something else. Every `refuse` and `own` command also carries an `In global mode:` note in its `notes` that tells readers exactly what it does. Every command and subcommand declares one, and `astryx manifest` publishes it; a command that only groups subcommands declares none. The CLI tests run every command in an empty folder and check what it does against this value; `astryx doctor` does not check it.',+ },{name: 'deprecated',type: 'string',diff --git a/packages/cli/authoring/doctypes/command/type.ts b/packages/cli/authoring/doctypes/command/type.tsindex a516a8c221..7b43e79bde 100644--- a/packages/cli/authoring/doctypes/command/type.ts+++ b/packages/cli/authoring/doctypes/command/type.ts@@ -40,6 +40,18 @@ export interface CommandOptionDoc {cliOnly?: boolean;}+/**+ * What a command does in a folder outside any project:+ * - `same`: it gives the answer it gives in a new project, reading the Core+ * the answering release carries.+ * - `refuse`: it writes nothing and fails before doing any work, naming the app+ * project or integration package it needs.+ * - `own`: it does something else.+ * Every `refuse` and `own` command also carries an `In global mode:` note+ * in its `notes`, for readers.+ */+export type CommandOutsideProject = 'same' | 'refuse' | 'own';+export interface CommandExampleDoc {label?: string;/** A full terminal invocation, e.g. 'astryx search button --json'. */@@ -81,6 +93,8 @@ export interface CommandDoc extends AuthoredDocGraphFields {examples?: CommandExampleDoc[];/** Documented exit codes. */exitCodes?: {code: number; when: string}[];+ /** What the command does outside a project: `same`, `refuse`, or `own`. Every command and subcommand declares one, and `astryx manifest` publishes it; a command that only groups subcommands declares none. */+ outsideProject?: CommandOutsideProject;/** Deprecation notice — a DEP-* id and the replacement. */deprecated?: string;/** Related command names; the CLI links each to its doc. */diff --git a/packages/cli/authoring/doctypes/reference/reference.doc.mjs b/packages/cli/authoring/doctypes/reference/reference.doc.mjsindex be80a48497..1d5d90d361 100644--- a/packages/cli/authoring/doctypes/reference/reference.doc.mjs+++ b/packages/cli/authoring/doctypes/reference/reference.doc.mjs@@ -152,7 +152,7 @@ export default {},{type: 'prose',- text: 'Each `sections[].content` is an ordered array of ReferenceContentBlock, the stable discriminated union of prose, heading, code, table, list, and token-ref, plus the reference block (ReferenceDocBlock). A read inlines a reference block the way it inlines a token-ref, so `astryx docs`, in text and in `--json`, returns only the stable block kinds. Docs-graph-only workflow and collection blocks are exported separately as GraphContentBlock and accepted by NamespaceDoc. choice, callout, and checklist remain invalid. ReferenceContentBlock is also reused by the `notes` field on SchemaDoc and CommandDoc. Inside text, `{@link <target>}` links another doc by identity (`[<provider>:]<kind>:<name>`): the CLI prints the command that opens it, and `astryx doctor` warns on one that names no doc.',+ text: 'Each `sections[].content` is an ordered array of ReferenceContentBlock, the stable discriminated union of prose, heading, code, table, list, and token-ref, plus the reference block (ReferenceDocBlock). A read inlines a reference block the way it inlines a token-ref, so `astryx docs`, in text and in `--json`, returns only the stable block kinds. Docs-graph-only workflow and collection blocks are exported separately as GraphContentBlock and accepted by NamespaceDoc. choice, callout, and checklist remain invalid. ReferenceContentBlock is also reused by the `notes` field on SchemaDoc and CommandDoc. Inside text, `{@link <target>}` links another doc by identity (`[<provider>:]<kind>:<name>`): the CLI prints the command that opens it, and `astryx doctor` warns on one that names no doc. Write a CLI command in text, shell code, or a table cell as a bare `astryx` command: a text read adds the runner the reader uses in front of it, and `--json` returns it as written.',},{type: 'prose',diff --git a/packages/cli/authoring/index.d.ts b/packages/cli/authoring/index.d.tsindex 2c8c58afd5..c7d6759e51 100644--- a/packages/cli/authoring/index.d.ts+++ b/packages/cli/authoring/index.d.ts@@ -163,6 +163,7 @@ export type {CommandArgDoc,CommandOptionDoc,CommandExampleDoc,+ CommandOutsideProject,// enumEnumMemberDoc,} from './doctypes/types.js';diff --git a/packages/cli/authoring/integration/integration.doc.mjs b/packages/cli/authoring/integration/integration.doc.mjsindex f243492bdd..e71dba6ce5 100644--- a/packages/cli/authoring/integration/integration.doc.mjs+++ b/packages/cli/authoring/integration/integration.doc.mjs@@ -16,7 +16,7 @@ export const doc = {'The astryx.integration.* manifest that sits beside an integration ' +"package's package.json. It can preserve a stable provider identity across a package rename, " +"and points the CLI at the package's components, templates, codemods, doc topics, " +- 'source themes, managed agent guidance, and issue tracker. Every field is optional.',+ 'source themes, managed agent guidance, issue tracker, and the command its users run the CLI with. Every field is optional.',appliesTo: 'astryx.integration.{ts,mjs,js}',fields: [{@@ -82,6 +82,13 @@ export const doc = {"Link to this integration's docs site, such as its home page. Catalogs that list the package may show it.",example: "'https://widgets.acme.dev'",},+ {+ name: 'cliCommand',+ type: 'string',+ description:+ 'The command your users run the Astryx CLI with, when it is not their package manager, such as a wrapper your company ships. Every command the CLI prints in an app that loads your package starts with it, in place of `pnpm exec astryx` or `yarn astryx`: hints, errors, Doctor fixes, and doc text. One line, without a subcommand. If two loaded packages set different commands, neither is used and `astryx doctor` warns. An invalid value is ignored with an `invalid_cli_command` warning, and the rest of the manifest still loads. JSON output keeps commands bare.',+ example: "'acme astryx'",+ },],examples: [{@@ -100,6 +107,10 @@ export const doc = {},],notes: [+ {+ type: 'prose',+ text: "In global mode: a manifest loads the same way when users install your package for their computer, beside the global CLI, and then applies in folders outside any project; inside a project, only if the project installs it. Peer ranges for `@astryxdesign/core` and `@astryxdesign/cli` are checked against the global CLI's release. See {@link namespace:global} and {@link generic:global-integrations}.",+ },{type: 'prose',text:@@ -115,7 +126,12 @@ export const doc = {'trimmed, non-blank string of at most 240 Unicode code points with no ' +'line separators, control characters, NUL, or Astryx/XDS managed-marker ' +'text. The configured project may contain at most 32 integration lines ' +- 'total.',+ 'total. Write each command in a line as a bare `astryx` command; the ' ++ 'managed block says once, before your lines, how the app starts the CLI.',+ },+ {+ type: 'prose',+ text: "Set `cliCommand` only when your users run the CLI with a command other than their package manager's, such as `acme astryx`. The CLI picks the command it prints in this order: the `cliCommand` of the loaded integrations when they name one command, then the command a host tool names, then the package manager's. Two different `cliCommand` values cancel out, and `astryx doctor` warns in its `cli-command` check. See `astryx docs cli/integrations/building-blocks/configuration/cli-command`.",},{type: 'prose',diff --git a/packages/cli/authoring/integration/parse.test.mjs b/packages/cli/authoring/integration/parse.test.mjsindex 1d6054efbb..c78fb90251 100644--- a/packages/cli/authoring/integration/parse.test.mjs+++ b/packages/cli/authoring/integration/parse.test.mjs@@ -97,6 +97,17 @@ describe('parseIntegration (load boundary)', () => {expect(reason({docsiteUrl: 'nope'})).toContain('docsiteUrl');});+ it('accepts a cliCommand and rejects one that is not a single clean line', () => {+ expect(parseIntegration({cliCommand: 'acme astryx'})).toEqual({+ cliCommand: 'acme astryx',+ });+ expect(reason({cliCommand: ''})).toContain('cliCommand');+ expect(reason({cliCommand: ' acme astryx'})).toContain('cliCommand');+ expect(reason({cliCommand: 'acme\nastryx'})).toContain('cliCommand');+ expect(reason({cliCommand: 'a'.repeat(121)})).toContain('120');+ expect(reason({cliCommand: 42})).toContain('cliCommand');+ });+it('rejects a noncanonical providerId', () => {expect(reason({providerId: 'Acme Widgets'})).toContain('providerId');});diff --git a/packages/cli/authoring/integration/schema.mjs b/packages/cli/authoring/integration/schema.mjsindex e0bb83d91c..768d2bde52 100644--- a/packages/cli/authoring/integration/schema.mjs+++ b/packages/cli/authoring/integration/schema.mjs@@ -19,6 +19,7 @@ import {formatZodError} from '../_shared/errors.mjs';/** @typedef {import('./type.js').AstryxIntegration} AstryxIntegration */const MAX_AGENT_DOC_LINES = 8;+const MAX_CLI_COMMAND_CODE_POINTS = 120;const MAX_AGENT_DOC_LINE_CODE_POINTS = 240;const MANAGED_MARKER_TEXT = /(?:ASTRYX|XDS):(START|END)/u;const PROVIDER_ID_RE =@@ -51,6 +52,21 @@ function invalidAgentDocLine(value) {return null;}+export const cliCommandSchema = z.string().superRefine((value, ctx) => {+ const message = invalidAgentDocLine(value);+ if (message) {+ ctx.addIssue({code: 'custom', message});+ return;+ }+ const codePoints = [...value].length;+ if (codePoints > MAX_CLI_COMMAND_CODE_POINTS) {+ ctx.addIssue({+ code: 'custom',+ message: `must contain at most ${MAX_CLI_COMMAND_CODE_POINTS} Unicode code points (received ${codePoints})`,+ });+ }+});+const agentDocLineSchema = z.string().superRefine((value, ctx) => {const message = invalidAgentDocLine(value);if (message) ctx.addIssue({code: 'custom', message});@@ -92,14 +108,15 @@ export const integrationBaseSchema = z.object({// IS an authoring mistake and still fails here.export const integrationSchema = integrationBaseSchema.extend({agentDocs: agentDocsSchema.optional(),+ cliCommand: cliCommandSchema.optional(),});/*** Parse every default-manifest field except the independently isolated- * `agentDocs` contribution.+ * `agentDocs` and `cliCommand` fields.* @param {unknown} input* @param {string} label- * @returns {Omit<AstryxIntegration, 'agentDocs'>}+ * @returns {Omit<AstryxIntegration, 'agentDocs' | 'cliCommand'>}*/export function parseIntegrationBase(input, label) {const result = integrationBaseSchema.safeParse(input);@@ -119,6 +136,20 @@ export function parseAgentDocsField(input, label) {return result.data;}+/**+ * Parse only the optional `cliCommand` field. Isolated like `agentDocs`: an+ * invalid command is ignored with a warning, and the rest of the manifest+ * still contributes.+ * @param {unknown} input+ * @param {string} label+ * @returns {string}+ */+export function parseCliCommandField(input, label) {+ const result = cliCommandSchema.safeParse(input);+ if (!result.success) throw new Error(formatZodError(label, result.error));+ return result.data;+}+/*** Compile-time drift-lock: sealed schema must infer exactly {@link AstryxIntegration}.*diff --git a/packages/cli/authoring/integration/type.ts b/packages/cli/authoring/integration/type.tsindex fd313ae61e..4cf9ed39b4 100644--- a/packages/cli/authoring/integration/type.ts+++ b/packages/cli/authoring/integration/type.ts@@ -48,6 +48,14 @@ export interface AstryxIntegration {* accepts it as a known field; catalogs that list the package may show* it. */docsiteUrl?: string;+ /** The command that runs the Astryx CLI for this package's users, such as+ * `acme astryx`. Every command the CLI prints in a project that loads+ * this package starts with it, in place of the package-manager prefix+ * (`pnpm exec astryx`, `yarn astryx`). One line, no subcommand. When two+ * loaded integrations set different commands, neither is used and+ * `astryx doctor` warns. An invalid value is ignored with a warning; the+ * rest of the manifest still loads. JSON output keeps commands bare. */+ cliCommand?: string;}/**diff --git a/packages/cli/clients/cli/bin/astryx.mjs b/packages/cli/clients/cli/bin/astryx.mjsindex b719de52a3..90afe4fabb 100755--- a/packages/cli/clients/cli/bin/astryx.mjs+++ b/packages/cli/clients/cli/bin/astryx.mjs@@ -14,7 +14,7 @@// unsupported runtimes this guard protects against.//// Sibling package modules (e.g. `cli/`, `lib/`) are resolved by this bin's REAL-// path. When the CLI is installed as a package, `npx astryx` runs this file+// path. When the CLI is installed as a package, the package manager runs this file// through the `node_modules/.bin/astryx` symlink, and some Node versions resolve// relative specifiers from the symlink's directory rather than the real package// — breaking bare `../…` imports with a cryptic ERR_MODULE_NOT_FOUND.@@ -53,10 +53,24 @@ if (!isNodeVersionSupported(process.versions.node)) {process.exit(1);}+// Global mode: choose the release that answers this folder and, when it is+// not this copy, hand the run to it before anything the project provides (its+// astryx.config, integrations, or Core) is loaded. Returns only when this copy+// answers. See foundation/release/handoff.mjs and spec AST-081 FR2 and FR9.+const {startRun} = await importSrc('../../foundation/release/handoff.mjs');+await startRun({+ cliRoot: join(binDir, '..', '..', '..'),+ argv: process.argv.slice(2),+});+// Imports that transitively load `styleText` must happen AFTER the gate above,// so they are dynamically imported here rather than at the top of the module.-const {program, loadProjectDebugHandler, handleVersionJsonPreflight} =- await importSrc('index.mjs');+const {+ program,+ loadProjectDebugHandler,+ loadProjectForHelp,+ handleVersionJsonPreflight,+} = await importSrc('index.mjs');const {isJsonMode, toErrorEnvelope} = await importSrc('../../foundation/response/json.mjs');const {handleCommanderError} = await importSrc('lib/json-shim.mjs');const {setOutcome} = await importSrc('../../foundation/debug/index.mjs');@@ -107,6 +121,9 @@ process.on('uncaughtException', handleFatal);// Pick up the project's `debug` function before parsing, so parse errors and// `--help` — which short-circuit before any hook runs — are reported too.await loadProjectDebugHandler();+// Help prints its commands while Commander parses, so a help run reads the+// project's declared `cliCommand` here.+await loadProjectForHelp();// `--version --json` answers and exits without Commander, so it runs here —// after the handler exists, or the run would go unrecorded.diff --git a/packages/cli/clients/cli/cli-command.test.mjs b/packages/cli/clients/cli/cli-command.test.mjsnew file mode 100644index 0000000000..f14db5e699--- /dev/null+++ b/packages/cli/clients/cli/cli-command.test.mjs@@ -0,0 +1,166 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * Every printed command starts with the project's CLI command: the door a host+ * sets, or the `cliCommand` a loaded integration declares. JSON keeps commands+ * bare.+ */++import {afterEach, beforeEach, describe, expect, it} 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 {runCli} from '../../test-utils/run-cli.mjs';+import {+ hasRecordedProject,+ runWithCliDoor,+} from '../../foundation/env/cli-command.mjs';+import {getCliInvocation} from '../../foundation/env/package-manager.mjs';+import {loadProjectForHelp} from './index.mjs';++const BIN = path.resolve(import.meta.dirname, 'bin', 'astryx.mjs');++/** @type {string} */+let tmpDir;++beforeEach(() => {+ // Repo-local, so Vite permits importing the integration manifest.+ tmpDir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-cli-command-'));+});++afterEach(() => {+ fs.rmSync(tmpDir, {recursive: true, force: true});+});++/**+ * An app that installs one integration declaring `cliCommand`, with no+ * astryx.config: the integration is autolinked.+ * @param {string} cliCommand+ */+function appWithIntegration(cliCommand) {+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({name: 'app', dependencies: {'@acme/x': '1.0.0'}}),+ );+ fs.writeFileSync(path.join(tmpDir, 'AGENTS.md'), '<!-- ASTRYX:START -->\n');+ const pkg = path.join(tmpDir, 'node_modules', '@acme', 'x');+ fs.mkdirSync(pkg, {recursive: true});+ fs.writeFileSync(+ path.join(pkg, 'package.json'),+ JSON.stringify({name: '@acme/x', version: '1.0.0'}),+ );+ fs.writeFileSync(+ path.join(pkg, 'astryx.integration.mjs'),+ `export default ${JSON.stringify({cliCommand})};\n`,+ );+}++describe("an integration's cliCommand", () => {+ it('starts the hints of a command that never loads the project itself', async () => {+ appWithIntegration('acme astryx');+ const {status, stderr} = await runCli(['theme', 'remove', 'nope'], tmpDir);+ expect(status).toBe(1);+ expect(stderr).toContain('`acme astryx theme add nope`');+ });+});++describe('the setup nudge in a project with no CLI of its own', () => {+ it('names the declared cliCommand for the step after installing the CLI (spec AST-081 FR5)', async () => {+ // Outside this repository: the nudge stays quiet in the CLI's own checkout.+ const app = fs.mkdtempSync(+ path.join(os.tmpdir(), 'astryx-cli-command-nudge-'),+ );+ try {+ // Only Core, of another release than the CLI that answers, an+ // integration declaring cliCommand, and no agent docs yet.+ fs.writeFileSync(+ path.join(app, 'package.json'),+ JSON.stringify({+ name: 'app',+ dependencies: {'@acme/x': '1.0.0', '@astryxdesign/core': '0.0.1'},+ }),+ );+ fs.writeFileSync(path.join(app, 'package-lock.json'), '{}');+ for (const [name, version, extra] of [+ ['@acme/x', '1.0.0', 'acme astryx'],+ ['@astryxdesign/core', '0.0.1', null],+ ]) {+ const dir = path.join(app, 'node_modules', ...name.split('/'));+ fs.mkdirSync(dir, {recursive: true});+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ JSON.stringify({name, version}),+ );+ if (extra) {+ fs.writeFileSync(+ path.join(dir, 'astryx.integration.mjs'),+ `export default ${JSON.stringify({cliCommand: extra})};\n`,+ );+ }+ }++ const {stderr} = await runCli(['docs', 'tokens'], app);+ expect(stderr).toContain(+ 'Next step: run `npm install @astryxdesign/[email protected]`, then `acme astryx init`',+ );+ } finally {+ fs.rmSync(app, {recursive: true, force: true});+ }+ });+});++describe('help', () => {+ it('loads the project for a help run, and only for one', async () => {+ appWithIntegration('acme astryx');+ const cwd = process.cwd();+ process.chdir(tmpDir);+ try {+ await loadProjectForHelp(['docs', 'theme']);+ expect(hasRecordedProject(tmpDir)).toBe(false);+ await loadProjectForHelp(['component', '--help']);+ expect(getCliInvocation(tmpDir)).toBe('acme astryx');+ } finally {+ process.chdir(cwd);+ }+ });++ it("prints the integration's command in `--help`", () => {+ appWithIntegration('acme astryx');+ const result = spawnSync(process.execPath, [BIN, '--help'], {+ cwd: tmpDir,+ encoding: 'utf-8',+ });+ expect(result.status).toBe(0);+ expect(result.stdout).toContain('acme astryx search button');+ });+});++describe("a host's door", () => {+ it('prefixes doc commands in text and leaves them bare in JSON', async () => {+ const text = await runWithCliDoor('acme astryx', () =>+ runCli(['docs', 'getting-started', '--full']),+ );+ expect(text.stdout).toContain('acme astryx init');++ const json = await runWithCliDoor('acme astryx', () =>+ runCli(['docs', 'getting-started', '--json']),+ );+ expect(json.stdout).toContain('astryx init');+ expect(json.stdout).not.toContain('acme astryx');+ });++ it('prefixes suggested commands in text and leaves them bare in JSON', async () => {+ const text = await runWithCliDoor('acme astryx', () =>+ runCli(['search', '']),+ );+ expect(text.stderr).toContain('acme astryx search button');++ const json = await runWithCliDoor('acme astryx', () =>+ runCli(['search', '', '--json']),+ );+ expect(JSON.parse(json.stdout).suggestions[0].name).toBe(+ 'astryx search button',+ );+ });+});diff --git a/packages/cli/clients/cli/commands/blog.doc.mjs b/packages/cli/clients/cli/commands/blog.doc.mjsindex ab1e560f36..3190b9b69c 100644--- a/packages/cli/clients/cli/commands/blog.doc.mjs+++ b/packages/cli/clients/cli/commands/blog.doc.mjs@@ -24,6 +24,7 @@ export const doc = {{label: 'List posts', cli: 'astryx blog'},{label: 'Read one post', cli: 'astryx blog introducing-astryx --json'},],+ outsideProject: 'same',exitCodes: [{code: 0, when: 'success'},{code: 1, when: 'unknown slug, or the feed or a post cannot be fetched'},diff --git a/packages/cli/clients/cli/commands/build-theme.batch-report.test.mjs b/packages/cli/clients/cli/commands/build-theme.batch-report.test.mjsindex fd0b6356ed..67f4b302c9 100644--- a/packages/cli/clients/cli/commands/build-theme.batch-report.test.mjs+++ b/packages/cli/clients/cli/commands/build-theme.batch-report.test.mjs@@ -91,12 +91,24 @@ function count(text, pattern) {/** @param {string} stdout */function lines(stdout) {- return stdout.split('\n').filter(Boolean);+ return bareRecipe(stdout).split('\n').filter(Boolean);+}++/**+ * The font recipe names `docs typography` with the project's CLI invocation,+ * which depends on where the test runs; compare it as bare `astryx`.+ * @param {string} stdout+ */+function bareRecipe(stdout) {+ return stdout.replace(+ /(recipe: |guidance: )\S.*? docs typography/g,+ '$1astryx docs typography',+ );}/** @param {string} stdout The sizes follow Core's CSS, so goldens keep the shape. */function normalized(stdout) {- return stdout.replace(/\d+(\.\d+)? KB/g, '<size> KB');+ return bareRecipe(stdout).replace(/\d+(\.\d+)? KB/g, '<size> KB');}/** Bytes of the full report printed by one invocation per theme. */diff --git a/packages/cli/clients/cli/commands/build-theme.font-warning.test.mjs b/packages/cli/clients/cli/commands/build-theme.font-warning.test.mjsindex bed176ad7f..9b61b255f3 100644--- a/packages/cli/clients/cli/commands/build-theme.font-warning.test.mjs+++ b/packages/cli/clients/cli/commands/build-theme.font-warning.test.mjs@@ -75,7 +75,7 @@ describe('theme build font-loading warning', () => {expect(result.stdout).toContain('display=swap');expect(result.stdout).toContain('@font-face');expect(result.stdout).toContain('font-display: swap');- expect(result.stdout).toContain('astryx docs typography');+ expect(result.stdout).toContain(' docs typography');// The one-line summaries follow the CLI's stream contract. These are// NOTICES about a correct theme, not warnings, so they go to stdout with// the rest of the build's progress — stderr stays for the defects an@@ -105,8 +105,8 @@ describe('theme build font-loading warning', () => {);expect(result.code).toBe(0);- expect(result.stdout).toContain(- '[note] Fonts named but not loaded: "Space Grotesk", "JetBrains Mono". Load them in your app (recipe: astryx docs typography).\n',+ expect(result.stdout).toMatch(+ /\[note\] Fonts named but not loaded: "Space Grotesk", "JetBrains Mono"\. Load them in your app \(recipe: .+ docs typography\)\.\n/,);expect(result.stdout).not.toContain('fonts.googleapis.com');expect(result.stdout).not.toContain('@font-face');diff --git a/packages/cli/clients/cli/commands/build-theme.mjs b/packages/cli/clients/cli/commands/build-theme.mjsindex 6252d24a03..e9b59fcf70 100644--- a/packages/cli/clients/cli/commands/build-theme.mjs+++ b/packages/cli/clients/cli/commands/build-theme.mjs@@ -34,6 +34,7 @@ import * as path from 'node:path';import {fileURLToPath} from 'node:url';import {spawn} from 'node:child_process';import {getCliInvocation} from '../../../foundation/env/package-manager.mjs';+import {isOutsideProject} from '../../../foundation/env/project-scope.mjs';import {jsonOut} from '../../../foundation/response/json.mjs';import {emit,@@ -224,10 +225,13 @@ async function runThemeBuildWatch(entries, options) {emit(text(watchingLine));await new Promise((/** @type {(value?: void) => void} */ resolve) => {+ let stopping = false;/** @param {NodeJS.Signals} signal */const stop = async signal => {- process.removeListener('SIGINT', stop);- process.removeListener('SIGTERM', stop);+ // A second interrupt while stopping (a terminal's Ctrl-C and the same+ // signal passed on by the copy that started the run) changes nothing.+ if (stopping) return;+ stopping = true;stopped = true;queued.clear();for (const d of debounces.values()) clearTimeout(d);@@ -237,10 +241,12 @@ async function runThemeBuildWatch(entries, options) {rebuildChild?.kill(signal);await rebuildDone;emit(text('\nStopped watching.'));+ process.removeListener('SIGINT', stop);+ process.removeListener('SIGTERM', stop);resolve();};- process.once('SIGINT', stop);- process.once('SIGTERM', stop);+ process.on('SIGINT', stop);+ process.on('SIGTERM', stop);});}@@ -283,14 +289,24 @@ function printThemeAddList(themes) {return theme.description ? [head, theme.description] : head;}),),- text(- `Import one: ${run} theme add <slug> [--package <package>]\n` +- `Fork source: ${run} theme eject <slug> [target-path]`,- ),+ text(themeNextSteps(run)),more,);}+/**+ * What to do with a listed theme. Outside a project there is no app to add one+ * to, so only the fork step is named (spec AST-081 FR3).+ * @param {string} run the CLI invocation+ * @returns {string}+ */+function themeNextSteps(run) {+ const fork = `Fork source: ${run} theme eject <slug> [target-path]`;+ return isOutsideProject()+ ? fork+ : `Import one: ${run} theme add <slug> [--package <package>]\n${fork}`;+}+/*** Print every field in the `theme.list` entries. Duplicate slugs stay separate* because each record names its owner.@@ -325,10 +341,7 @@ function printThemeList(themes, unmigratedCopies = []) {default: (/** @type {boolean} */ value) => (value ? 'yes' : 'no'),},}),- text(- `Import one: ${run} theme add <slug> [--package <package>]\n` +- `Fork source: ${run} theme eject <slug> [target-path]`,- ),+ text(themeNextSteps(run)),more,);}diff --git a/packages/cli/clients/cli/commands/build.doc.mjs b/packages/cli/clients/cli/commands/build.doc.mjsindex ea29a13406..a534477ef1 100644--- a/packages/cli/clients/cli/commands/build.doc.mjs+++ b/packages/cli/clients/cli/commands/build.doc.mjs@@ -47,6 +47,7 @@ export const doc = {cli: 'astryx build "analytics dashboard" --json',},],+ outsideProject: 'same',exitCodes: [{code: 0, when: 'success (including zero matches)'},{diff --git a/packages/cli/clients/cli/commands/build.exit-codes-doc.test.mjs b/packages/cli/clients/cli/commands/build.exit-codes-doc.test.mjsindex e582bb2f47..9ad6983aa6 100644--- a/packages/cli/clients/cli/commands/build.exit-codes-doc.test.mjs+++ b/packages/cli/clients/cli/commands/build.exit-codes-doc.test.mjs@@ -11,6 +11,7 @@ import * as os from 'node:os';import * as path from 'node:path';import {runCli} from '../../../test-utils/run-cli.mjs';import {doc as buildDoc} from './build.doc.mjs';+import {linkThisCliAsProjectCli} from '../../../test-utils/release-fixtures.mjs';const SLOW = 30_000;@@ -20,6 +21,9 @@ let tmpDir;beforeEach(() => {tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-build-no-core-'));fs.writeFileSync(path.join(tmpDir, 'package.json'), JSON.stringify({name: 'consumer'}));+ // A project whose own CLI answers and that installs no Core: outside a+ // project a copy answers from the Core it carries instead (AST-081 FR3).+ linkThisCliAsProjectCli(tmpDir);});afterEach(() => {diff --git a/packages/cli/clients/cli/commands/component.doc.mjs b/packages/cli/clients/cli/commands/component.doc.mjsindex 1b70f4eec8..47db40075a 100644--- a/packages/cli/clients/cli/commands/component.doc.mjs+++ b/packages/cli/clients/cli/commands/component.doc.mjs@@ -90,6 +90,7 @@ export const doc = {cli: 'astryx component SideNav --package @astryxdesign/core',},],+ outsideProject: 'same',exitCodes: [{code: 0, when: 'success'},{diff --git a/packages/cli/clients/cli/commands/discover.broken-integration.test.mjs b/packages/cli/clients/cli/commands/discover.broken-integration.test.mjsindex 9d8103e524..582a2bd5bb 100644--- a/packages/cli/clients/cli/commands/discover.broken-integration.test.mjs+++ b/packages/cli/clients/cli/commands/discover.broken-integration.test.mjs@@ -68,8 +68,8 @@ describe('astryx discover with a manifest that fails to load', () => {const {status, stdout, stderr} = await runCli(['discover'], {cwd: project});expect(status).toBe(0);- expect(stderr).toContain(- 'Warning: @test/broken has 1 integration issue(s). Run: astryx doctor',+ expect(stderr).toMatch(+ /Warning: @test\/broken has 1 integration issue\(s\)\. Run: .+ doctor/,);expect(stdout).not.toContain('No integrations configured.');expect(stdout).toContain(@@ -87,6 +87,7 @@ describe('astryx discover with a manifest that fails to load', () => {expect(meta.configured).toBe(true);// The official list still answers; nothing else is claimed.expect(meta.sources.map(s => s.name)).toEqual(['Astryx']);+ expect(meta.answeredBy).toEqual(expect.any(Object));expect(stderr).not.toContain('integration issue');});});@@ -132,8 +133,8 @@ describe('astryx discover with a configured package that is not installed', () =const {status, stderr} = await runCli(['discover'], {cwd: project});expect(status).toBe(0);- expect(stderr).toContain(- 'Warning: @test/missing has 1 integration issue(s). Run: astryx doctor\n',+ expect(stderr).toMatch(+ /Warning: @test\/missing has 1 integration issue\(s\)\. Run: .+ doctor\n/,);});});@@ -151,8 +152,8 @@ describe('astryx search with a manifest that fails to load', () => {const {status, stderr} = await runCli(['search', 'button'], {cwd: project});expect(status).toBe(0);- expect(stderr).toContain(- 'Warning: @test/broken has 1 integration issue(s). Run: astryx doctor',+ expect(stderr).toMatch(+ /Warning: @test\/broken has 1 integration issue\(s\)\. Run: .+ doctor/,);const asJson = await runCli(['search', 'button', '--json'], {cwd: project});diff --git a/packages/cli/clients/cli/commands/discover.doc.mjs b/packages/cli/clients/cli/commands/discover.doc.mjsindex 8f1f61b4f5..e9c647c275 100644--- a/packages/cli/clients/cli/commands/discover.doc.mjs+++ b/packages/cli/clients/cli/commands/discover.doc.mjs@@ -18,6 +18,7 @@ export const doc = {'Browse and search integrations: the ones you have and the ones you could add',description:'Lists what this project has, the integrations it loads and the official packages it declares, then what it could add: the official Astryx packages first, then whatever its discover sources list, with what each one adds. ' ++ 'Inside a project, integrations installed for the computer, beside the CLI installed for it, are listed as ones the project could add, with its install command; outside one they load. ' +'A package query shows one package: what it adds, every version a source knows, and the command that adds it. ' +"An @scope/name/Component path prints an installed component's doc; any other item path shows that item. " +'Anything else, even an exact component name, searches every item and package and lists the matches. Discover only reads: your package manager installs, updates, and removes packages.',@@ -78,6 +79,7 @@ export const doc = {cli: 'astryx discover dashboard --type template --available',},],+ outsideProject: 'same',exitCodes: [{code: 0, when: 'success'},{@@ -86,4 +88,10 @@ export const doc = {},],related: ['component', 'search', 'template'],+ notes: [+ {+ type: 'prose',+ text: "In global mode: outside a project, integrations installed next to your global install are listed as installed and their items show up; inside a project, only the project's integrations are, and the global ones the project could add are listed under available, with the project's install command. In a project, the project's version of Astryx runs it, whichever astryx command you start. See {@link namespace:global} and {@link generic:computer-integrations}.",+ },+ ],};diff --git a/packages/cli/clients/cli/commands/discover.no-source.test.mjs b/packages/cli/clients/cli/commands/discover.no-source.test.mjsindex 1c92948837..b95f256515 100644--- a/packages/cli/clients/cli/commands/discover.no-source.test.mjs+++ b/packages/cli/clients/cli/commands/discover.no-source.test.mjs@@ -139,6 +139,7 @@ describe('astryx discover in a project with nothing of its own', () => {themes: ['neutral'],}),);+ expect(result.meta.answeredBy).toEqual(expect.any(Object));});it('answers every query with the list, and says why in text', async () => {diff --git a/packages/cli/clients/cli/commands/docs.doc.mjs b/packages/cli/clients/cli/commands/docs.doc.mjsindex cd16e1bf05..011ae8e159 100644--- a/packages/cli/clients/cli/commands/docs.doc.mjs+++ b/packages/cli/clients/cli/commands/docs.doc.mjs@@ -63,6 +63,7 @@ export const doc = {{label: 'One API function', cli: 'astryx docs cli/api/functions/search'},{label: 'A whole guide', cli: 'astryx docs cli/integrations/quick-start --full'},],+ outsideProject: 'same',exitCodes: [{code: 0, when: 'success'},{diff --git a/packages/cli/clients/cli/commands/docs.mjs b/packages/cli/clients/cli/commands/docs.mjsindex d7367809fd..6632a76030 100644--- a/packages/cli/clients/cli/commands/docs.mjs+++ b/packages/cli/clients/cli/commands/docs.mjs@@ -10,6 +10,9 @@* contract: a topic returns its whole doc, and `--index` its sections.* Supports --detail (full|compact|brief) and --lang (en|zh|dense). A code* block's label prints above its fence, and table cells escape their pipes.+ * Docs write commands as bare `astryx ...`; text output prefixes them with the+ * project's invocation (prefixCliCommands, in formatBlock and the summaries),+ * and JSON keeps them bare.** Usage:* astryx docs List available topics@@ -25,6 +28,7 @@import {formatCliCommand,getCliInvocation,+ prefixCliCommands,} from '../../../foundation/env/package-manager.mjs';import {jsonOut} from '../../../foundation/response/json.mjs';import {@@ -96,12 +100,17 @@ function formatTableCompact(headers, rows) {* @returns {string | null}*/export function formatBlock(block, detail) {+ // Docs write commands as bare `astryx ...`; show them the way this project+ // runs the CLI.+ const stem = getCliInvocation();+ /** @param {string} value */+ const shown = value => prefixCliCommands(value, stem);switch (block.type) {case 'prose':- return block.text;+ return shown(block.text);case 'heading':- return `${'#'.repeat(block.level || 3)} ${block.text}`;+ return `${'#'.repeat(block.level || 3)} ${shown(block.text)}`;case 'code':if (detail === 'compact' || detail === 'brief') return null;@@ -112,19 +121,29 @@ export function formatBlock(block, detail) {const label = block.label? `${block.label.replace(/:\s*$/, '')}:\n`: '';- return `${label}\`\`\`${block.lang}\n${block.code}\n\`\`\``;+ const body = prefixCliCommands(block.code, stem, block.lang);+ return `${label}\`\`\`${block.lang}\n${body}\n\`\`\``;}- case 'table':+ case 'table': {+ // A cell that is a whole command, such as `astryx theme add neutral`+ // written without backticks, is prefixed too.+ /** @param {string} cell */+ const shownCell = cell =>+ /^astryx(\s|$)/.test(cell ?? '')+ ? `${stem}${cell.slice('astryx'.length)}`+ : shown(cell ?? '');+ const rows = block.rows.map(row => row.map(shownCell));if (detail === 'brief') {- return block.rows+ return rows.map(r => r.slice(0, 2).map(tableCell).join('=')).join(' | ');}if (detail === 'compact') {- return formatTableCompact(block.headers, block.rows);+ return formatTableCompact(block.headers, rows);}- return formatTable(block.headers, block.rows);+ return formatTable(block.headers, rows);+ }case 'list': {const prefix =@@ -135,7 +154,9 @@ export function formatBlock(block, detail) {: block.style === 'do'? () => '+ ': () => '- ';- return block.items.map((item, i) => `${prefix(i)}${item}`).join('\n');+ return block.items+ .map((item, i) => `${prefix(i)}${shown(item)}`)+ .join('\n');}default:@@ -289,7 +310,7 @@ function formatTreeChild(child, detail, level, root, run, owner) {child.summary &&(child.kind === 'namespace' || child.kind === 'generic')) {- parts.push(child.summary);+ parts.push(prefixCliCommands(child.summary, run));}const content = formatTreeBlocks(child.content ?? [], detail, level - 2);if (content.length > 0) parts.push(content.join('\n\n'));@@ -341,7 +362,7 @@ function emitTree(node, detail, childDetail, run) {.every(route => route.startsWith(`${node.route}/`));const root = allBelow ? node.route : '';emit(- section(node.title, wrapText(node.summary)),+ section(node.title, wrapText(prefixCliCommands(node.summary, run))),record({package: node.package}),...(node.content?.length? [@@ -427,9 +448,12 @@ function emitIndex(index, owner, run) {// Summaries wrap rather than being cut: the summary is how a reader picks// the one section to open. A section another package wrote says which one.records(- index.sections.map(s =>- s.package === owner ? s : {...s, title: `${s.title} (${s.package})`},- ),+ index.sections.map(s => {+ const shown = {...s, summary: prefixCliCommands(s.summary ?? '', run)};+ return s.package === owner+ ? shown+ : {...shown, title: `${s.title} (${s.package})`};+ }),{fields: ['id', 'title', 'summary'],layout: 'inline',@@ -462,9 +486,10 @@ function childRow(child, owner) {return {// A child another package owns says which one.name: child.package === owner ? child.name : `${child.name} (${child.package})`,- summary: titleAddsIdentity- ? `${child.title}: ${child.summary}`- : child.summary,+ summary: prefixCliCommands(+ titleAddsIdentity ? `${child.title}: ${child.summary}` : child.summary,+ getCliInvocation(),+ ),};}@@ -479,14 +504,19 @@ function childRow(child, owner) {function emitNode(node, detail, run) {if (node.kind === 'namespace') {emit(- section(node.title, wrapText(node.summary)),+ section(node.title, wrapText(prefixCliCommands(node.summary, run))),record({package: node.package}),- // A namespace may author intro `blocks`; they render above its children.+ // A namespace may author intro `blocks`; they render above its children,+ // prose wrapped like the summary....(node.content?.length? [text(node.content- .map(b => formatBlock(b, detail))+ .map(b =>+ b.type === 'prose'+ ? wrapText(formatBlock(b, detail) ?? '')+ : formatBlock(b, detail),+ ).filter(Boolean).join('\n\n'),),diff --git a/packages/cli/clients/cli/commands/docs.test.mjs b/packages/cli/clients/cli/commands/docs.test.mjsindex d11180dd4a..3918bccf72 100644--- a/packages/cli/clients/cli/commands/docs.test.mjs+++ b/packages/cli/clients/cli/commands/docs.test.mjs@@ -113,7 +113,7 @@ describe('progressive reads', () => {expect(stdout).toMatch(/^principles +\S/m);expect(widest(stdout)).toBeLessThanOrEqual(120);// The repo root has no `astryx` bin, so the CLI names the scoped package.- expect(stdout).toMatch(/Usage: \S+(?: dlx)? (?:astryx|@astryxdesign\/cli) docs <topic>/);+ expect(stdout).toMatch(/Usage: \S+(?: dlx)? (?:astryx|@astryxdesign\/cli(?:@\S+)?) docs <topic>/);}, SLOW);it("prints a topic's section index with the keys to read by", async () => {@@ -255,7 +255,7 @@ describe('the docs tree, one level at a time', () => {const {status, stdout} = await runCli(['docs', 'cli/api/functions/search']);expect(status).toBe(0);expect(stdout).toMatch(/^## search\(\)/m);- expect(stdout).toContain('Read it with `astryx docs cli/commands/search`.');+ expect(stdout).toMatch(/Read it with `.+ docs cli\/commands\/search`\./);expect(stdout).toMatch(/Up: .*docs cli\/api\/functions$/m);}, SLOW);diff --git a/packages/cli/clients/cli/commands/doctor-integration-components.doc.mjs b/packages/cli/clients/cli/commands/doctor-integration-components.doc.mjsindex 2014c94c7b..6f28be4502 100644--- a/packages/cli/clients/cli/commands/doctor-integration-components.doc.mjs+++ b/packages/cli/clients/cli/commands/doctor-integration-components.doc.mjs@@ -49,6 +49,7 @@ export const doc = {cli: 'astryx doctor integration components @acme/widgets --json',},],+ outsideProject: 'same',exitCodes: [{code: 0,diff --git a/packages/cli/clients/cli/commands/doctor-integration-docs.doc.mjs b/packages/cli/clients/cli/commands/doctor-integration-docs.doc.mjsindex f80d570320..a51855da65 100644--- a/packages/cli/clients/cli/commands/doctor-integration-docs.doc.mjs+++ b/packages/cli/clients/cli/commands/doctor-integration-docs.doc.mjs@@ -39,6 +39,7 @@ export const doc = {cli: 'astryx doctor integration docs @acme/widgets --json',},],+ outsideProject: 'same',exitCodes: [{code: 0,diff --git a/packages/cli/clients/cli/commands/doctor-integration-templates.doc.mjs b/packages/cli/clients/cli/commands/doctor-integration-templates.doc.mjsindex 051a2c4d34..ac0423e75a 100644--- a/packages/cli/clients/cli/commands/doctor-integration-templates.doc.mjs+++ b/packages/cli/clients/cli/commands/doctor-integration-templates.doc.mjs@@ -37,6 +37,7 @@ export const doc = {cli: 'astryx doctor integration templates @acme/widgets --json',},],+ outsideProject: 'same',exitCodes: [{code: 0,diff --git a/packages/cli/clients/cli/commands/doctor-integration-validate.doc.mjs b/packages/cli/clients/cli/commands/doctor-integration-validate.doc.mjsindex 27a3d4b468..19e25a739f 100644--- a/packages/cli/clients/cli/commands/doctor-integration-validate.doc.mjs+++ b/packages/cli/clients/cli/commands/doctor-integration-validate.doc.mjs@@ -22,7 +22,9 @@ export const doc = {'warns about each field that does not match, naming the field and a fix. A doc ' +'it cannot fully check is listed with the reason, and test fixtures under ' +'`__tests__` in the components or docs root are counted, not checked. Without ' +- 'TypeScript it prints one line saying the docs were not type-checked.',+ 'TypeScript it prints one line saying the docs were not type-checked. ' ++ 'Outside a package, with no package name it writes nothing and reports one no_package issue (exit 1); ' ++ 'a package name is looked up as it is in a project.',fn: 'validateIntegration',args: [{@@ -43,6 +45,7 @@ export const doc = {cli: 'astryx doctor integration validate @acme/widgets --json',},],+ outsideProject: 'own',exitCodes: [{code: 0,@@ -51,4 +54,10 @@ export const doc = {{code: 1, when: 'one or more error-severity issues'},],related: ['doctor integration templates', 'template'],+ notes: [+ {+ type: 'prose',+ text: "In global mode: outside a package, with no package named, it writes nothing, reports one `no_package` issue, and exits 1; a package name is looked up as it is in a project. In a project, the project's version of Astryx runs it, whichever astryx command you start. See {@link namespace:global} and {@link generic:global-integrations}.",+ },+ ],};diff --git a/packages/cli/clients/cli/commands/doctor-integration.test.mjs b/packages/cli/clients/cli/commands/doctor-integration.test.mjsindex f03795bddf..0c1f7a8bf3 100644--- a/packages/cli/clients/cli/commands/doctor-integration.test.mjs+++ b/packages/cli/clients/cli/commands/doctor-integration.test.mjs@@ -19,7 +19,7 @@ import {Command} from 'commander';import {discoverCoreTemplates} from '../../../foundation/discovery/template-adapter.mjs';import {discoverOwnedComponents} from '../../../foundation/discovery/component-discovery.mjs';import {discoverBuiltinTopics} from '../../../foundation/discovery/docs-discovery.mjs';-import {findCoreDir} from '../../../foundation/fs/paths.mjs';+import {findCoreDir, findProjectCoreDir} from '../../../foundation/fs/paths.mjs';import {registerDoctor} from './doctor.mjs';import {expectRecordsCarry} from '../../../test-utils/text-projection.mjs';@@ -185,7 +185,7 @@ describe('doctor integration — command', () => {]);expect(logCalls.join('\n')).toContain(- 'astryx doctor integration templates <package>',+ ' doctor integration templates <package>',);expect(process.exitCode).toBeUndefined();});@@ -817,7 +817,8 @@ describe('doctor integration — command', () => {tmpDir = outside;try {writeComponentIntegration('AcmeCarousel');- expect(findCoreDir(outside)).toBeNull();+ // Doctor judges the project's own Core, never the one a copy carries.+ expect(findProjectCoreDir(outside)).toBeNull();process.chdir(outside);await createProgram().parseAsync([diff --git a/packages/cli/clients/cli/commands/doctor.doc.mjs b/packages/cli/clients/cli/commands/doctor.doc.mjsindex 495204829c..fba76c3418 100644--- a/packages/cli/clients/cli/commands/doctor.doc.mjs+++ b/packages/cli/clients/cli/commands/doctor.doc.mjs@@ -18,8 +18,11 @@ export const doc = {'Runs read-only project health diagnostics by default: Node version, @astryxdesign/core ' +'install and version alignment, theme packages, generated app themes when present, earlier copied-theme migration, config, integrations (every one astryx.config names must load, linked without a config entry, ' +'provider identity, contribution issues), agent docs, core peer dependencies, package manager, ' +- "and the docs the CLI reads. It writes nothing, but loading astryx.config runs that file's code. " +- 'The `integration` subcommands provide authoring checks for one integration package.',+ "the docs the CLI reads, the newest release the computer knows of, with the install and upgrade commands when the project's release is older, and every `astryx` command on the search path, warning when the first one is not the Astryx CLI or predates the hand-off. It writes nothing, but loading astryx.config runs that file's code. " ++ 'The `integration` subcommands provide authoring checks for one integration package. ' ++ 'Outside a project it checks the computer instead: the Node version, the release that answered, ' ++ 'the newest release this computer knows of, with the command that upgrades the CLI installed for the computer when it is older, the astryx commands on the search path, the integrations installed for the computer (warning about one it skips), and whether the computer-level agent text (`astryx init --user`) is present, matches this release, was edited, or is turned off (info only). ' ++ 'It never fails a check because the folder has no project.',fn: 'doctor',subcommands: ['integration'],examples: [@@ -42,9 +45,16 @@ export const doc = {cli: 'astryx doctor integration docs @acme/widgets',},],+ outsideProject: 'own',exitCodes: [{code: 0, when: 'no checks failed (warnings are allowed)'},{code: 1, when: 'one or more checks failed'},],related: ['init', 'upgrade'],+ notes: [+ {+ type: 'prose',+ text: "In global mode: outside a project, doctor checks your computer instead of a folder: `node-version`, `answering-release` (the version that answered), `newest-release`, `cli-on-path` (every astryx command on your PATH), `computer-integrations` (integrations installed globally), and `computer-agent-text` (the agent guide). It never fails a check because the folder has no project. In a project, the project's version of Astryx runs it, whichever astryx command you start. See {@link namespace:global} and {@link generic:who-answers}.",+ },+ ],};diff --git a/packages/cli/clients/cli/commands/doctor.mjs b/packages/cli/clients/cli/commands/doctor.mjsindex f93142bca9..ed595802e5 100644--- a/packages/cli/clients/cli/commands/doctor.mjs+++ b/packages/cli/clients/cli/commands/doctor.mjs@@ -38,6 +38,8 @@ import {doc as integrationDocConflictsFn} from '../../../api/integration/integraimport {NO_RESULT_SET} from '../../../foundation/debug/index.mjs';import {cliError} from '../lib/cli-error.mjs';import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';+import {formatCliCommand} from '../../../foundation/env/package-manager.mjs';+import {isOutsideProject} from '../../../foundation/env/project-scope.mjs';const STATUS = {pass: '[ok]',@@ -194,6 +196,9 @@ function printIntegrationValidation(data) {}),]: [text('[ok] No integration issues found.')]),+ ...(data.notes ?? []).map(note =>+ text(`note (${note.code}): ${note.message}`),+ ),text(`Summary: ${errors} error${errors === 1 ? '' : 's'}, ` +`${warnings} warning${warnings === 1 ? '' : 's'}`,@@ -541,7 +546,7 @@ async function runIntegrationValidation(program, pkg) {noPackage? 'Nothing was validated: no package.json found. Run this command inside a package directory.': 'Nothing was validated: no astryx.integration.* found next to package.json. ' +- 'To validate an installed integration: astryx doctor integration validate <package>',+ `To validate an installed integration: ${formatCliCommand('doctor integration validate <package>')}`,),);} else printIntegrationValidation(result.data);@@ -564,10 +569,14 @@ async function runAuthoringCheck(program, pkg, kind) {if (program.opts().json) jsonOut(result);else if (!result.data.validated) {+ // Outside a project no integration is installed to check by name+ // (spec AST-081 FR3).emit(text(- 'Nothing was checked: no astryx.integration.* found next to package.json. ' +- `To check an installed integration: astryx doctor integration ${kind} <package>`,+ isOutsideProject()+ ? 'Nothing was checked: no astryx.integration.* found next to package.json, and this folder is outside a project.'+ : 'Nothing was checked: no astryx.integration.* found next to package.json. ' ++ `To check an installed integration: ${formatCliCommand(`doctor integration ${kind} <package>`)}`,),);} else if (kind === 'templates') {diff --git a/packages/cli/clients/cli/commands/doctor.test.mjs b/packages/cli/clients/cli/commands/doctor.test.mjsindex 3f999c8e1d..6d7d795972 100644--- a/packages/cli/clients/cli/commands/doctor.test.mjs+++ b/packages/cli/clients/cli/commands/doctor.test.mjs@@ -20,6 +20,7 @@ import {checkPackageManager,} from '../../../api/doctor/doctor.mjs';import {MIN_NODE_VERSION} from '../../../foundation/env/node-version.mjs';+import {CLI_VERSION, linkThisCliAsProjectCli} from '../../../test-utils/release-fixtures.mjs';let tmpDir;let logCalls;@@ -101,7 +102,7 @@ describe('doctor — individual checks', () => {});it('app themes: reports unmanaged state as one INFO check', async () => {- fs.writeFileSync(path.join(tmpDir, 'package.json'), '{"name":"app"}\n');+ fs.writeFileSync(path.join(tmpDir, 'package.json'), '{"name":"app","dependencies":{"@astryxdesign/core":"*"}}\n');const result = await runChecks({cwd: tmpDir});const themeChecks = result.checks.filter(check =>check.id.startsWith('theme-'),@@ -176,13 +177,16 @@ describe('doctor — individual checks', () => {it('agent-docs: the fix names the scoped package when the project has no local CLI', () => {fs.writeFileSync(path.join(tmpDir, 'package-lock.json'), '{}');const res = checkAgentDocs({cwd: tmpDir});- expect(res.fix).toContain('`npx @astryxdesign/cli init --features agents`');+ expect(res.fix).toContain(+ `\`npx @astryxdesign/cli@${CLI_VERSION} init --features agents\``,+ );});it('agent-docs: the fix keeps `npx astryx` when the project has a local CLI', () => {fs.writeFileSync(path.join(tmpDir, 'package-lock.json'), '{}');fs.mkdirSync(path.join(tmpDir, 'node_modules', '.bin'), {recursive: true});fs.writeFileSync(path.join(tmpDir, 'node_modules', '.bin', 'astryx'), '');+ linkThisCliAsProjectCli(tmpDir);const res = checkAgentDocs({cwd: tmpDir});expect(res.fix).toContain('`npx astryx init --features agents`');});@@ -301,7 +305,8 @@ describe('doctor — runChecks / report', () => {expect(total).toBe(report.checks.length);});- it('reports a FAIL for core when run in a bare directory', async () => {+ it('reports a FAIL for core in a project that declares Core but installs none', async () => {+ fs.writeFileSync(path.join(tmpDir, 'package.json'), '{"name":"app","dependencies":{"@astryxdesign/core":"*"}}\n');const report = await runChecks({cwd: tmpDir});expect(find(report.checks, 'core-installed').status).toBe('fail');expect(report.summary.fail).toBeGreaterThan(0);@@ -346,7 +351,8 @@ describe('doctor — command', () => {process.exitCode = prevExit;});- it('sets exit code 1 when a check FAILs (bare dir, no @astryxdesign/core)', async () => {+ it('sets exit code 1 when a check FAILs (Core declared, not installed)', async () => {+ fs.writeFileSync(path.join(tmpDir, 'package.json'), '{"name":"app","dependencies":{"@astryxdesign/core":"*"}}\n');const prevCwd = process.cwd();const prevExit = process.exitCode;process.exitCode = undefined;diff --git a/packages/cli/clients/cli/commands/gap-report.doc.mjs b/packages/cli/clients/cli/commands/gap-report.doc.mjsindex adf4f2f2c0..7e947faf0f 100644--- a/packages/cli/clients/cli/commands/gap-report.doc.mjs+++ b/packages/cli/clients/cli/commands/gap-report.doc.mjs@@ -83,6 +83,7 @@ export const doc = {cli: "astryx gap-report Button --category missing_variant --reason 'Need a compact size' --to @acme/widgets",},],+ outsideProject: 'same',exitCodes: [{code: 0,diff --git a/packages/cli/clients/cli/commands/hook.doc.mjs b/packages/cli/clients/cli/commands/hook.doc.mjsindex 4013ee700a..f978d74740 100644--- a/packages/cli/clients/cli/commands/hook.doc.mjs+++ b/packages/cli/clients/cli/commands/hook.doc.mjs@@ -40,6 +40,7 @@ export const doc = {{label: 'Browse the catalog', cli: 'astryx hook --list'},{label: 'One hook as JSON', cli: 'astryx hook useFocusTrap --json'},],+ outsideProject: 'same',exitCodes: [{code: 0, when: 'success'},{diff --git a/packages/cli/clients/cli/commands/init.behavior.test.mjs b/packages/cli/clients/cli/commands/init.behavior.test.mjsindex 2df96d0a37..65302545e7 100644--- a/packages/cli/clients/cli/commands/init.behavior.test.mjs+++ b/packages/cli/clients/cli/commands/init.behavior.test.mjs@@ -39,6 +39,11 @@ const exists = rel => fs.existsSync(path.join(tmpDir, rel));describe('astryx init — default (no flags)', () => {it('installs the tool-agnostic AGENTS.md cheat sheet and prints next steps', async () => {+ // Inside a project; outside one the steps are left out (outside-project.test.mjs).+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ '{"name":"app","dependencies":{"@astryxdesign/core":"*"}}',+ );const {status, stdout} = await runCli(['init'], {cwd: tmpDir});expect(status).toBe(0);expect(exists('AGENTS.md')).toBe(true);diff --git a/packages/cli/clients/cli/commands/init.doc.mjs b/packages/cli/clients/cli/commands/init.doc.mjsindex 9facd85acf..62d104fea8 100644--- a/packages/cli/clients/cli/commands/init.doc.mjs+++ b/packages/cli/clients/cli/commands/init.doc.mjs@@ -19,7 +19,12 @@ export const doc = {'agents, and CI). By default it installs the AGENTS.md/CLAUDE.md agent-docs, ' +'including guidance from configured integrations, and prints getting-started ' +"steps. --features and --all print only the chosen features' guidance (no " +- 'getting-started steps); the theme feature also writes an annotated theme template.',+ 'getting-started steps); the theme feature also writes an annotated theme template. ' ++ 'Outside a project it writes the same files but prints no step that sets up a project: ' ++ 'no getting-started steps, and no step that adds a theme to an app. ' ++ '--user writes the computer-level agent text instead (see the flag), in any folder, and touches nothing in the folder. ' ++ 'The CLI installed for the computer also keeps that text current in the background, unless --user --remove-agents turned it off; ' ++ 'package install scripts, project setup, and upgrade never write it.',fn: 'init',options: [{@@ -43,6 +48,18 @@ export const doc = {"(deleting AGENTS.md or .claude/CLAUDE.md when only init's heading is left) and do nothing else. " +'--features, --all, --agent and --agent-docs-path are refused; a file written with --agent-docs-path keeps its block',},+ {+ flag: '--user',+ param: 'options.user',+ description:+ 'Write or refresh the computer-level agent text instead of setting up the folder: one skill file, ~/.agents/skills/astryx/SKILL.md, which most coding agents read, ' ++ 'linked into the skill folders of agents that read only their own (~/.claude/skills always; Kiro, Windsurf, Letta, Xcode\'s coding assistant, and ~/.config/agents/skills when that folder exists): a folder symlink with a relative target, a junction on Windows, or a copy where neither can be made. Continue, whose scanner skips links, gets a managed copy, refreshed with the file. ' ++ "It tells agents anywhere on the computer that Astryx is there, when it is relevant, and to start with `astryx search`. " ++ 'Records the links it made in astryx/settings.json in the per-user configuration folder, so removal removes exactly those; the CLI installed for the computer refreshes the file in the background after each upgrade. ' ++ 'Works in any folder. A file without the Astryx markers, one edited since Astryx wrote it, or a symlink, is kept as it is, and so is anything at a link target that Astryx did not create. ' ++ 'Warns, and still writes, when no `astryx` command on the computer runs the Astryx CLI. ' ++ 'With --remove-agents it removes the file, the links, and the copy instead and records that the text is turned off. --features, --all, --agent and --agent-docs-path are refused',+ },{flag: '--agent <tool>',param: 'options.agent',@@ -51,7 +68,7 @@ export const doc = {'Target AI tool for agent docs: claude (CLAUDE.md or .claude/CLAUDE.md, else creates .claude/CLAUDE.md), cursor (.cursorrules if present, else AGENTS.md), ' +'codex and muse (AGENTS.md), hermes (.hermes.md or HERMES.md if present, else AGENTS.md), all (every existing agent doc, else AGENTS.md and .claude/CLAUDE.md). ' +'An unknown tool exits 1 with ERR_UNKNOWN_AGENT. ' +- 'Used only when agent docs are installed (the default, --all, or --features agents); --agent-docs-path takes precedence',+ 'Used only when agent docs are installed (the default, --all, or --features agents); --agent-docs-path takes precedence.',},{flag: '--agent-docs-path <path...>',@@ -66,7 +83,10 @@ export const doc = {{label: 'Default setup', cli: 'astryx init'},{label: 'All features, no prompts', cli: 'astryx init --all'},{label: 'Machine-readable receipt', cli: 'astryx init --json'},+ {label: 'Agent text for the whole computer', cli: 'astryx init --user'},+ {label: 'Remove the computer-level agent text and turn it off', cli: 'astryx init --user --remove-agents'},],+ outsideProject: 'own',exitCodes: [{code: 0,@@ -74,8 +94,14 @@ export const doc = {},{code: 1,- when: 'an unknown --agent or feature, an --agent-docs-path outside the project, --remove-agents combined with install options, or --all with --features (ERR_INVALID_ARGUMENT)',+ when: 'an unknown --agent (ERR_UNKNOWN_AGENT) or feature, an --agent-docs-path outside the project, --remove-agents combined with install options, --user combined with --features, --all, --agent or --agent-docs-path, or --all with --features (ERR_INVALID_ARGUMENT)',},],related: ['doctor', 'upgrade', 'build', 'theme'],+ notes: [+ {+ type: 'prose',+ text: "In global mode: outside a project, init writes the agent docs (AGENTS.md) into the folder and prints no getting-started steps. `init --user` writes the agent guide for your computer, in any folder, and is never handed to a project's own CLI. In a project, the project's version of Astryx runs it, whichever astryx command you start. See {@link namespace:global} and {@link generic:computer-agent-guide}.",+ },+ ],};diff --git a/packages/cli/clients/cli/commands/integration-add.doc.mjs b/packages/cli/clients/cli/commands/integration-add.doc.mjsindex 3c06f38252..2738e1d91e 100644--- a/packages/cli/clients/cli/commands/integration-add.doc.mjs+++ b/packages/cli/clients/cli/commands/integration-add.doc.mjs@@ -113,6 +113,7 @@ export const doc = {cli: 'astryx integration add theme ocean --from neutral',},],+ outsideProject: 'refuse',exitCodes: [{code: 0, when: 'the contribution is written or the dry run succeeds'},{@@ -121,4 +122,10 @@ export const doc = {},],related: ['integration verify', 'doctor integration validate', 'theme add'],+ notes: [+ {+ type: 'prose',+ text: "In global mode: outside a package, integration add writes nothing and stops with `ERR_FILE_NOT_FOUND`: \"No package.json found. Run this command inside an integration package.\" In a project, the project's version of Astryx runs it, whichever astryx command you start. See {@link namespace:global} and {@link generic:global-integrations}.",+ },+ ],};diff --git a/packages/cli/clients/cli/commands/integration-authoring.test.mjs b/packages/cli/clients/cli/commands/integration-authoring.test.mjsindex 1d3b780774..8d63addcc4 100644--- a/packages/cli/clients/cli/commands/integration-authoring.test.mjs+++ b/packages/cli/clients/cli/commands/integration-authoring.test.mjs@@ -219,7 +219,7 @@ describe('integration authoring CLI', () => {expect(text.status).toBe(verifyText.status);expect(text.stdout).toBe(verifyText.stdout);expect(text.stderr).toContain('`integration pack --check` is deprecated');- expect(text.stderr).toContain('astryx integration verify');+ expect(text.stderr).toContain(' integration verify`');// Without --check it fails, as it did, and points only at the new name:// suggesting `--check` would send people to the deprecated spelling.const bare = await runCli(['integration', 'pack'], tmpDir);@@ -227,13 +227,13 @@ describe('integration authoring CLI', () => {expect(bare.stderr).toContain('`integration pack` is now `integration verify`',);- expect(bare.stderr).toContain('astryx integration verify');+ expect(bare.stderr).toContain(' integration verify`');expect(bare.stderr).toContain('npm pack');expect(bare.stderr).not.toContain('--check');const bareJson = await runCli(['--json', 'integration', 'pack'], tmpDir);expect(parseEnvelope(bareJson.stdout)).toMatchObject({code: 'ERR_INVALID_ARGUMENT',- error: expect.stringContaining('astryx integration verify'),+ error: expect.stringContaining(' integration verify`'),});// Help lists it, marked deprecated: nothing is hidden.const help = await runCli(['integration', '--help'], tmpDir);diff --git a/packages/cli/clients/cli/commands/integration-check.doc.mjs b/packages/cli/clients/cli/commands/integration-check.doc.mjsindex 1fc36f2491..1cee420f00 100644--- a/packages/cli/clients/cli/commands/integration-check.doc.mjs+++ b/packages/cli/clients/cli/commands/integration-check.doc.mjs@@ -35,14 +35,15 @@ export const doc = {'`integration check` on every build; run ' +'`integration verify` before you publish, to check that the packed package ' +'works in an app. To check an installed integration by name, run the ' +- '`doctor integration` subcommands with its package name.',+ '`doctor integration` subcommands with its package name. Outside a package, ' ++ 'it writes nothing, `validate` reports one `no_package` issue, and it exits 1.',fn: 'integrationCheck',options: [{flag: '--strict',param: 'options.strict',description:- 'Also exit 1 on any warning and on any check that did not run. A new check or failure code joins only in a minor release, named in the release notes.',+ 'Also exit 1 on any warning and on any check that did not run. A new check or failure code joins only in a minor release, named in the release notes; until then, a malformed `cliCommand` is reported as a note (`invalid_cli_command`) that fails nothing.',},],examples: [@@ -65,6 +66,7 @@ export const doc = {cli: 'integration verify',},],+ outsideProject: 'own',exitCodes: [{code: 0,@@ -82,4 +84,10 @@ export const doc = {'doctor integration templates','doctor integration docs',],+ notes: [+ {+ type: 'prose',+ text: "In global mode: outside a package, it writes nothing, its `validate` check reports one `no_package` issue, and it exits 1. In a project, the project's version of Astryx runs it, whichever astryx command you start. See {@link namespace:global} and {@link generic:global-integrations}.",+ },+ ],};diff --git a/packages/cli/clients/cli/commands/integration-check.test.mjs b/packages/cli/clients/cli/commands/integration-check.test.mjsindex e9e7022f4a..104c354dd1 100644--- a/packages/cli/clients/cli/commands/integration-check.test.mjs+++ b/packages/cli/clients/cli/commands/integration-check.test.mjs@@ -265,13 +265,43 @@ describe('astryx integration check', () => {'"typecheck": "tsc --noEmit && astryx integration check --strict"',);expect(run.stdout).toContain(- 'A new check or failure code joins only in a minor release, named in the release notes.',+ 'A new check or failure code joins only in a minor release, named in the release notes; until then, a malformed `cliCommand` is reported as a note (`invalid_cli_command`) that fails nothing.',);expect(run.stdout).toContain('integration verify');expect(run.stdout).toContain('against the package in the current folder');expect(run.stdout).not.toContain('[package]');});+ it('reports a malformed cliCommand as a note beside the issues, which --strict does not fail', async () => {+ // A unique template id, so nothing else warns.+ writePackage({+ id: 'acme-notes-only-fixture',+ extraManifest: ", cliCommand: ' acme astryx\\n'",+ });++ const json = await runCli(+ ['--json', 'integration', 'check', '--strict'],+ tmpDir,+ );+ const envelope = JSON.parse(json.stdout);+ const validate = envelope.data.checks[0].response.data;+ expect(validate.issues.map((/** @type {any} */ i) => i.code)).not.toContain(+ 'invalid_cli_command',+ );+ expect(validate.notes).toEqual([+ {code: 'invalid_cli_command', message: expect.any(String)},+ ]);+ expect(envelope.data.failed).toBe(false);+ expect(json.status).toBe(0);++ const text = await runCli(['integration', 'check'], tmpDir);+ expect(+ text.stdout+ .split('\n')+ .filter(line => line.startsWith('note (invalid_cli_command): ')),+ ).toHaveLength(1);+ });+it('takes no package name: one passed is an error, not a check of the current folder', async () => {writePackage({id: 'acme-page'});diff --git a/packages/cli/clients/cli/commands/integration-pack.doc.mjs b/packages/cli/clients/cli/commands/integration-pack.doc.mjsindex 022e57731a..2fe47038fd 100644--- a/packages/cli/clients/cli/commands/integration-pack.doc.mjs+++ b/packages/cli/clients/cli/commands/integration-pack.doc.mjs@@ -8,7 +8,7 @@ export const doc = {namespace: 'cli/commands',summary: 'Deprecated: the old name of `integration verify`',description:- '`astryx integration pack --check` is the name this check had before {@link command:integration verify}. It still runs the same check, with the same output, JSON, and exit codes, and prints a note that names `integration verify`. It will be removed in a later release.',+ '`astryx integration pack --check` is the name this check had before {@link command:integration verify}. It still runs the same check, with the same output, JSON, and exit codes, and prints a note that names `integration verify`. It will be removed in a later release. Outside a package it writes nothing and reports one failed check, no_package, naming the integration package it needs (exit 1).',fn: 'integrationPackCheck',options: [{@@ -19,6 +19,7 @@ export const doc = {examples: [{label: 'The old spelling', cli: 'astryx integration pack --check'},],+ outsideProject: 'own',exitCodes: [{code: 0, when: 'the packed package exposes the same valid contributions'},{@@ -27,4 +28,10 @@ export const doc = {},],related: ['integration verify'],+ notes: [+ {+ type: 'prose',+ text: "In global mode: outside a package, `integration pack --check` writes nothing, reports one failed check, `no_package`, and exits 1. In a project, the project's version of Astryx runs it, whichever astryx command you start. See {@link namespace:global} and {@link generic:global-integrations}.",+ },+ ],};diff --git a/packages/cli/clients/cli/commands/integration-verify.doc.mjs b/packages/cli/clients/cli/commands/integration-verify.doc.mjsindex 71080d04cd..c177463edf 100644--- a/packages/cli/clients/cli/commands/integration-verify.doc.mjs+++ b/packages/cli/clients/cli/commands/integration-verify.doc.mjs@@ -8,15 +8,22 @@ export const doc = {namespace: 'cli/commands',summary: 'Check the package the way npm will publish it, before you publish',description:- 'Packs the package with npm, unpacks the tarball into a temporary app without installing its dependencies, and checks that the app sees the same components, templates, themes, docs, and codemods as the package, that every public import resolves, and that the package declares a CLI new enough to read it. It publishes nothing and leaves no tarball behind. It runs the package\'s own pack lifecycle scripts, as `npm pack` does.',+ 'Packs the package with npm, unpacks the tarball into a temporary app without installing its dependencies, and checks that the app sees the same components, templates, themes, docs, and codemods as the package, that every public import resolves, and that the package declares a CLI new enough to read it. It publishes nothing and leaves no tarball behind. It runs the package\'s own pack lifecycle scripts, as `npm pack` does. Outside a package it writes nothing and reports one failed check, no_package, naming the integration package it needs (exit 1).',fn: 'integrationPackCheck',examples: [{label: 'Check before publishing', cli: 'astryx integration verify'},{label: 'Machine-readable result', cli: 'astryx integration verify --json'},],+ outsideProject: 'own',exitCodes: [{code: 0, when: 'the packed package exposes the same valid contributions'},{code: 1, when: 'the tarball is incomplete or invalid'},],related: ['integration add', 'doctor integration validate'],+ notes: [+ {+ type: 'prose',+ text: "In global mode: outside a package, it writes nothing, reports one failed check, `no_package`, and exits 1. In a project, the project's version of Astryx runs it, whichever astryx command you start. See {@link namespace:global} and {@link generic:global-integrations}.",+ },+ ],};diff --git a/packages/cli/clients/cli/commands/integration.mjs b/packages/cli/clients/cli/commands/integration.mjsindex d2ef87e705..4d04fb1771 100644--- a/packages/cli/clients/cli/commands/integration.mjs+++ b/packages/cli/clients/cli/commands/integration.mjs@@ -20,6 +20,7 @@ import {doc as integrationAddFn} from '../../../api/integration/integrationAdd.dimport {doc as integrationCheckFn} from '../../../api/integration/integrationCheck.doc.mjs';import {printIntegrationCheckResponse} from './doctor.mjs';import {doc as integrationPackCheckFn} from '../../../api/integration/integrationPackCheck.doc.mjs';+import {formatCliCommand} from '../../../foundation/env/package-manager.mjs';/*** @param {import('commander').Command} command@@ -283,14 +284,14 @@ export function registerIntegration(program) {if (!options.check) {// One way forward: the new name. `npm pack` is what builds a tarball.return cliError(- '`integration pack` is now `integration verify`: run `astryx integration verify` to check the package the way npm will publish it. To build the tarball, run `npm pack`.',+ `\`integration pack\` is now \`integration verify\`: run \`${formatCliCommand('integration verify')}\` to check the package the way npm will publish it. To build the tarball, run \`npm pack\`.`,{code: ERROR_CODES.ERR_INVALID_ARGUMENT},);}// stderr, and only in text: JSON callers get the same envelope as verify.if (!program.opts().json) {console.error(- 'Note: `integration pack --check` is deprecated. Run `astryx integration verify`: it runs the same check.',+ `Note: \`integration pack --check\` is deprecated. Run \`${formatCliCommand('integration verify')}\`: it runs the same check.`,);}return verifyPackage(program);diff --git a/packages/cli/clients/cli/commands/json-contract.test.mjs b/packages/cli/clients/cli/commands/json-contract.test.mjsindex 22ae37cc36..40dc3d099d 100644--- a/packages/cli/clients/cli/commands/json-contract.test.mjs+++ b/packages/cli/clients/cli/commands/json-contract.test.mjs@@ -148,6 +148,7 @@ describe('--json contract: supported commands emit valid envelopes', () => {expect(parsed.meta.sources).toEqual([expect.objectContaining({name: 'Astryx', status: 'fresh'}),]);+ expect(parsed.meta.answeredBy).toEqual(expect.any(Object));});it('astryx template --json emits a typed envelope', async () => {@@ -166,7 +167,11 @@ describe('--json contract: supported commands emit valid envelopes', () => {});it('astryx doctor --json emits a doctor envelope with checks + summary', async () => {- // Run in a bare tmp dir → @astryxdesign/core won't resolve → a FAIL → exit 1.+ // A project that declares @astryxdesign/core but installs none → a FAIL → exit 1.+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ '{"name":"app","dependencies":{"@astryxdesign/core":"*"}}',+ );const {status, stdout} = await runCli(['doctor', '--json'], {cwd: tmpDir});expect(status).toBe(1);const parsed = parseJson(stdout);diff --git a/packages/cli/clients/cli/commands/manifest.doc.mjs b/packages/cli/clients/cli/commands/manifest.doc.mjsindex 0b29bf13ac..5db7b93b4a 100644--- a/packages/cli/clients/cli/commands/manifest.doc.mjs+++ b/packages/cli/clients/cli/commands/manifest.doc.mjs@@ -22,6 +22,7 @@ export const doc = {{label: 'Full manifest', cli: 'astryx manifest --json'},{label: 'The same manifest, under data.manifest (type "help")', cli: 'astryx --json'},],+ outsideProject: 'same',exitCodes: [{code: 0, when: 'success'},{code: 1, when: 'the manifest cannot be generated'},diff --git a/packages/cli/clients/cli/commands/outside-project.test.mjs b/packages/cli/clients/cli/commands/outside-project.test.mjsnew file mode 100644index 0000000000..ca7e4fc30d--- /dev/null+++ b/packages/cli/clients/cli/commands/outside-project.test.mjs@@ -0,0 +1,774 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file What every command does outside a project (spec AST-081 FR3, FR4).+ *+ * 1. Declarations: every command and subcommand doc declares `outsideProject`+ * (`same`, `refuse`, or `own`), a group that only holds subcommands+ * declares nothing, and `astryx manifest` publishes each value.+ * 2. Behavior: each command's examples run in an empty folder, outside any+ * project, where the repository's Core is the Core this release carries.+ * - `same`: the run matches the same example in a new project that+ * installs only this release's Core: exit status, envelope type or error+ * code, and the files written.+ * - `refuse`: the run writes nothing and fails with ERR_PROJECT_REQUIRED, or+ * with the code its released versions refuse with (listed below).+ * - `own`: each has a test of its own in this file.+ * 3. Advice: outside a project, no output names a step that only works inside+ * one.+ */++import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {fileURLToPath, pathToFileURL} from 'node:url';+import {afterAll, afterEach, beforeAll, describe, expect, it, vi} from 'vitest';+import {program, JSON_SUPPORTED} from '../index.mjs';+import {buildManifest} from '../lib/manifest.mjs';+import {runCli} from '../../../test-utils/run-cli.mjs';+import {+ checkAnsweringRelease,+ checkComputerAgentText,+ checkNewestRelease,+} from '../../../api/doctor/doctor.mjs';++const HERE = path.dirname(fileURLToPath(import.meta.url));+const CLI_ROOT = path.resolve(HERE, '../../..');+const CORE_ROOT = path.resolve(CLI_ROOT, '../core');+const VERSION = JSON.parse(+ fs.readFileSync(path.join(CLI_ROOT, 'package.json'), 'utf-8'),+).version;+const SLOW = 60_000;++/**+ * The code each `refuse` command's released versions refuse with outside a+ * project. Every other `refuse` command fails with ERR_PROJECT_REQUIRED.+ * @type {Record<string, string>}+ */+const RELEASED_REFUSAL_CODES = {+ swizzle: 'ERR_CORE_NOT_FOUND',+ 'integration add': 'ERR_FILE_NOT_FOUND',+ 'theme use': 'ERR_THEME_INVALID',+ 'theme remove': 'ERR_THEME_INVALID',+};++/** Every `own` command; each has a describe block below. */+const OWN_TESTED = new Set([+ 'doctor',+ 'doctor integration validate',+ 'init',+ 'integration check',+ 'integration verify',+ 'integration pack',+ 'theme add',+ 'upgrade',+]);++/** @returns {Promise<any[]>} every command doc the CLI ships */+async function loadCommandDocs() {+ const docs = [];+ for (const name of fs.readdirSync(HERE)) {+ if (!name.endsWith('.doc.mjs')) continue;+ const {doc} = await import(pathToFileURL(path.join(HERE, name)).href);+ if (doc?.type === 'command') docs.push(doc);+ }+ return docs.sort((a, b) => a.name.localeCompare(b.name));+}++const commandDocs = await loadCommandDocs();+const byName = new Map(commandDocs.map(doc => [doc.name, doc]));++/** A doc that only groups subcommands: it has subcommands and wraps no function. */+function isGroup(doc) {+ return (doc.subcommands?.length ?? 0) > 0 && doc.fn == null;+}++/** Split an example's command line the way a shell would, quotes included. */+function splitArgs(line) {+ const out = [];+ let current = '';+ let quote = null;+ let started = false;+ for (const ch of line) {+ if (quote) {+ if (ch === quote) quote = null;+ else current += ch;+ } else if (ch === '"' || ch === "'") {+ quote = ch;+ started = true;+ } else if (/\s/.test(ch)) {+ if (current || started) out.push(current);+ current = '';+ started = false;+ } else {+ current += ch;+ }+ }+ if (current || started) out.push(current);+ return out;+}++/** The command an argument list runs: its longest name prefix with a doc. */+function invokedCommand(args) {+ const words = args.filter(arg => !arg.startsWith('-'));+ for (let n = words.length; n > 0; n--) {+ const name = words.slice(0, n).join(' ');+ if (byName.has(name) && args.join(' ').includes(name))+ return byName.get(name);+ }+ return byName.get('manifest');+}++/** Every example in every doc, keyed by the command it runs. */+const examples = commandDocs.flatMap(doc =>+ (doc.examples ?? []).map(example => {+ const args = splitArgs(example.cli).slice(1);+ return {+ cli: example.cli,+ args: args.includes('--json') ? args : ['--json', ...args],+ command: invokedCommand(args),+ };+ }),+);++/** @type {string[]} */+const tmpDirs = [];+function tmpDir(label) {+ const dir = fs.mkdtempSync(+ path.join(os.tmpdir(), `astryx-outside-${label}-`),+ );+ tmpDirs.push(dir);+ return dir;+}++/** A new project that installs only this release's Core. */+function newProject() {+ const dir = tmpDir('project');+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ JSON.stringify({+ name: 'new-app',+ private: true,+ dependencies: {'@astryxdesign/core': VERSION},+ }),+ );+ fs.mkdirSync(path.join(dir, 'node_modules', '@astryxdesign'), {+ recursive: true,+ });+ fs.symlinkSync(+ CORE_ROOT,+ path.join(dir, 'node_modules', '@astryxdesign', 'core'),+ 'dir',+ );+ return dir;+}++/** Files under `dir`, relative, skipping node_modules. */+function filesIn(dir, root = dir) {+ /** @type {string[]} */+ const out = [];+ for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {+ const file = path.join(dir, entry.name);+ if (entry.isDirectory() && entry.name !== 'node_modules') {+ out.push(...filesIn(file, root));+ } else if (entry.isFile()) {+ out.push(path.relative(root, file));+ }+ }+ return out.sort();+}++/** What a run answered: exit status, envelope type or error code, files written. */+async function answer(args, dir) {+ const before = new Set(filesIn(dir));+ const r = await runCli(args, dir);+ let envelope = null;+ try {+ envelope = JSON.parse(r.stdout);+ } catch {+ // Compared as unparsed below.+ }+ return {+ status: r.status,+ kind: envelope ? (envelope.code ?? envelope.type ?? null) : 'not json',+ written: filesIn(dir).filter(file => !before.has(file)),+ envelope,+ stdout: r.stdout,+ stderr: r.stderr,+ };+}++// No run reaches the network: a fetch fails the same way in both folders.+const realFetch = globalThis.fetch;+beforeAll(() => {+ globalThis.fetch = async () => {+ throw new TypeError('fetch failed');+ };+});+afterAll(() => {+ globalThis.fetch = realFetch;+});+afterEach(() => {+ while (tmpDirs.length) {+ fs.rmSync(/** @type {string} */ (tmpDirs.pop()), {+ recursive: true,+ force: true,+ });+ }+});++describe('outsideProject declarations', () => {+ it.each(commandDocs.map(doc => [doc.name, doc]))(+ '%s declares a value, unless it only groups subcommands',+ (_name, doc) => {+ if (isGroup(doc)) expect(doc.outsideProject).toBeUndefined();+ else expect(['same', 'refuse', 'own']).toContain(doc.outsideProject);+ },+ );++ it('astryx manifest publishes each command doc value', () => {+ const manifest = buildManifest(program, {jsonSupported: JSON_SUPPORTED});+ const flat = [];+ const walk = cmds => {+ for (const cmd of cmds) {+ flat.push(cmd);+ walk(cmd.subcommands ?? []);+ }+ };+ walk(manifest.commands);+ expect(flat.length).toBeGreaterThan(0);+ for (const cmd of flat) {+ const doc = byName.get(cmd.name);+ expect(doc, `${cmd.name} has a command doc`).toBeDefined();+ expect(cmd.outsideProject, cmd.name).toBe(doc.outsideProject);+ }+ });++ it('names every refusal code a released version uses only for a refuse command', () => {+ for (const name of Object.keys(RELEASED_REFUSAL_CODES)) {+ expect(byName.get(name)?.outsideProject, name).toBe('refuse');+ }+ });++ it('gives every own command a test of its own', () => {+ const own = commandDocs+ .filter(doc => doc.outsideProject === 'own')+ .map(doc => doc.name);+ expect(new Set(own)).toEqual(OWN_TESTED);+ });+});++describe('every example in an empty folder matches its declaration', () => {+ const cases = examples.filter(e => e.command.outsideProject !== 'own');++ it.each(cases.map(e => [e.cli, e]))(+ '%s',+ async (_cli, example) => {+ const {command, args} = example;+ const empty = await answer(args, tmpDir('empty'));+ if (command.outsideProject === 'refuse') {+ expect(empty.status).not.toBe(0);+ expect(empty.written).toEqual([]);+ expect(empty.kind).toBe(+ RELEASED_REFUSAL_CODES[command.name] ?? 'ERR_PROJECT_REQUIRED',+ );+ return;+ }+ const project = await answer(args, newProject());+ expect(+ {status: empty.status, kind: empty.kind, written: empty.written},+ `${example.cli}\n${empty.stdout}`,+ ).toEqual({+ status: project.status,+ kind: project.kind,+ written: project.written,+ });+ },+ SLOW,+ );+});++describe('doctor outside a project (own)', () => {+ it(+ 'checks the computer and never fails because the folder has no project',+ async () => {+ const dir = tmpDir('doctor');+ const r = await answer(['--json', 'doctor'], dir);+ expect(r.status).toBe(0);+ expect(r.written).toEqual([]);+ const checks = r.envelope.data.checks;+ expect(checks.map(c => c.id)).toEqual([+ 'node-version',+ 'answering-release',+ 'newest-release',+ 'cli-on-path',+ 'computer-integrations',+ 'computer-agent-text',+ ]);+ expect(checks.every(c => c.status !== 'fail')).toBe(true);+ expect(checks[1].message).toContain(`CLI ${VERSION}`);+ },+ SLOW,+ );++ it(+ 'treats a package.json that declares no Astryx package as outside a project',+ async () => {+ const dir = tmpDir('doctor-pkg');+ fs.writeFileSync(path.join(dir, 'package.json'), '{"name":"x"}');+ const r = await answer(['--json', 'doctor'], dir);+ expect(r.status).toBe(0);+ expect(r.envelope.data.checks.map(c => c.id)).not.toContain(+ 'core-installed',+ );+ },+ SLOW,+ );++ it(+ 'runs the project checks inside a project, unchanged',+ async () => {+ const r = await answer(['--json', 'doctor'], newProject());+ const ids = r.envelope.data.checks.map(c => c.id);+ expect(ids).toContain('core-installed');+ expect(ids).not.toContain('answering-release');+ expect(ids).not.toContain('computer-agent-text');+ const newest = r.envelope.data.checks.find(+ c => c.id === 'newest-release',+ );+ expect(newest.status).toBe('info');+ },+ SLOW,+ );++ it('names the release that answered and the Core it reads', () => {+ expect(+ checkAnsweringRelease({+ nodeVersion: '22.13.0',+ answeredBy: {cli: '1.2.0', core: '1.2.0', copy: 'carried'},+ latest: null,+ }),+ ).toMatchObject({+ status: 'pass',+ message: expect.stringContaining('CLI 1.2.0 with Core 1.2.0'),+ });+ expect(+ checkAnsweringRelease({+ nodeVersion: '22.13.0',+ answeredBy: {cli: '1.2.0', core: null, copy: 'carried'},+ latest: null,+ }),+ ).toMatchObject({status: 'info'});+ });++ it('reports the newest release it knows of, as info only', () => {+ const at = latest =>+ checkNewestRelease({+ nodeVersion: '22.13.0',+ answeredBy: {cli: '1.2.0', core: '1.2.0', copy: 'carried'},+ latest,+ });+ expect(at(null).message).toBe(+ 'Update check: not run yet, so the newest release is not known here; it runs in the background once a day, after a command.',+ );+ expect(at('1.3.0').message).toContain('1.3.0 is newer than 1.2.0');+ expect(at('1.2.0').message).toContain('No newer release is known');+ for (const latest of [null, '1.3.0', '1.2.0', '1.1.0']) {+ expect(at(latest).status).toBe('info');+ expect(at(latest).fix).toBeUndefined();+ }+ });+});++describe('doctor: the computer-level agent text', () => {+ const at = agentText =>+ checkComputerAgentText({+ nodeVersion: '22.13.0',+ answeredBy: {cli: '1.2.0', core: '1.2.0', copy: 'carried'},+ latest: null,+ agentText,+ cwd: os.tmpdir(),+ });+ const A = '/home/me/.agents/skills/astryx/SKILL.md';+ const C = '/home/me/.claude/skills/astryx';++ it('present and current, linked: no fix', () => {+ const check = at([+ {path: A, state: 'current'},+ {path: C, state: 'linked', link: true},+ ]);+ expect(check).toMatchObject({id: 'computer-agent-text', status: 'info'});+ expect(check.message).toContain('matches this release');+ expect(check.message).toContain(`Linked into: ${C}`);+ expect(check.fix).toBeUndefined();+ });++ it('a different file, or a link not made yet: fix with init --user', () => {+ for (const [file, link] of [+ ['differs', 'linked'],+ ['current', 'absent'],+ ]) {+ const check = at([+ {path: A, state: file},+ {path: C, state: link, link: true},+ ]);+ expect(check.status).toBe('info');+ expect(check.fix).toMatch(/init --user`\.$/);+ }+ });++ it('names a link target it skipped because Astryx did not create what is there', () => {+ const check = at([+ {path: A, state: 'current'},+ {path: C, state: 'foreign', link: true},+ ]);+ expect(check.message).toContain(+ `Not linked, because something Astryx did not create is there: ${C}`,+ );+ });++ it('flags a link whose skill folder is missing, with the fix', () => {+ const check = at([+ {path: A, state: 'current'},+ {path: C, state: 'dangling', link: true},+ ]);+ expect(check.message).toContain(+ `the skill folder the link points to is not there`,+ );+ expect(check.message).toContain(C);+ expect(check.fix).toMatch(/init --user`\.$/);+ });++ it('absent: fix with init --user; a file Astryx did not write: left as it is', () => {+ const check = at([+ {path: A, state: 'absent'},+ {path: C, state: 'absent', link: true},+ ]);+ expect(check.message).toContain('No computer-level agent text');+ expect(check.fix).toMatch(/init --user`\.$/);+ expect(+ at([+ {path: A, state: 'foreign'},+ {path: C, state: 'absent', link: true},+ ]).message,+ ).toContain(`${A} was not written by Astryx, so it is left as it is`);+ });++ it(+ 'reads the home folder: absent, then current after init --user',+ async () => {+ const home = tmpDir('home');+ vi.stubEnv('HOME', home);+ vi.stubEnv('USERPROFILE', home);+ try {+ const find = r =>+ r.envelope.data.checks.find(c => c.id === 'computer-agent-text');+ const before = find(await answer(['--json', 'doctor'], tmpDir('doc')));+ expect(before.message).toContain('No computer-level agent text');+ expect(before.status).toBe('info');+ await runCli(['--json', 'init', '--user'], tmpDir('user'));+ const after = find(await answer(['--json', 'doctor'], tmpDir('doc2')));+ expect(after.message).toContain('matches this release');+ expect(after.fix).toBeUndefined();+ } finally {+ vi.unstubAllEnvs();+ }+ },+ SLOW,+ );+});++describe('doctor integration validate outside a package (own)', () => {+ it(+ 'writes nothing and reports one no_package issue',+ async () => {+ const r = await answer(+ ['--json', 'doctor', 'integration', 'validate'],+ tmpDir('validate'),+ );+ expect(r.status).toBe(1);+ expect(r.written).toEqual([]);+ expect(r.envelope.data.issues.map(i => i.code)).toEqual(['no_package']);+ },+ SLOW,+ );++ it(+ 'looks a package name up as in a project',+ async () => {+ const empty = await answer(+ ['--json', 'doctor', 'integration', 'validate', '@acme/widgets'],+ tmpDir('validate-pkg'),+ );+ const project = await answer(+ ['--json', 'doctor', 'integration', 'validate', '@acme/widgets'],+ newProject(),+ );+ expect(empty.status).toBe(project.status);+ expect(empty.envelope.data.issues.map(i => i.code)).toEqual(+ project.envelope.data.issues.map(i => i.code),+ );+ },+ SLOW,+ );+});++describe('integration check outside a package (own)', () => {+ it(+ 'writes nothing, reports one no_package issue from validate, and exits 1',+ async () => {+ const r = await answer(+ ['--json', 'integration', 'check'],+ tmpDir('check'),+ );+ expect(r.status).toBe(1);+ expect(r.written).toEqual([]);+ expect(r.envelope.type).toBe('integration.check');+ expect(r.envelope.data.failed).toBe(true);+ const validate = r.envelope.data.checks.find(c => c.check === 'validate');+ expect(validate.response.data.issues.map(i => i.code)).toEqual([+ 'no_package',+ ]);+ },+ SLOW,+ );+});++describe('init outside a project (own)', () => {+ it(+ 'writes the agent docs and prints no getting-started steps',+ async () => {+ const dir = tmpDir('init');+ const json = await answer(['--json', 'init'], dir);+ expect(json.status).toBe(0);+ expect(json.written).toEqual(['AGENTS.md']);+ expect(json.envelope.data.nextSteps).toBe(false);+ const text = await runCli(['init'], tmpDir('init-text'));+ expect(text.stdout).not.toContain('Next steps');+ expect(text.stdout).not.toContain('npm install');+ },+ SLOW,+ );++ it(+ 'names no step that adds a theme to an app',+ async () => {+ const r = await runCli(['init', '--all'], tmpDir('init-all'));+ expect(r.status).toBe(0);+ expect(r.stdout).not.toContain('theme add');+ expect(r.stdout).toContain('theme eject');+ },+ SLOW,+ );++ it(+ '--user writes only the computer-level agent text and its link, in the home folder',+ async () => {+ const home = tmpDir('home');+ vi.stubEnv('HOME', home);+ vi.stubEnv('USERPROFILE', home);+ try {+ const r = await answer(+ ['--json', 'init', '--user'],+ tmpDir('init-user'),+ );+ expect(r.status).toBe(0);+ expect(r.written).toEqual([]);+ expect(r.envelope.type).toBe('init.user');+ // The per-user cache and settings may also live under this home+ // folder.+ expect(+ filesIn(home).filter(+ f => !f.startsWith('.cache') && !f.startsWith('.config'),+ ),+ ).toEqual([path.join('.agents', 'skills', 'astryx', 'SKILL.md')]);+ // Claude Code's folder is a link to it.+ expect(+ fs+ .lstatSync(path.join(home, '.claude', 'skills', 'astryx'))+ .isSymbolicLink(),+ ).toBe(true);+ } finally {+ vi.unstubAllEnvs();+ }+ },+ SLOW,+ );++ it(+ 'prints the getting-started steps inside a project',+ async () => {+ const r = await answer(['--json', 'init'], newProject());+ expect(r.envelope.data.nextSteps).toBe(true);+ },+ SLOW,+ );+});++describe.each([+ ['integration verify', ['integration', 'verify']],+ ['integration pack', ['integration', 'pack', '--check']],+])('%s outside a package (own)', (_name, args) => {+ it(+ 'writes nothing and reports one failed check, no_package',+ async () => {+ const r = await answer(['--json', ...args], tmpDir('verify'));+ expect(r.status).toBe(1);+ expect(r.written).toEqual([]);+ expect(r.envelope.type).toBe('integration.pack-check');+ expect(r.envelope.data.issues.map(i => i.code)).toEqual(['no_package']);+ },+ SLOW,+ );+});++describe('theme add outside a project (own)', () => {+ it(+ 'lists the available themes with no slug, as in a new project',+ async () => {+ const empty = await answer(+ ['--json', 'theme', 'add'],+ tmpDir('theme-add'),+ );+ const project = await answer(['--json', 'theme', 'add'], newProject());+ expect(empty.status).toBe(0);+ expect(empty.envelope.type).toBe('theme.list');+ expect(empty.envelope.data.map(t => t.slug)).toEqual(+ project.envelope.data.map(t => t.slug),+ );+ },+ SLOW,+ );++ it(+ 'writes nothing and names the app project it needs, given a slug',+ async () => {+ const r = await answer(+ ['--json', 'theme', 'add', 'butter'],+ tmpDir('theme-add-slug'),+ );+ expect(r.status).toBe(1);+ expect(r.written).toEqual([]);+ expect(r.kind).toBe('ERR_THEME_INVALID');+ expect(r.envelope.error).toContain('app project');+ },+ SLOW,+ );+});++describe('upgrade outside a project (own)', () => {+ it(+ 'lists the codemods this release ships',+ async () => {+ const r = await answer(+ ['--json', 'upgrade', '--list'],+ tmpDir('upgrade-list'),+ );+ expect(r.status).toBe(0);+ expect(r.envelope.type).toBe('upgrade.list');+ },+ SLOW,+ );++ it(+ 'finds no copied compositions to update',+ async () => {+ const r = await answer(+ ['--json', 'upgrade', '--registry', '--apply'],+ tmpDir('upgrade-reg'),+ );+ expect(r.status).toBe(0);+ expect(r.written).toEqual([]);+ },+ SLOW,+ );++ it(+ 'writes nothing and fails a migration with ERR_VERSION_DETECT, naming no install step',+ async () => {+ const r = await answer(+ ['--json', 'upgrade', '--from', '0.1.0', '--apply'],+ tmpDir('upgrade-from'),+ );+ expect(r.status).toBe(1);+ expect(r.written).toEqual([]);+ expect(r.kind).toBe('ERR_VERSION_DETECT');+ expect(r.envelope.error).toContain('outside a project');+ expect(r.envelope.error).not.toMatch(/install the target/i);+ },+ SLOW,+ );+});++describe('no advice that works only inside a project', () => {+ it(+ 'prints no setup reminder in a package.json that declares no Astryx package',+ async () => {+ const dir = tmpDir('nudge');+ fs.writeFileSync(path.join(dir, 'package.json'), '{"name":"x"}');+ const r = await runCli(['docs', 'tokens'], dir);+ expect(r.stderr).not.toMatch(/finish setup/);+ },+ SLOW,+ );++ it(+ 'theme list names no step that adds a theme to an app',+ async () => {+ const r = await runCli(['theme', 'list'], tmpDir('theme-list'));+ expect(r.status).toBe(0);+ expect(r.stdout).not.toContain('theme add');+ expect(r.stdout).toContain('theme eject');+ },+ SLOW,+ );++ it(+ 'a theme search result forks the source instead of adding the theme',+ async () => {+ const r = await answer(+ ['--json', 'search', 'warm', '--type', 'theme'],+ tmpDir('search'),+ );+ const themes = r.envelope.data.results.filter(x => x.domain === 'theme');+ expect(themes.length).toBeGreaterThan(0);+ for (const theme of themes) {+ expect(theme.command).toBe(`astryx theme eject ${theme.name}`);+ }+ const inside = await answer(+ ['--json', 'search', 'warm', '--type', 'theme'],+ newProject(),+ );+ for (const theme of inside.envelope.data.results.filter(+ x => x.domain === 'theme',+ )) {+ expect(theme.command).toBe(`astryx theme add ${theme.name}`);+ }+ },+ SLOW,+ );++ it(+ 'discover names no config step',+ async () => {+ const r = await runCli(['discover'], tmpDir('discover'));+ expect(r.stdout).not.toContain('astryx.config');+ },+ SLOW,+ );++ it(+ 'the integration checks name no installed-integration step',+ async () => {+ for (const kind of ['templates', 'components', 'docs']) {+ const r = await runCli(+ ['doctor', 'integration', kind],+ tmpDir('authoring'),+ );+ expect(r.stdout).toContain('Nothing was checked');+ expect(r.stdout).not.toContain('To check an installed integration');+ }+ },+ SLOW,+ );+});diff --git a/packages/cli/clients/cli/commands/search.doc.mjs b/packages/cli/clients/cli/commands/search.doc.mjsindex 91408a86cf..938d859012 100644--- a/packages/cli/clients/cli/commands/search.doc.mjs+++ b/packages/cli/clients/cli/commands/search.doc.mjs@@ -51,6 +51,7 @@ export const doc = {},{label: 'Themes you can add', cli: 'astryx search warm --type theme'},],+ outsideProject: 'same',exitCodes: [{code: 0, when: 'success (including zero matches)'},{diff --git a/packages/cli/clients/cli/commands/search.mjs b/packages/cli/clients/cli/commands/search.mjsindex 383e328c68..e71711d5a5 100644--- a/packages/cli/clients/cli/commands/search.mjs+++ b/packages/cli/clients/cli/commands/search.mjs@@ -32,7 +32,6 @@ import {cliError} from '../lib/cli-error.mjs';import {defineCommand} from '../lib/define-command.mjs';import {search as searchApi} from '../../../api/search/search.mjs';import {Project} from '../../../foundation/config/project.mjs';-import {findCoreDir} from '../../../foundation/fs/paths.mjs';import {warnOnIntegrationIssues} from '../../../foundation/integrations/integration-warnings.mjs';import {doc as searchCommand} from './search.doc.mjs';import {doc as searchFn} from '../../../api/search/search.doc.mjs';@@ -104,16 +103,22 @@ export function registerSearch(program) {// ── Text output ──────────────────────────────────────────────const run = getCliInvocation();const {query: q, matchCount, results} = result.data;- // Outside an app an open search covers the docs and themes alone. Say- // so, so that list does not read as "Astryx has no such component".- const note =- !options.type && !findCoreDir(process.cwd())- ? [- text(- '@astryxdesign/core is not installed here, so only the docs and themes were searched.',- ),- ]- : [];+ // When Core could not be had, an open search covers the rest alone. Say+ // so, on standard error and in the output, so the list does not read as+ // "Astryx has no such component".+ const partial = result.meta?.partial;+ if (partial) {+ console.error(+ `astryx: components, hooks, and templates were not searched: ${partial.reason}`,+ );+ }+ const note = partial+ ? [+ text(+ 'Components, hooks, and templates need @astryxdesign/core, which could not be found (see the line above), so only the docs and themes were searched.',+ ),+ ]+ : [];// No matches is a valid, successful outcome — clean message, exit 0.if (results.length === 0) {diff --git a/packages/cli/clients/cli/commands/search.test.mjs b/packages/cli/clients/cli/commands/search.test.mjsindex 2818537062..a2083ecf44 100644--- a/packages/cli/clients/cli/commands/search.test.mjs+++ b/packages/cli/clients/cli/commands/search.test.mjs@@ -15,8 +15,13 @@ import * as fs from 'node:fs';import * as os from 'node:os';import * as path from 'node:path';import {fileURLToPath} from 'node:url';-import {search, scoreCandidate, SEARCH_DOMAINS} from '../../../api/search/search.mjs';+import {+ search,+ scoreCandidate,+ SEARCH_DOMAINS,+} from '../../../api/search/search.mjs';import {runCli} from '../../../test-utils/run-cli.mjs';+import {linkThisCliAsProjectCli} from '../../../test-utils/release-fixtures.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));// Run against the monorepo root so @astryxdesign/core is discoverable.@@ -58,123 +63,147 @@ function printsField(lines, key, value) {// `astryx` bin is installed), so compare the part after `astryx`.const text = asText(value).split('\n')[0].trimEnd();const shown = text.replace(/^astryx /, '');- return lines.some(line => line.startsWith(`${key}:`) && line.trimEnd().endsWith(shown));+ return lines.some(+ line => line.startsWith(`${key}:`) && line.trimEnd().endsWith(shown),+ );}-describe('search() API — ranking', () => {- it('ranks an exact component name match first', async () => {- const {data} = await search('button', OPTS);- expect(data.results.length).toBeGreaterThan(0);- const top = data.results[0];- expect(top.domain).toBe('component');- expect(top.name).toBe('Button');- expect(top.score).toBe(100);- expect(top.command).toBe('astryx component Button');- });-- it('returns components/hooks tagged with a matching keyword', async () => {- const {data} = await search('button', OPTS);- // IconButton carries the "button" keyword; should be present and scored- // on a keyword (not name) signal.- const iconButton = data.results.find(r => r.name === 'IconButton');- expect(iconButton).toBeTruthy();- expect(iconButton.domain).toBe('component');- expect(iconButton.score).toBeGreaterThanOrEqual(70);- expect(iconButton.reason.toLowerCase()).toContain('keyword');- });-}, SCAN_TIMEOUT);--describe('search() API — cross-domain', () => {- it('returns results from more than one domain for a broad query', async () => {- const {data} = await search('color', OPTS);- const domains = new Set(data.results.map(r => r.domain));- // "color" is a doc topic AND appears across components.- expect(domains.has('doc')).toBe(true);- expect(domains.size).toBeGreaterThan(1);- // The doc topic should carry a follow-up `astryx docs` command.- const docHit = data.results.find(r => r.domain === 'doc');- expect(docHit.command.startsWith('astryx docs ')).toBe(true);- });-- it('every result is tagged with a known domain and a command', async () => {- const {data} = await search('button', OPTS);- for (const r of data.results) {- expect(SEARCH_DOMAINS).toContain(r.domain);- expect(typeof r.command).toBe('string');- expect(r.command.length).toBeGreaterThan(0);- }- });-}, SCAN_TIMEOUT);--describe('search() API — filters', () => {- it('--type component returns only components', async () => {- const {data} = await search('modal', {...OPTS, type: 'component'});- expect(data.results.length).toBeGreaterThan(0);- for (const r of data.results) {- expect(r.domain).toBe('component');- }- });-- it('--type doc returns only docs', async () => {- const {data} = await search('color', {...OPTS, type: 'doc'});- for (const r of data.results) {- expect(r.domain).toBe('doc');- }- });-- it('--type theme returns only themes, each with the command that adds it', async () => {- const {data} = await search('warm', {...OPTS, type: 'theme'});- expect(data.results.map(r => r.name)).toContain('neutral');- for (const r of data.results) {- expect(r.domain).toBe('theme');- expect(r.command).toBe(`astryx theme add ${r.name}`);- }- });-- it('respects --limit', async () => {- const {data} = await search('button', {...OPTS, limit: 3});- expect(data.results.length).toBeLessThanOrEqual(3);- });-- it('rejects an unknown --type', async () => {- await expect(search('x', {...OPTS, type: 'bogus'})).rejects.toThrow(/Unknown --type/);- });-}, SCAN_TIMEOUT);--describe('search() API — fuzzy / typo tolerance', () => {- it('finds Button for the typo "buton"', async () => {- const {data} = await search('buton', OPTS);- const button = data.results.find(r => r.name === 'Button');- expect(button).toBeTruthy();- expect(button.domain).toBe('component');- });-}, SCAN_TIMEOUT);--describe('search() API — empty + envelope', () => {- it('returns an empty result set (not an error) for a no-match query', async () => {- const {type, data} = await search('zzqqxx_definitely_no_match', OPTS);- expect(type).toBe('search');- expect(data.results).toEqual([]);- expect(data.query).toBe('zzqqxx_definitely_no_match');- });-- it('throws when the query is empty', async () => {- await expect(search('', OPTS)).rejects.toThrow(/query is required/);- });+describe(+ 'search() API — ranking',+ () => {+ it('ranks an exact component name match first', async () => {+ const {data} = await search('button', OPTS);+ expect(data.results.length).toBeGreaterThan(0);+ const top = data.results[0];+ expect(top.domain).toBe('component');+ expect(top.name).toBe('Button');+ expect(top.score).toBe(100);+ expect(top.command).toBe('astryx component Button');+ });++ it('returns components/hooks tagged with a matching keyword', async () => {+ const {data} = await search('button', OPTS);+ // IconButton carries the "button" keyword; should be present and scored+ // on a keyword (not name) signal.+ const iconButton = data.results.find(r => r.name === 'IconButton');+ expect(iconButton).toBeTruthy();+ expect(iconButton.domain).toBe('component');+ expect(iconButton.score).toBeGreaterThanOrEqual(70);+ expect(iconButton.reason.toLowerCase()).toContain('keyword');+ });+ },+ SCAN_TIMEOUT,+);++describe(+ 'search() API — cross-domain',+ () => {+ it('returns results from more than one domain for a broad query', async () => {+ const {data} = await search('color', OPTS);+ const domains = new Set(data.results.map(r => r.domain));+ // "color" is a doc topic AND appears across components.+ expect(domains.has('doc')).toBe(true);+ expect(domains.size).toBeGreaterThan(1);+ // The doc topic should carry a follow-up `astryx docs` command.+ const docHit = data.results.find(r => r.domain === 'doc');+ expect(docHit.command.startsWith('astryx docs ')).toBe(true);+ });++ it('every result is tagged with a known domain and a command', async () => {+ const {data} = await search('button', OPTS);+ for (const r of data.results) {+ expect(SEARCH_DOMAINS).toContain(r.domain);+ expect(typeof r.command).toBe('string');+ expect(r.command.length).toBeGreaterThan(0);+ }+ });+ },+ SCAN_TIMEOUT,+);++describe(+ 'search() API — filters',+ () => {+ it('--type component returns only components', async () => {+ const {data} = await search('modal', {...OPTS, type: 'component'});+ expect(data.results.length).toBeGreaterThan(0);+ for (const r of data.results) {+ expect(r.domain).toBe('component');+ }+ });- it('returns the correct envelope shape', async () => {- const result = await search('button', OPTS);- expect(result.type).toBe('search');- expect(result.data).toHaveProperty('query');- expect(Array.isArray(result.data.results)).toBe(true);- const top = result.data.results[0];- expect(top).toHaveProperty('domain');- expect(top).toHaveProperty('name');- expect(top).toHaveProperty('score');- expect(top).toHaveProperty('description');- expect(top).toHaveProperty('command');- });-}, SCAN_TIMEOUT);+ it('--type doc returns only docs', async () => {+ const {data} = await search('color', {...OPTS, type: 'doc'});+ for (const r of data.results) {+ expect(r.domain).toBe('doc');+ }+ });++ it('--type theme returns only themes, each with the command that adds it', async () => {+ const {data} = await search('warm', {...OPTS, type: 'theme'});+ expect(data.results.map(r => r.name)).toContain('neutral');+ for (const r of data.results) {+ expect(r.domain).toBe('theme');+ expect(r.command).toBe(`astryx theme add ${r.name}`);+ }+ });++ it('respects --limit', async () => {+ const {data} = await search('button', {...OPTS, limit: 3});+ expect(data.results.length).toBeLessThanOrEqual(3);+ });++ it('rejects an unknown --type', async () => {+ await expect(search('x', {...OPTS, type: 'bogus'})).rejects.toThrow(+ /Unknown --type/,+ );+ });+ },+ SCAN_TIMEOUT,+);++describe(+ 'search() API — fuzzy / typo tolerance',+ () => {+ it('finds Button for the typo "buton"', async () => {+ const {data} = await search('buton', OPTS);+ const button = data.results.find(r => r.name === 'Button');+ expect(button).toBeTruthy();+ expect(button.domain).toBe('component');+ });+ },+ SCAN_TIMEOUT,+);++describe(+ 'search() API — empty + envelope',+ () => {+ it('returns an empty result set (not an error) for a no-match query', async () => {+ const {type, data} = await search('zzqqxx_definitely_no_match', OPTS);+ expect(type).toBe('search');+ expect(data.results).toEqual([]);+ expect(data.query).toBe('zzqqxx_definitely_no_match');+ });++ it('throws when the query is empty', async () => {+ await expect(search('', OPTS)).rejects.toThrow(/query is required/);+ });++ it('returns the correct envelope shape', async () => {+ const result = await search('button', OPTS);+ expect(result.type).toBe('search');+ expect(result.data).toHaveProperty('query');+ expect(Array.isArray(result.data.results)).toBe(true);+ const top = result.data.results[0];+ expect(top).toHaveProperty('domain');+ expect(top).toHaveProperty('name');+ expect(top).toHaveProperty('score');+ expect(top).toHaveProperty('description');+ expect(top).toHaveProperty('command');+ });+ },+ SCAN_TIMEOUT,+);describe('scoreCandidate()', () => {it('scores an exact name match at 100', () => {@@ -183,199 +212,303 @@ describe('scoreCandidate()', () => {it('scores an exact keyword above a description mention', () => {const kw = scoreCandidate('toggle', {name: 'Switch', keywords: ['toggle']});- const desc = scoreCandidate('toggle', {name: 'Switch', description: 'A toggle control'});+ const desc = scoreCandidate('toggle', {+ name: 'Switch',+ description: 'A toggle control',+ });expect(kw.score).toBeGreaterThan(desc.score);});it('returns null when nothing matches', () => {- expect(scoreCandidate('zzzz', {name: 'Button', keywords: ['cta']})).toBeNull();+ expect(+ scoreCandidate('zzzz', {name: 'Button', keywords: ['cta']}),+ ).toBeNull();});});-describe('search CLI — exit codes + JSON contract', () => {- it('exits 0 for a successful search', async () => {- const r = await runCli(['search', 'button'], REPO_ROOT);- expect(r.status).toBe(0);- });-- it('exits 0 for a no-match query (valid empty result, not failure)', async () => {- const r = await runCli(['search', 'zzqqxx_no_match'], REPO_ROOT);- expect(r.status).toBe(0);- expect(r.stdout).toContain('No results');- });-- it('takes every word after `search` as one query', async () => {- // Commander took only the first word, so `search dark mode` searched for- // "dark" and dropped "mode" without a word.- const json = await runCli(['--json', 'search', 'dark', 'mode', '--type', 'doc'], REPO_ROOT);- expect(json.status).toBe(0);- const env = JSON.parse(json.stdout);- expect(env.data.query).toBe('dark mode');- // theme topic-level and section tie; either is correct- const top = env.data.results[0];- expect(top.name === 'theme' || top.name === 'use-a-theme' || top.section === 'light-dark-mode').toBe(true);- const text = await runCli(['search', 'dark', 'mode', '--type', 'doc'], REPO_ROOT);- expect(text.stdout).toContain('Results for "dark mode"');- }, SCAN_TIMEOUT);-- it('exits 1 for an invalid --type', async () => {- const r = await runCli(['search', 'x', '--type', 'bogus'], REPO_ROOT);- expect(r.status).toBe(1);- });-- it('exits 1 for an invalid --limit', async () => {- const r = await runCli(['search', 'x', '--limit', '0'], REPO_ROOT);- expect(r.status).toBe(1);- });-- it.each(['1.5', '5abc'])(- 'refuses --limit %s like search({limit}) does, in both modes',- async value => {- await expect(- search('x', {...OPTS, limit: Number(value)}),- ).rejects.toMatchObject({code: 'ERR_INVALID_ARGUMENT'});- const json = await runCli(['--json', 'search', 'x', '--limit', value], REPO_ROOT);- expect(json.status).toBe(1);- expect(JSON.parse(json.stdout)).toMatchObject({code: 'ERR_INVALID_ARGUMENT'});- const text = await runCli(['search', 'x', '--limit', value], REPO_ROOT);- expect(text.status).toBe(1);- },- );-- it('emits a valid --json envelope', async () => {- const r = await runCli(['--json', 'search', 'button'], REPO_ROOT);- expect(r.status).toBe(0);- const parsed = JSON.parse(r.stdout);- expect(parsed.apiVersion).toBe(1);- expect(parsed.type).toBe('search');- expect(parsed.data.query).toBe('button');- expect(Array.isArray(parsed.data.results)).toBe(true);- expect(parsed.data.matchCount).toBeGreaterThanOrEqual(- parsed.data.results.length,- );- expect(parsed.data.results[0].name).toBe('Button');- });-- it('says how many matched when --limit cut the list short', async () => {- // The text view is a projection of the JSON, and the JSON now carries the- // match total. A bare "(2)" heading over a capped list reads as "that is- // all Astryx has", which is the conclusion `search` exists to prevent.- const capped = await runCli(- ['search', 'button', '--type', 'component', '--limit', '2'],- REPO_ROOT,+describe(+ 'search CLI — exit codes + JSON contract',+ () => {+ it('exits 0 for a successful search', async () => {+ const r = await runCli(['search', 'button'], REPO_ROOT);+ expect(r.status).toBe(0);+ });++ it('exits 0 for a no-match query (valid empty result, not failure)', async () => {+ const r = await runCli(['search', 'zzqqxx_no_match'], REPO_ROOT);+ expect(r.status).toBe(0);+ expect(r.stdout).toContain('No results');+ });++ it(+ 'takes every word after `search` as one query',+ async () => {+ // Commander took only the first word, so `search dark mode` searched for+ // "dark" and dropped "mode" without a word.+ const json = await runCli(+ ['--json', 'search', 'dark', 'mode', '--type', 'doc'],+ REPO_ROOT,+ );+ expect(json.status).toBe(0);+ const env = JSON.parse(json.stdout);+ expect(env.data.query).toBe('dark mode');+ // theme topic-level and section tie; either is correct+ const top = env.data.results[0];+ expect(+ top.name === 'theme' ||+ top.name === 'use-a-theme' ||+ top.section === 'light-dark-mode',+ ).toBe(true);+ const text = await runCli(+ ['search', 'dark', 'mode', '--type', 'doc'],+ REPO_ROOT,+ );+ expect(text.stdout).toContain('Results for "dark mode"');+ },+ SCAN_TIMEOUT,);- expect(capped.status).toBe(0);- expect(capped.stdout).toMatch(/^Results for "button" \(2 of \d+\)$/m);- const uncapped = await runCli(- ['search', 'button', '--type', 'component', '--limit', '500'],- REPO_ROOT,+ it('exits 1 for an invalid --type', async () => {+ const r = await runCli(['search', 'x', '--type', 'bogus'], REPO_ROOT);+ expect(r.status).toBe(1);+ });++ it('exits 1 for an invalid --limit', async () => {+ const r = await runCli(['search', 'x', '--limit', '0'], REPO_ROOT);+ expect(r.status).toBe(1);+ });++ it.each(['1.5', '5abc'])(+ 'refuses --limit %s like search({limit}) does, in both modes',+ async value => {+ await expect(+ search('x', {...OPTS, limit: Number(value)}),+ ).rejects.toMatchObject({code: 'ERR_INVALID_ARGUMENT'});+ const json = await runCli(+ ['--json', 'search', 'x', '--limit', value],+ REPO_ROOT,+ );+ expect(json.status).toBe(1);+ expect(JSON.parse(json.stdout)).toMatchObject({+ code: 'ERR_INVALID_ARGUMENT',+ });+ const text = await runCli(['search', 'x', '--limit', value], REPO_ROOT);+ expect(text.status).toBe(1);+ },);- expect(uncapped.stdout).toMatch(/^Results for "button" \(\d+\)$/m);- expect(uncapped.stdout).not.toMatch(/Results for "button" \(\d+ of/);- });- it('emits a valid --json envelope with empty results for no match', async () => {- const r = await runCli(['--json', 'search', 'zzqqxx_no_match'], REPO_ROOT);- expect(r.status).toBe(0);- const parsed = JSON.parse(r.stdout);- expect(parsed.type).toBe('search');- expect(parsed.data.results).toEqual([]);- expect(parsed.data.matchCount).toBe(0);- });-- it('renders each result as a greppable key: value record', async () => {- const r = await runCli(['search', 'button'], REPO_ROOT);- expect(r.stdout).toMatch(/^command:\s+\S.*(?:astryx|@astryxdesign\/cli) component Button$/m);- // Fields mirror the JSON object and are line-greppable.- expect(r.stdout).toMatch(/^name:\s+Button$/m);- expect(r.stdout).toMatch(/^domain:\s+component$/m);- expect(r.stdout).toContain('description:');- });-- it('prints every result field under its JSON key (score and reason with --verbose)', async () => {- // Between them these reach every domain, so every per-domain field shows.- // A theme matches `theme` only through its description, a prose mention- // ranked below every name and keyword hit, so the theme domain comes from- // a theme's own name.- const domains = new Set();- for (const args of [- ['search', 'theme', '--limit', '60'],- ['search', 'neutral', '--type', 'theme'],- ]) {- const env = JSON.parse((await runCli(['--json', ...args], REPO_ROOT)).stdout);- const plain = (await runCli(args, REPO_ROOT)).stdout.split('\n');- const verbose = (await runCli([...args, '--verbose'], REPO_ROOT)).stdout.split('\n');- for (const result of env.data.results) {- domains.add(result.domain);- for (const [key, value] of Object.entries(result)) {- if (value == null || value === '') continue;- const label = `${result.domain} ${result.name}: ${key}`;- expect(printsField(verbose, key, value), label).toBe(true);- if (key !== 'score' && key !== 'reason') {- expect(printsField(plain, key, value), label).toBe(true);+ it('emits a valid --json envelope', async () => {+ const r = await runCli(['--json', 'search', 'button'], REPO_ROOT);+ expect(r.status).toBe(0);+ const parsed = JSON.parse(r.stdout);+ expect(parsed.apiVersion).toBe(1);+ expect(parsed.type).toBe('search');+ expect(parsed.data.query).toBe('button');+ expect(Array.isArray(parsed.data.results)).toBe(true);+ expect(parsed.data.matchCount).toBeGreaterThanOrEqual(+ parsed.data.results.length,+ );+ expect(parsed.data.results[0].name).toBe('Button');+ });++ it('says how many matched when --limit cut the list short', async () => {+ // The text view is a projection of the JSON, and the JSON now carries the+ // match total. A bare "(2)" heading over a capped list reads as "that is+ // all Astryx has", which is the conclusion `search` exists to prevent.+ const capped = await runCli(+ ['search', 'button', '--type', 'component', '--limit', '2'],+ REPO_ROOT,+ );+ expect(capped.status).toBe(0);+ expect(capped.stdout).toMatch(/^Results for "button" \(2 of \d+\)$/m);++ const uncapped = await runCli(+ ['search', 'button', '--type', 'component', '--limit', '500'],+ REPO_ROOT,+ );+ expect(uncapped.stdout).toMatch(/^Results for "button" \(\d+\)$/m);+ expect(uncapped.stdout).not.toMatch(/Results for "button" \(\d+ of/);+ });++ it('emits a valid --json envelope with empty results for no match', async () => {+ const r = await runCli(+ ['--json', 'search', 'zzqqxx_no_match'],+ REPO_ROOT,+ );+ expect(r.status).toBe(0);+ const parsed = JSON.parse(r.stdout);+ expect(parsed.type).toBe('search');+ expect(parsed.data.results).toEqual([]);+ expect(parsed.data.matchCount).toBe(0);+ });++ it('renders each result as a greppable key: value record', async () => {+ const r = await runCli(['search', 'button'], REPO_ROOT);+ expect(r.stdout).toMatch(+ /^command:\s+\S.*(?:astryx|@astryxdesign\/cli(?:@\S+)?) component Button$/m,+ );+ // Fields mirror the JSON object and are line-greppable.+ expect(r.stdout).toMatch(/^name:\s+Button$/m);+ expect(r.stdout).toMatch(/^domain:\s+component$/m);+ expect(r.stdout).toContain('description:');+ });++ it('prints every result field under its JSON key (score and reason with --verbose)', async () => {+ // Between them these reach every domain, so every per-domain field shows.+ // A theme matches `theme` only through its description, a prose mention+ // ranked below every name and keyword hit, so the theme domain comes from+ // a theme's own name.+ const domains = new Set();+ for (const args of [+ ['search', 'theme', '--limit', '60'],+ ['search', 'neutral', '--type', 'theme'],+ ]) {+ const env = JSON.parse(+ (await runCli(['--json', ...args], REPO_ROOT)).stdout,+ );+ const plain = (await runCli(args, REPO_ROOT)).stdout.split('\n');+ const verbose = (+ await runCli([...args, '--verbose'], REPO_ROOT)+ ).stdout.split('\n');+ for (const result of env.data.results) {+ domains.add(result.domain);+ for (const [key, value] of Object.entries(result)) {+ if (value == null || value === '') continue;+ const label = `${result.domain} ${result.name}: ${key}`;+ expect(printsField(verbose, key, value), label).toBe(true);+ if (key !== 'score' && key !== 'reason') {+ expect(printsField(plain, key, value), label).toBe(true);+ }}}}- }- expect(domains).toEqual(new Set(SEARCH_DOMAINS));- }, 90_000);-- it('--verbose exits 0 and prints import/match detail', async () => {- // Regression: the boolean verbose flag was named --detail, which collided- // with the value-taking global `--detail <level>` — a bare `search- // --detail` errored "argument missing" and the verbose output was- // unreachable. It is now `--verbose`.- const r = await runCli(['search', 'button', '--verbose'], REPO_ROOT);- expect(r.status).toBe(0);- expect(r.stdout).toContain('import:');- // Ranking detail: pre-formatter this was a single `match: <reason> (score N)`- // line; it's now separate `score:` / `reason:` record fields mirroring --json.- expect(r.stdout).toContain('score:');- expect(r.stdout).toContain('reason:');- });-- it('points at discover for packages that could add more, except for hooks', async () => {- const open = await runCli(['search', 'data', 'table'], REPO_ROOT);- expect(open.status).toBe(0);- expect(open.stdout).toMatch(/^More in packages you could add: .*discover 'data table'$/m);- const none = await runCli(['search', 'zzqqxxnomatch'], REPO_ROOT);- expect(none.stdout).toMatch(/^More in packages you could add: .*discover zzqqxxnomatch$/m);- const hooks = await runCli(['search', 'click', '--type', 'hook'], REPO_ROOT);- expect(hooks.status).toBe(0);- expect(hooks.stdout).not.toContain('More in packages you could add');- const json = await runCli(['--json', 'search', 'button'], REPO_ROOT);- expect(json.stdout).not.toContain('More in packages you could add');- });-- it('searches the docs and themes when no @astryxdesign/core is reachable, and exits 1 for --type component', async () => {- const empty = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-search-cli-no-core-'));- try {- const open = await runCli(['--json', 'search', 'make', 'an', 'integration'], empty);+ expect(domains).toEqual(new Set(SEARCH_DOMAINS));+ }, 90_000);++ it('--verbose exits 0 and prints import/match detail', async () => {+ // Regression: the boolean verbose flag was named --detail, which collided+ // with the value-taking global `--detail <level>` — a bare `search+ // --detail` errored "argument missing" and the verbose output was+ // unreachable. It is now `--verbose`.+ const r = await runCli(['search', 'button', '--verbose'], REPO_ROOT);+ expect(r.status).toBe(0);+ expect(r.stdout).toContain('import:');+ // Ranking detail: pre-formatter this was a single `match: <reason> (score N)`+ // line; it's now separate `score:` / `reason:` record fields mirroring --json.+ expect(r.stdout).toContain('score:');+ expect(r.stdout).toContain('reason:');+ });++ it('points at discover for packages that could add more, except for hooks', async () => {+ const open = await runCli(['search', 'data', 'table'], REPO_ROOT);expect(open.status).toBe(0);- expect(JSON.parse(open.stdout).data.results[0]).toMatchObject({domain: 'doc'});- // Bundled themes need no project, so an open search finds them too.- const theme = await runCli(['--json', 'search', 'neutral'], empty);- expect(theme.status).toBe(0);- expect(JSON.parse(theme.stdout).data.results[0]).toMatchObject({- domain: 'theme',- name: 'neutral',- });- // The text says the search covered the docs and themes alone.- const text = await runCli(['search', 'button'], empty);- expect(text.status).toBe(0);- expect(text.stdout).toContain('only the docs and themes were searched');- // A themes-only search needs no core, like a docs-only one.- const themes = await runCli(['--json', 'search', 'warm', '--type', 'theme'], empty);- expect(themes.status).toBe(0);- const found = JSON.parse(themes.stdout).data.results;- expect(found.map(r => r.name)).toContain('neutral');- expect(found.every(r => r.domain === 'theme')).toBe(true);- const json = await runCli(['--json', 'search', 'button', '--type', 'component'], empty);- expect(json.status).toBe(1);- expect(JSON.parse(json.stdout)).toMatchObject({code: 'ERR_CORE_NOT_FOUND'});- } finally {- fs.rmSync(empty, {recursive: true, force: true});- }- });-}, SCAN_TIMEOUT);+ expect(open.stdout).toMatch(+ /^More in packages you could add: .*discover 'data table'$/m,+ );+ const none = await runCli(['search', 'zzqqxxnomatch'], REPO_ROOT);+ expect(none.stdout).toMatch(+ /^More in packages you could add: .*discover zzqqxxnomatch$/m,+ );+ const hooks = await runCli(+ ['search', 'click', '--type', 'hook'],+ REPO_ROOT,+ );+ expect(hooks.status).toBe(0);+ expect(hooks.stdout).not.toContain('More in packages you could add');+ const json = await runCli(['--json', 'search', 'button'], REPO_ROOT);+ expect(json.stdout).not.toContain('More in packages you could add');+ });++ it("finds components in an open search outside a project and in a fresh clone, reading the release's own Core", async () => {+ const empty = fs.mkdtempSync(+ path.join(os.tmpdir(), 'astryx-search-cli-carried-'),+ );+ const clone = fs.mkdtempSync(+ path.join(os.tmpdir(), 'astryx-search-cli-clone-'),+ );+ // A fresh clone: it declares Core, with nothing installed.+ fs.writeFileSync(+ path.join(clone, 'package.json'),+ JSON.stringify({+ name: 'clone',+ dependencies: {'@astryxdesign/core': '*'},+ }),+ );+ try {+ for (const dir of [empty, clone]) {+ const run = await runCli(['--json', 'search', 'button'], dir);+ expect(run.status).toBe(0);+ const envelope = JSON.parse(run.stdout);+ expect(envelope.meta?.partial).toBeUndefined();+ expect(+ envelope.data.results.some(+ (/** @type {any} */ r) =>+ r.domain === 'component' && r.name === 'Button',+ ),+ ).toBe(true);+ }+ } finally {+ fs.rmSync(empty, {recursive: true, force: true});+ fs.rmSync(clone, {recursive: true, force: true});+ }+ });++ it('searches the docs and themes when no @astryxdesign/core is reachable, and exits 1 for --type component', async () => {+ const empty = fs.mkdtempSync(+ path.join(os.tmpdir(), 'astryx-search-cli-no-core-'),+ );+ // The project's own CLI answers here and no Core is installed; outside a+ // project the carried Core would answer instead (AST-081 FR3).+ linkThisCliAsProjectCli(empty);+ try {+ const open = await runCli(+ ['--json', 'search', 'make', 'an', 'integration'],+ empty,+ );+ expect(open.status).toBe(0);+ expect(JSON.parse(open.stdout).data.results[0]).toMatchObject({+ domain: 'doc',+ });+ // Never silently: JSON names what it skipped and why.+ expect(JSON.parse(open.stdout).meta.partial).toMatchObject({+ skipped: ['component', 'hook', 'template'],+ reason: expect.stringContaining('@astryxdesign/core'),+ });+ // Bundled themes need no project, so an open search finds them too.+ const theme = await runCli(['--json', 'search', 'neutral'], empty);+ expect(theme.status).toBe(0);+ expect(JSON.parse(theme.stdout).data.results[0]).toMatchObject({+ domain: 'theme',+ name: 'neutral',+ });+ // The text says the search covered the docs and themes alone.+ const text = await runCli(['search', 'button'], empty);+ expect(text.status).toBe(0);+ expect(text.stdout).toContain('only the docs and themes were searched');+ expect(text.stderr).toMatch(+ /^astryx: components, hooks, and templates were not searched: /mu,+ );+ // A themes-only search needs no core, like a docs-only one.+ const themes = await runCli(+ ['--json', 'search', 'warm', '--type', 'theme'],+ empty,+ );+ expect(themes.status).toBe(0);+ const found = JSON.parse(themes.stdout).data.results;+ expect(found.map(r => r.name)).toContain('neutral');+ expect(found.every(r => r.domain === 'theme')).toBe(true);+ const json = await runCli(+ ['--json', 'search', 'button', '--type', 'component'],+ empty,+ );+ expect(json.status).toBe(1);+ expect(JSON.parse(json.stdout)).toMatchObject({+ code: 'ERR_CORE_NOT_FOUND',+ });+ } finally {+ fs.rmSync(empty, {recursive: true, force: true});+ }+ });+ },+ SCAN_TIMEOUT,+);diff --git a/packages/cli/clients/cli/commands/setup-nudge.test.mjs b/packages/cli/clients/cli/commands/setup-nudge.test.mjsindex 1ed509022c..4a301fea07 100644--- a/packages/cli/clients/cli/commands/setup-nudge.test.mjs+++ b/packages/cli/clients/cli/commands/setup-nudge.test.mjs@@ -112,7 +112,8 @@ describe('isAstryxPromptInReach — up to the repository root', () => {});describe('enforcement layer 3 — per-command setup nudge', () => {- const asProject = () => write('package.json', '{"name":"t"}');+ const asProject = () =>+ write('package.json', '{"name":"t","dependencies":{"@astryxdesign/core":"*"}}');it('nudges on stderr after a command when not set up', async () => {asProject();@@ -120,6 +121,22 @@ describe('enforcement layer 3 — per-command setup nudge', () => {expect(r.stderr).toMatch(NUDGE);});+ it("in a project with only Core of another release, names adding the CLI at Core's version first, as the daily hint does", async () => {+ write(+ 'package.json',+ '{"name":"t","dependencies":{"@astryxdesign/core":"0.0.1"}}',+ );+ write(+ 'node_modules/@astryxdesign/core/package.json',+ '{"name":"@astryxdesign/core","version":"0.0.1"}',+ );+ write('package-lock.json', '{}');+ const r = await runCli(['docs', 'tokens'], tmp);+ expect(r.stderr).toContain(+ 'Next step: run `npm install @astryxdesign/[email protected]`, then `npx astryx init` to finish setup and install the Astryx agent prompt.',+ );+ });+it('is suppressed in --json (machine mode stays clean), stdout valid JSON', async () => {asProject();const r = await runCli(['--json', 'docs', 'tokens'], tmp);@@ -139,6 +156,11 @@ describe('enforcement layer 3 — per-command setup nudge', () => {expect((await runCli(['docs', 'tokens'], tmp)).stderr).not.toMatch(NUDGE);});+ it('is quiet outside a project (a package.json that declares no Astryx package)', async () => {+ write('package.json', '{"name":"t"}');+ expect((await runCli(['docs', 'tokens'], tmp)).stderr).not.toMatch(NUDGE);+ });+it('is quiet in an integration package, which is not an app', async () => {asProject();write('astryx.integration.mjs', 'export default {};\n');@@ -153,7 +175,7 @@ describe('enforcement layer 3 — per-command setup 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"}');+ write('packages/app/package.json', '{"name":"app","dependencies":{"@astryxdesign/core":"*"}}');const r = await runCli(['docs', 'tokens'], path.join(tmp, 'packages/app'));expect(r.stderr).not.toMatch(NUDGE);});@@ -161,7 +183,7 @@ describe('enforcement layer 3 — per-command setup 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"}');+ write('packages/app/package.json', '{"name":"app","dependencies":{"@astryxdesign/core":"*"}}');const r = await runCli(['docs', 'tokens'], path.join(tmp, 'packages/app'));expect(r.stderr).toMatch(NUDGE);});@@ -171,7 +193,7 @@ describe('enforcement layer 3 — per-command setup nudge', () => {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"}');+ fs.writeFileSync(path.join(inside, 'package.json'), '{"name":"t","dependencies":{"@astryxdesign/core":"*"}}');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.doc.mjs b/packages/cli/clients/cli/commands/swizzle.doc.mjsindex 38ddf9d6e0..5fbd1f4633 100644--- a/packages/cli/clients/cli/commands/swizzle.doc.mjs+++ b/packages/cli/clients/cli/commands/swizzle.doc.mjs@@ -57,6 +57,7 @@ export const doc = {cli: 'astryx swizzle SideNav --package @astryxdesign/core',},],+ outsideProject: 'refuse',exitCodes: [{code: 0, when: 'success'},{@@ -65,4 +66,10 @@ export const doc = {},],related: ['component', 'discover', 'upgrade'],+ notes: [+ {+ type: 'prose',+ text: 'In global mode: outside a project, swizzle writes nothing and stops with `ERR_CORE_NOT_FOUND`: "Could not find @astryxdesign/core package. Make sure you are inside the design system monorepo or have @astryxdesign/core installed." In a project, the project\'s version of Astryx runs it, whichever astryx command you start. See {@link namespace:global} and {@link generic:problems}.',+ },+ ],};diff --git a/packages/cli/clients/cli/commands/swizzle.routing.test.mjs b/packages/cli/clients/cli/commands/swizzle.routing.test.mjsindex 8b267f37e4..b06ec87fdd 100644--- a/packages/cli/clients/cli/commands/swizzle.routing.test.mjs+++ b/packages/cli/clients/cli/commands/swizzle.routing.test.mjs@@ -315,7 +315,7 @@ describe('swizzle — StyleX build setup note (#3373)', () => {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/);+ expect(humanResult.stdout).toMatch(/@astryxdesign\/cli@\S+ docs styling/);});// The note quotes what StyleX does without a compiler; this keeps it true.diff --git a/packages/cli/clients/cli/commands/template.doc.mjs b/packages/cli/clients/cli/commands/template.doc.mjsindex 5633337a74..74031c7c61 100644--- a/packages/cli/clients/cli/commands/template.doc.mjs+++ b/packages/cli/clients/cli/commands/template.doc.mjs@@ -102,6 +102,7 @@ export const doc = {cli: 'astryx template --cdn public/demo.html',},],+ outsideProject: 'same',exitCodes: [{code: 0,diff --git a/packages/cli/clients/cli/commands/theme-add-lifecycle.test.mjs b/packages/cli/clients/cli/commands/theme-add-lifecycle.test.mjsindex 5ef5697adf..95dce79587 100644--- a/packages/cli/clients/cli/commands/theme-add-lifecycle.test.mjs+++ b/packages/cli/clients/cli/commands/theme-add-lifecycle.test.mjs@@ -20,7 +20,7 @@ beforeEach(() => {JSON.stringify({name: 'app',private: true,- dependencies: {'@acme/themes': '^1.0.0'},+ dependencies: {'@acme/themes': '^1.0.0', '@astryxdesign/core': '*'},}),);const packageDir = path.join(tmpDir, 'node_modules', '@acme', 'themes');@@ -99,7 +99,7 @@ describe('theme add cleanup lifecycle', () => {change: {action: 'add', slug: 'ocean', changed: true},},});- expect(payload.meta).toBeUndefined();+ expect(Object.keys(payload.meta)).toEqual(['answeredBy']);});it('keeps --import as an accepted no-op with the same response', async () => {@@ -151,7 +151,7 @@ describe('theme add cleanup lifecycle', () => {expect(result.status, result.stderr).toBe(0);const payload = JSON.parse(result.stdout);expect(payload).toMatchObject({type: 'theme.list'});- expect(payload.meta).toBeUndefined();+ expect(Object.keys(payload.meta)).toEqual(['answeredBy']);expect(payload.data.some(theme => theme.slug === 'broken')).toBe(false);expect(Object.keys(payload.data[0]).sort()).toEqual(['description',diff --git a/packages/cli/clients/cli/commands/theme-add.doc.mjs b/packages/cli/clients/cli/commands/theme-add.doc.mjsindex 0477a77b59..f3cfb7d071 100644--- a/packages/cli/clients/cli/commands/theme-add.doc.mjs+++ b/packages/cli/clients/cli/commands/theme-add.doc.mjs@@ -11,7 +11,7 @@ export const doc = {summary:"Add a built theme to the app. To copy a theme's source as an editable fork, run `theme eject <slug> [path] [--overwrite]`.",description:- "Records the theme in the generated app module and imports its built module and stylesheets. --import remains accepted as a compatibility no-op. To copy a theme's source as an editable fork, run `theme eject <slug> [path] [--overwrite]`. A bare command or --list delegates to themeListCopySources(), whose released JSON bytes stay unchanged while its text names the current add and eject commands; use --package when owners share a slug.",+ "Records the theme in the generated app module and imports its built module and stylesheets. --import remains accepted as a compatibility no-op. To copy a theme's source as an editable fork, run `theme eject <slug> [path] [--overwrite]`. A bare command or --list delegates to themeListCopySources(), whose released JSON bytes stay unchanged while its text names the current add and eject commands; use --package when owners share a slug. Outside a project, a bare command or --list lists the available themes as in a new project; given a slug it writes nothing and fails, naming the app project it needs (ERR_THEME_INVALID), or with ERR_UNKNOWN_THEME when no theme has that slug.",fn: 'themeAdd',args: [{name: 'slug', param: 'slug', required: false}],options: [@@ -38,6 +38,7 @@ export const doc = {cli: 'astryx theme add ocean --package @acme/themes',},],+ outsideProject: 'own',exitCodes: [{code: 0, when: 'the theme is listed or added'},{@@ -46,4 +47,10 @@ export const doc = {},],related: ['theme list', 'theme remove', 'theme use', 'theme eject'],+ notes: [+ {+ type: 'prose',+ text: 'In global mode: outside a project, theme add with no slug lists the themes available, as in a new project; with a slug it writes nothing and stops with `ERR_THEME_INVALID`: "No package.json found. Run this command inside an app project." In a project, the project\'s version of Astryx runs it, whichever astryx command you start. See {@link namespace:global} and {@link generic:problems}.',+ },+ ],};diff --git a/packages/cli/clients/cli/commands/theme-build.doc.mjs b/packages/cli/clients/cli/commands/theme-build.doc.mjsindex 303ba86c5b..7b242fed0d 100644--- a/packages/cli/clients/cli/commands/theme-build.doc.mjs+++ b/packages/cli/clients/cli/commands/theme-build.doc.mjs@@ -83,6 +83,7 @@ export const doc = {cli: 'astryx theme build ./src/themes/ocean.ts --icons-specifier ./icons.mjs',},],+ outsideProject: 'same',exitCodes: [{code: 0,diff --git a/packages/cli/clients/cli/commands/theme-eject.doc.mjs b/packages/cli/clients/cli/commands/theme-eject.doc.mjsindex c10459f6f8..301a7d3d99 100644--- a/packages/cli/clients/cli/commands/theme-eject.doc.mjs+++ b/packages/cli/clients/cli/commands/theme-eject.doc.mjs@@ -36,6 +36,7 @@ export const doc = {cli: 'astryx theme eject ocean src/themes/my-ocean --package @acme/themes',},],+ outsideProject: 'same',exitCodes: [{code: 0, when: 'all source and descriptor files are written'},{diff --git a/packages/cli/clients/cli/commands/theme-list.behavior.test.mjs b/packages/cli/clients/cli/commands/theme-list.behavior.test.mjsindex 7d2550970e..7343481e05 100644--- a/packages/cli/clients/cli/commands/theme-list.behavior.test.mjs+++ b/packages/cli/clients/cli/commands/theme-list.behavior.test.mjs@@ -24,6 +24,12 @@ afterEach(() => {describe('astryx theme list', () => {it('lists bundled themes and points at import, eject, and discover', async () => {+ // Inside a project; outside one there is no app to import into+ // (outside-project.test.mjs).+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ '{"name":"app","dependencies":{"@astryxdesign/core":"*"}}',+ );const {status, stdout} = await runCli(['theme', 'list'], {cwd: tmpDir});expect(status).toBe(0);diff --git a/packages/cli/clients/cli/commands/theme-list.doc.mjs b/packages/cli/clients/cli/commands/theme-list.doc.mjsindex c533f5e82b..72565b70cb 100644--- a/packages/cli/clients/cli/commands/theme-list.doc.mjs+++ b/packages/cli/clients/cli/commands/theme-list.doc.mjs@@ -33,6 +33,7 @@ export const doc = {cli: 'astryx theme list --package @acme/themes',},],+ outsideProject: 'same',exitCodes: [{code: 0, when: 'success'},{diff --git a/packages/cli/clients/cli/commands/theme-palette-generate.doc.mjs b/packages/cli/clients/cli/commands/theme-palette-generate.doc.mjsindex c7336b5f6e..55e353eb4c 100644--- a/packages/cli/clients/cli/commands/theme-palette-generate.doc.mjs+++ b/packages/cli/clients/cli/commands/theme-palette-generate.doc.mjs@@ -57,6 +57,7 @@ export const doc = {cli: 'astryx theme palette generate themes/ocean/palette.config.json --out themes/ocean/tokens/ocean.palette.ts --preview themes/ocean/tokens/ocean.palette.html',},],+ outsideProject: 'same',exitCodes: [{code: 0,diff --git a/packages/cli/clients/cli/commands/theme-remove.doc.mjs b/packages/cli/clients/cli/commands/theme-remove.doc.mjsindex 4f894c4e50..872c77fdd1 100644--- a/packages/cli/clients/cli/commands/theme-remove.doc.mjs+++ b/packages/cli/clients/cli/commands/theme-remove.doc.mjs@@ -14,9 +14,16 @@ export const doc = {fn: 'themeRemove',args: [{name: 'slug', param: 'slug', required: true}],examples: [{label: 'Remove an added theme', cli: 'astryx theme remove ocean'}],+ outsideProject: 'refuse',exitCodes: [{code: 0, when: 'the module is regenerated without the theme'},{code: 1, when: 'the theme is not added, is the default, or state is invalid'},],related: ['theme add', 'theme use', 'theme list'],+ notes: [+ {+ type: 'prose',+ text: "In global mode: outside a project, theme remove writes nothing and stops with `ERR_THEME_INVALID`: \"No package.json found. Run this command inside an app project.\" In a project, the project's version of Astryx runs it, whichever astryx command you start. See {@link namespace:global} and {@link generic:problems}.",+ },+ ],};diff --git a/packages/cli/clients/cli/commands/theme-targets.doc.mjs b/packages/cli/clients/cli/commands/theme-targets.doc.mjsindex 954b7dc5cb..fed9b3ffca 100644--- a/packages/cli/clients/cli/commands/theme-targets.doc.mjs+++ b/packages/cli/clients/cli/commands/theme-targets.doc.mjs@@ -30,6 +30,7 @@ export const doc = {{label: 'Search keys', cli: 'astryx theme targets thumb'},{label: 'For a lint or an audit script', cli: 'astryx --json theme targets'},],+ outsideProject: 'same',exitCodes: [{code: 0, when: 'success'},{code: 1, when: 'a filter matches no target, or core cannot be resolved'},diff --git a/packages/cli/clients/cli/commands/theme-template.doc.mjs b/packages/cli/clients/cli/commands/theme-template.doc.mjsindex 1db55f23cb..6242db1ef8 100644--- a/packages/cli/clients/cli/commands/theme-template.doc.mjs+++ b/packages/cli/clients/cli/commands/theme-template.doc.mjs@@ -35,6 +35,7 @@ export const doc = {{label: 'Write it at the project root', cli: 'astryx theme template'},{label: 'Somewhere else', cli: 'astryx theme template src/themes/starter.ts'},],+ outsideProject: 'same',exitCodes: [{code: 0, when: 'success, including when an existing file was left untouched'},{code: 1, when: 'the target path escapes the project, or the file cannot be written'},diff --git a/packages/cli/clients/cli/commands/theme-use.doc.mjs b/packages/cli/clients/cli/commands/theme-use.doc.mjsindex 1b1ede769c..789a8bd6c5 100644--- a/packages/cli/clients/cli/commands/theme-use.doc.mjs+++ b/packages/cli/clients/cli/commands/theme-use.doc.mjs@@ -14,9 +14,16 @@ export const doc = {fn: 'themeUse',args: [{name: 'slug', param: 'slug', required: true}],examples: [{label: 'Choose the default theme', cli: 'astryx theme use ocean'}],+ outsideProject: 'refuse',exitCodes: [{code: 0, when: 'the module is regenerated with the selected default'},{code: 1, when: 'the theme is not added or state is invalid'},],related: ['theme add', 'theme remove', 'theme list'],+ notes: [+ {+ type: 'prose',+ text: "In global mode: outside a project, theme use writes nothing and stops with `ERR_THEME_INVALID`: \"No package.json found. Run this command inside an app project.\" In a project, the project's version of Astryx runs it, whichever astryx command you start. See {@link namespace:global} and {@link generic:problems}.",+ },+ ],};diff --git a/packages/cli/clients/cli/commands/upgrade.config-ordering.test.mjs b/packages/cli/clients/cli/commands/upgrade.config-ordering.test.mjsindex 9a9819da11..b0743d4271 100644--- a/packages/cli/clients/cli/commands/upgrade.config-ordering.test.mjs+++ b/packages/cli/clients/cli/commands/upgrade.config-ordering.test.mjs@@ -30,6 +30,7 @@ import {Command} from 'commander';import {registerUpgrade} from './upgrade.mjs';import {Project} from '../../../foundation/config/project.mjs';import {generateCompressedIndex} from '../../../foundation/agent-docs/agent-docs.mjs';+import {CLI_VERSION} from '../../../test-utils/release-fixtures.mjs';let tmpDir;let originalCwd;@@ -189,7 +190,7 @@ describe('upgrade — core codemods run before config load', () => {expect(out).toMatch(/fails strict validation/i);// The fixture has no `astryx` bin installed, so the command names the scoped package.expect(out).toContain(- '@astryxdesign/cli upgrade --from 0.1.2 --codemod migrate-layout-components-to-experimental --apply',+ `@astryxdesign/cli@${CLI_VERSION} upgrade --from 0.1.2 --codemod migrate-layout-components-to-experimental --apply`,);expect(exitCode).not.toBe(1);});diff --git a/packages/cli/clients/cli/commands/upgrade.doc.mjs b/packages/cli/clients/cli/commands/upgrade.doc.mjsindex ad296cece1..c4c90781e4 100644--- a/packages/cli/clients/cli/commands/upgrade.doc.mjs+++ b/packages/cli/clients/cli/commands/upgrade.doc.mjs@@ -21,7 +21,9 @@ export const doc = {'agent-docs block when Core or configured integration guidance changes. ' +'Dry-run by default. --apply writes codemod and receipt changes, runs hooks, then refreshes agent docs. ' +'Anything a post-codemod hook prints goes to stderr, so stdout carries only the result. ' +- 'ShadCN-copied compositions are checked automatically during a normal upgrade, or alone with --registry.',+ 'ShadCN-copied compositions are checked automatically during a normal upgrade, or alone with --registry. ' ++ 'Outside a project, --list lists the codemods this release ships and --registry finds no copied compositions to update; ' ++ 'a migration writes nothing and fails with ERR_VERSION_DETECT, because no installed Core names its target.',fn: 'upgrade',options: [{@@ -102,6 +104,7 @@ export const doc = {},{label: 'Apply a migration', cli: 'astryx upgrade --from 0.1.0 --apply'},],+ outsideProject: 'own',exitCodes: [{code: 0, when: 'success, including complete dry-run previews'},{@@ -116,6 +119,10 @@ export const doc = {],related: ['init', 'doctor'],notes: [+ {+ type: 'prose',+ text: "In global mode: in a project, upgrade runs the codemods of the project's own CLI, whichever astryx command you start; in a project with no CLI of its own, the astryx command you started runs them, so install the CLI at the new Core's version first (`astryx doctor` prints the command). Outside a project, `--list` lists this version's codemods, `--registry` finds no copied compositions, and a migration writes nothing and stops with `ERR_VERSION_DETECT`. See {@link namespace:global} and {@link generic:who-answers}.",+ },{type: 'heading', level: 3, text: 'A CLI older than your Core'},{type: 'prose',diff --git a/packages/cli/clients/cli/commands/upgrade.file-protection.test.mjs b/packages/cli/clients/cli/commands/upgrade.file-protection.test.mjsindex 401bc298c5..6eda9be6cf 100644--- a/packages/cli/clients/cli/commands/upgrade.file-protection.test.mjs+++ b/packages/cli/clients/cli/commands/upgrade.file-protection.test.mjs@@ -10,6 +10,7 @@ import * as fs from 'node:fs';import * as os from 'node:os';import * as path from 'node:path';import {fileURLToPath} from 'node:url';+import {CLI_VERSION} from '../../../test-utils/release-fixtures.mjs';const CLI = path.resolve(path.dirname(fileURLToPath(import.meta.url)),@@ -44,7 +45,7 @@ function seed({hook = false} = {}) {write('package.json', JSON.stringify({name: 'consumer', private: true}));write('node_modules/@astryxdesign/core/package.json',- JSON.stringify({name: '@astryxdesign/core', version: '0.6.0'}),+ JSON.stringify({name: '@astryxdesign/core', version: CLI_VERSION}),);write('.gitattributes', 'generated/** linguist-generated=true\n');const source =@@ -122,7 +123,7 @@ describe('upgrade protected-file contract', () => {write('package.json', JSON.stringify({name: 'consumer', private: true}));write('node_modules/@astryxdesign/core/package.json',- JSON.stringify({name: '@astryxdesign/core', version: '0.1.3'}),+ JSON.stringify({name: '@astryxdesign/core', version: CLI_VERSION}),);write('astryx.config.mjs',diff --git a/packages/cli/clients/cli/commands/upgrade.hook-output.test.mjs b/packages/cli/clients/cli/commands/upgrade.hook-output.test.mjsindex dca08937e1..3b8121182c 100644--- a/packages/cli/clients/cli/commands/upgrade.hook-output.test.mjs+++ b/packages/cli/clients/cli/commands/upgrade.hook-output.test.mjs@@ -12,6 +12,7 @@ import * as fs from 'node:fs';import * as path from 'node:path';import * as os from 'node:os';import {fileURLToPath} from 'node:url';+import {CLI_VERSION} from '../../../test-utils/release-fixtures.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));const CLI = path.resolve(__dirname, '..', 'bin', 'astryx.mjs');@@ -41,7 +42,7 @@ beforeEach(() => {write('package.json', JSON.stringify({name: 'consumer', private: true}));write('node_modules/@astryxdesign/core/package.json',- JSON.stringify({name: '@astryxdesign/core', version: '0.6.0'}),+ JSON.stringify({name: '@astryxdesign/core', version: CLI_VERSION}),);write('src/panel.tsx',diff --git a/packages/cli/clients/cli/index.mjs b/packages/cli/clients/cli/index.mjsindex 579b27fcc3..a3c42f2a6f 100644--- a/packages/cli/clients/cli/index.mjs+++ b/packages/cli/clients/cli/index.mjs@@ -16,8 +16,14 @@ import {Command, Option} from 'commander';import {fileURLToPath} from 'node:url';import * as fs from 'node:fs';import * as path from 'node:path';-import {getCliInvocation} from '../../foundation/env/package-manager.mjs';+import {formatCliCommand, getCliInvocation} from '../../foundation/env/package-manager.mjs';+import {hasRecordedProject} from '../../foundation/env/cli-command.mjs';+import {isOutsideProject} from '../../foundation/env/project-scope.mjs';import {API_VERSION, setJsonMode} from '../../foundation/response/json.mjs';+import {answeredBy, runChoice} from '../../foundation/release/run-context.mjs';+import {addCliCommand} from '../../foundation/release/notices.mjs';+import {projectRootOf} from '../../foundation/release/choose.mjs';+import {readReleaseFacts} from '../../foundation/release/project.mjs';import {buildManifest} from './lib/manifest.mjs';import {cliError} from './lib/cli-error.mjs';import {emit, section, text, records} from './formatters/index.mjs';@@ -28,6 +34,7 @@ import {addDocHelp, markReportsResult} from './lib/define-command.mjs';import {doc as manifestDoc} from './commands/manifest.doc.mjs';import {isAstryxInitialized, isAstryxPromptInReach} from '../../foundation/agent-docs/agent-docs.mjs';import {CLI_ROOT} from '../../foundation/fs/paths.mjs';+import {setupNudge} from '../../foundation/agent-docs/agent-doc-state.mjs';import * as debug from '../../foundation/debug/index.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));@@ -64,7 +71,7 @@ export function handleVersionJsonPreflight(argv = process.argv.slice(2)) {// reports the same shape Commander's own `--version` path does.debug.recordCommandResult(debug.NO_RESULT_SET);debug.setOutcome('ok', {exitCode: 0});- console.log(JSON.stringify({apiVersion: API_VERSION, type: 'version', data: {version: pkg.version}}, null, 2));+ console.log(JSON.stringify({apiVersion: API_VERSION, type: 'version', data: {version: pkg.version}, meta: {answeredBy: answeredBy()}}, null, 2));process.exit(0);}@@ -186,6 +193,31 @@ export async function loadProjectDebugHandler() {}}+/**+ * Load the project's integrations before a help run, so help prints commands+ * with the `cliCommand` they declare (spec:AST-081 FR5). Help is printed while+ * Commander parses, before any hook, so the preAction load cannot reach it.+ * `Project.load` reads astryx.config and each integration's manifest; it does+ * no discovery. Skipped when the debug preload already loaded the project, and+ * outside a package. Called from the bin before Commander parses.+ *+ * @param {string[]} [argv] arguments after the binary.+ * @returns {Promise<void>}+ */+export async function loadProjectForHelp(argv = process.argv.slice(2)) {+ const help =+ argv.includes('--help') || argv.includes('-h') || argv[0] === 'help';+ if (!help) return;+ try {+ const cwd = process.cwd();+ if (hasRecordedProject(cwd)) return;+ const {Project} = await import('../../foundation/config/project.mjs');+ await Project.load(cwd);+ } catch {+ // Help prints with the package-manager guess.+ }+}+/*** Hand the whole invocation to the debug recorder: which command ran, its* positional arguments by name, its options and where each value came from,@@ -329,7 +361,8 @@ export async function createProgram() {// kit in clients/cli/formatters.program.addHelpText('after',- '\n' ++ // A function, so the example names the invocation when help is printed.+ () => '\n' +[section('Output format',@@ -352,9 +385,13 @@ export async function createProgram() {{fields: ['block', 'shape']},),text(- 'Grep a field across records, e.g. astryx search button | grep "^command:". ' ++ `Grep a field across records, e.g. ${formatCliCommand('search button')} | grep "^command:". ` +'Errors/warnings go to stderr; use --json for structured parsing.',),+ text(+ "Global mode: in a project, the project's own CLI answers (this copy hands the run to it); a copy installed for the computer checks for updates once a day and keeps an agent skill in your home folder. " ++ `See ${formatCliCommand('docs global')}.`,+ ),].map(block => block.toString()).join('\n\n'),@@ -451,6 +488,7 @@ export async function createProgram() {// Enriched, self-describing surface (the full manifest payload).manifest,},+ meta: {answeredBy: answeredBy()},}, null, 2));debug.recordCommandResult(debug.resultSet({@@ -547,6 +585,24 @@ export async function createProgram() {process.exit(1);});+ /**+ * Load the project's integrations before any command runs, so every command+ * it prints starts with the `cliCommand` they declare (the picker reads them+ * synchronously; see foundation/env/cli-command.mjs). Skipped when this+ * process already loaded the project, such as the bin's debug preload. A+ * project that cannot load is the command's to report, never this hook's.+ */+ program.hook('preAction', async () => {+ try {+ const cwd = process.cwd();+ if (hasRecordedProject(cwd)) return;+ const {Project} = await import('../../foundation/config/project.mjs');+ await Project.load(cwd);+ } catch {+ // Best-effort: the picker falls back to its package-manager guess.+ }+ });+/*** Enforcement layer 3 — setup nudge. If this project hasn't run `astryx init`* yet (no Astryx marker in any agent-doc file between the project and its@@ -561,8 +617,9 @@ 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, outside a project (no package.json),- * and inside the CLI's own source checkout when it runs from there.+ * for the installer commands themselves, outside a project (no package.json,+ * or one that neither installs nor declares Astryx), and inside the CLI's own+ * source checkout when it runs from there.*/program.hook('preAction', (thisCommand, actionCommand) => {try {@@ -570,16 +627,30 @@ export async function createProgram() {if (SETUP_NUDGE_EXEMPT.has(actionCommand.name())) return;const cwd = process.cwd();if (!fs.existsSync(path.join(cwd, 'package.json'))) return; // not a project+ // A package.json that neither installs nor declares Astryx is outside a+ // project: `init` would set up a project the folder does not have+ // (spec AST-081 FR3).+ if (isOutsideProject(cwd)) return;// 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 (inOwnSourceCheckout(cwd)) return; // developing Astryx itself, not an appif (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.- console.error(- `\nNext step: run \`${getCliInvocation(cwd)} init\` to finish setup and install the Astryx agent prompt.`,- );+ // Same wording as the core/cli postinstall nudges. getCliInvocation()+ // renders the correct form for THIS project — an integration's cliCommand,+ // scoped `npx @astryxdesign/cli` one-off, or `<pm> astryx` when installed —+ // never npx with the unscoped name, which fetches an unrelated package.+ // A project with no CLI of its own, answered by another release than its+ // Core's: add the CLI at Core's version first, as the daily hint says,+ // then run that CLI's init (spec AST-081 FR2).+ const choice = runChoice(cwd);+ if (choice.copy === 'starting' && choice.coreVersion && choice.coreVersion !== choice.version) {+ const root = projectRootOf(readReleaseFacts(cwd)) ?? cwd;+ console.error(+ setupNudge(getCliInvocation(root, {installed: true}), {before: addCliCommand(root, choice.coreVersion)}).trimEnd(),+ );+ return;+ }+ console.error(setupNudge(getCliInvocation(cwd)).trimEnd());} catch {// Never let the nudge break a command.}@@ -632,7 +703,7 @@ export async function createProgram() {);if (program.opts().json) {process.__xdsJsonHandled = true;- console.log(JSON.stringify({apiVersion: API_VERSION, type: 'manifest', data: manifest}, null, 2));+ console.log(JSON.stringify({apiVersion: API_VERSION, type: 'manifest', data: manifest, meta: {answeredBy: answeredBy()}}, null, 2));return;}// Human-readable summary as greppable records (agents should use --json).diff --git a/packages/cli/clients/cli/lib/cli-error.mjs b/packages/cli/clients/cli/lib/cli-error.mjsindex 303a29e2b6..e7ef42a9ad 100644--- a/packages/cli/clients/cli/lib/cli-error.mjs+++ b/packages/cli/clients/cli/lib/cli-error.mjs@@ -53,6 +53,7 @@import {isJsonMode, jsonError as _jsonError, humanWarn} from '../../../foundation/response/json.mjs';import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';import {setOutcome} from '../../../foundation/debug/index.mjs';+import {formatCliCommand} from '../../../foundation/env/package-manager.mjs';/*** Suggestion object — matches the shape used by API errors and the JSON@@ -122,7 +123,9 @@ export function cliError(message, options = {}) {if (suggestions?.length) {console.error('');for (const s of suggestions) {- const tag = s.reason ? ` ${s.name} (${s.reason})` : ` ${s.name}`;+ // A suggested command stays bare in JSON and is prefixed here.+ const name = /^astryx(\s|$)/.test(s.name) ? formatCliCommand(s.name) : s.name;+ const tag = s.reason ? ` ${name} (${s.reason})` : ` ${name}`;console.error(tag);}}diff --git a/packages/cli/clients/cli/lib/component-format.test.mjs b/packages/cli/clients/cli/lib/component-format.test.mjsindex 4025319c71..bf4b940c75 100644--- a/packages/cli/clients/cli/lib/component-format.test.mjs+++ b/packages/cli/clients/cli/lib/component-format.test.mjs@@ -67,7 +67,7 @@ describe('formatFull sub-component rendering', () => {expect(out).not.toContain('undefined');// Points the reader at the sub-component's own docs instead of a blank.expect(out).toMatch(- /(?:astryx|@astryxdesign\/cli) component XDSRadioListItem/,+ /(?:astryx|@astryxdesign\/cli(?:@\S+)?) component XDSRadioListItem/,);});diff --git a/packages/cli/clients/cli/lib/define-command.mjs b/packages/cli/clients/cli/lib/define-command.mjsindex 3eb528743b..d6c4a6c015 100644--- a/packages/cli/clients/cli/lib/define-command.mjs+++ b/packages/cli/clients/cli/lib/define-command.mjs@@ -180,8 +180,8 @@ export function defineCommand(parent, doc, {fn, action} = {}) {*/export function addDocHelp(cmd, doc) {addExitCodesHelp(cmd, doc.exitCodes);- // Rendered when help is shown, so the run prefix (npx astryx, pnpm astryx,- // ...) is looked up then, not on every start.+ // Rendered when help is shown, so the run prefix (pnpm exec astryx, yarn+ // astryx, ...) is looked up then, not on every start.cmd.addHelpText('after', () => {const examples = (doc.examples ?? []).flatMap(({label, cli}) => [...(label ? [` # ${label}`] : []),diff --git a/packages/cli/clients/cli/lib/json-shim.mjs b/packages/cli/clients/cli/lib/json-shim.mjsindex 22dba4aa8b..0cbf09d1eb 100644--- a/packages/cli/clients/cli/lib/json-shim.mjs+++ b/packages/cli/clients/cli/lib/json-shim.mjs@@ -42,6 +42,7 @@*/import {API_VERSION, isJsonMode, toErrorEnvelope} from '../../../foundation/response/json.mjs';+import {answeredBy} from '../../../foundation/release/run-context.mjs';import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';import {setCommand, setOutcome, recordHelp} from '../../../foundation/debug/index.mjs';@@ -84,7 +85,7 @@ function jsonActive() {* subcommand (e.g. `astryx component --help --json`).** @param {import('commander').Command} cmd- * @returns {{apiVersion: number, type: 'help', data: object}}+ * @returns {{apiVersion: number, type: 'help', data: object, meta: {answeredBy: {cli: string, core: string | null, copy: 'project' | 'starting' | 'matched' | 'carried' | 'fallback'}}}}*/export function buildHelpEnvelope(cmd) {// Reconstruct the fully-qualified command name (e.g. "astryx theme build").@@ -119,6 +120,7 @@ export function buildHelpEnvelope(cmd) {options,subcommands,},+ meta: {answeredBy: answeredBy()},};}diff --git a/packages/cli/clients/cli/lib/manifest.d.ts b/packages/cli/clients/cli/lib/manifest.d.tsindex c783816c25..77bca46b6d 100644--- a/packages/cli/clients/cli/lib/manifest.d.ts+++ b/packages/cli/clients/cli/lib/manifest.d.ts@@ -50,6 +50,13 @@ export interface ManifestCommand {examples?: string[];/** Documented exit codes: the process exit status and when it occurs. */exitCodes?: {code: number; when: string}[];+ /**+ * What the command does in a folder outside any project: `same` gives the+ * answer it gives in a new project; `refuse` writes nothing and fails, naming+ * the app project or integration package it needs; `own` does something+ * else, which its docs state. Absent on a group that only holds subcommands.+ */+ outsideProject?: 'same' | 'refuse' | 'own';/** Nested subcommands (e.g. `theme build` under `theme`). */subcommands?: ManifestCommand[];}@@ -64,6 +71,8 @@ export interface CLIManifest {commands: ManifestCommand[];/** Sorted list of fully-qualified command names that support `--json`. */jsonSupported: string[];+ /** What a run may do beyond its command (the hand-off, the daily update check, the agent skill), and the docs topic that explains it. */+ globalMode: {docs: string; summary: string};/** Flat index of response `type` discriminators keyed by command name. */responseTypes: Record<string, string[]>;}diff --git a/packages/cli/clients/cli/lib/manifest.mjs b/packages/cli/clients/cli/lib/manifest.mjsindex f475515267..b9784fd2dc 100644--- a/packages/cli/clients/cli/lib/manifest.mjs+++ b/packages/cli/clients/cli/lib/manifest.mjs@@ -9,7 +9,8 @@** Its per-command facts come from the command's own definitions: names,* arguments and options from Commander metadata (program.commands, cmd.options,- * cmd.registeredArguments, cmd.description()); examples from its CommandDoc;+ * cmd.registeredArguments, cmd.description()); examples, exit codes, and what+ * it does outside a project from its CommandDoc;* response `type` discriminators from the returns of the FunctionDoc it wraps* (both attached by `defineCommand`); `--json` support from the JSON_SUPPORTED* allowlist in index.mjs. The hand-kept lists are CLI_LAYER_RESPONSE_TYPES,@@ -39,6 +40,16 @@ import {API_VERSION} from '../../../foundation/response/json.mjs';import {commandDocsOf} from './define-command.mjs';import {doc as manifestDoc} from '../commands/manifest.doc.mjs';+/**+ * What a run may do beyond the command it was asked for (spec AST-081;+ * `spec:AST-017` FR14), and where it is explained.+ */+export const GLOBAL_MODE = Object.freeze({+ docs: 'astryx docs global',+ summary:+ "In a folder that belongs to a project, the project's own CLI answers: this copy hands the run to it. In a project with no CLI of its own, and outside any project, this copy answers. A copy installed for the computer checks the registry for a newer release once a day in the background, and keeps one agent skill file in the home folder.",+});+/*** Envelopes the CLI layer builds itself, so the wrapped FunctionDoc cannot* declare them: `manifest` wraps no API function, `theme build` batches several@@ -194,6 +205,10 @@ function describeCommand(cmd, root, jsonSupported) {}));if (exitCodes.length > 0) entry.exitCodes = exitCodes;+ // What the command does outside a project (spec AST-081 FR4). Every command+ // declares it in its CommandDoc; a group that only holds subcommands does not.+ if (docs?.doc.outsideProject) entry.outsideProject = docs.doc.outsideProject;+// Sort subcommands by name for a stable, agent-facing contract — the same// guarantee the top-level command list makes. Otherwise Commander// registration order leaks into the manifest and a pure reorder of@@ -265,6 +280,7 @@ export function buildManifest(program, opts = {}) {globalOptions: describeGlobalOptions(program),commands,jsonSupported: [...jsonSupported].sort(),+ globalMode: GLOBAL_MODE,// Flat index of every response `type` discriminator the CLI can emit,// keyed by command — lets an agent know what to expect back per call.responseTypes: Object.fromEntries(diff --git a/packages/cli/clients/cli/lib/manifest.test.mjs b/packages/cli/clients/cli/lib/manifest.test.mjsindex b2d1f2f511..7cf06ed7ed 100644--- a/packages/cli/clients/cli/lib/manifest.test.mjs+++ b/packages/cli/clients/cli/lib/manifest.test.mjs@@ -307,3 +307,28 @@ describe('manifest: text projection', () => {for (const key of textKeys) expect(jsonKeys).toContain(key);});});++describe('global mode is discoverable (spec:AST-017 FR14)', () => {+ it('the manifest names what a run may do beyond its command, and the docs topic that explains it', () => {+ expect(manifest.globalMode.docs).toBe('astryx docs global');+ for (const word of ['hands the run', 'once a day', 'agent skill']) {+ expect(manifest.globalMode.summary).toContain(word);+ }+ });++ it('--help carries one line pointing to the global mode docs', () => {+ const help = program.helpInformation() + '';+ let after = '';+ program.emit('afterHelp', {+ error: false,+ write: (/** @type {string} */ s) => {+ after += s;+ },+ });+ const lines = `${help}${after}`+ .split('\n')+ .filter(line => line.startsWith('Global mode:'));+ expect(lines).toHaveLength(1);+ expect(lines[0]).toMatch(/docs global\.$/u);+ });+});diff --git a/packages/cli/foundation/agent-docs/agent-doc-state.mjs b/packages/cli/foundation/agent-docs/agent-doc-state.mjsindex 476fc8c690..007cdbf7fb 100644--- a/packages/cli/foundation/agent-docs/agent-doc-state.mjs+++ b/packages/cli/foundation/agent-docs/agent-doc-state.mjs@@ -135,15 +135,37 @@ function findRepositoryRoot(start) {}/**- * 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+ * The invocation the setup nudge falls back to when the CLI's picker+ * (`getCliInvocation`) cannot be loaded. Scoped package form+ * (`@astryxdesign/cli`) — always resolves to us, even before the CLI is+ * installed. npx with the unscoped name 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';+export const SETUP_INVOCATION = 'npx @astryxdesign/cli';++/**+ * The one-line next-step every setup layer prints. Kept here so layer 1+ * (core), layer 2 (cli postinstall) and layer 3 (each command) can never word+ * it differently. Each layer passes the stem from the CLI's picker when it can+ * load it.+ *+ * @param {string} [invocation] the CLI invocation stem, e.g. `pnpm exec astryx`+ * @param {{before?: string | null}} [options] `before`: a command to run+ * first, such as the one that adds the CLI to a project that has none+ * @returns {string}+ */+export function setupNudge(+ invocation = SETUP_INVOCATION,+ {before = null} = {},+) {+ const run = before+ ? `\`${before}\`, then \`${invocation} init\``+ : `\`${invocation} init\``;+ return `\nNext step: run ${run} to finish setup and install the Astryx agent prompt.\n\n`;+}++/** The nudge with the fallback invocation. */+export const SETUP_NUDGE = setupNudge();/*** Pure decision: should a postinstall print the setup nudge? Shared by BOTHdiff --git a/packages/cli/foundation/agent-docs/agent-docs.mjs b/packages/cli/foundation/agent-docs/agent-docs.mjsindex fb657cefb9..e75beccc70 100644--- a/packages/cli/foundation/agent-docs/agent-docs.mjs+++ b/packages/cli/foundation/agent-docs/agent-docs.mjs@@ -379,7 +379,7 @@ export function detectStylingSystem(targetDir) {* among them. An agent cannot ask for a topic it was never told about, and* `getting-started` is the one it should reach for first.*- * @param {string} version+ * @param {string | null} version the Core version* @param {{coreDir?: string|null, invocation?: string, stylingSystem?: 'stylex'|'tailwind'|'css', zh?: boolean, lang?: string, topics?: string[], agentDocs?: Array<{package: string, append: readonly string[]}>}} [options]* @returns {string}*/@@ -420,9 +420,9 @@ export function generateCompressedIndex(// Best-effort: component count is cosmetic; fall back to the default.}}-- // Header — state the CLI prefix once; commands below are shown as `astryx <cmd>`.lines.push(`Astryx v${version} · ${componentCount} components`);++ // State the CLI prefix once; commands below are shown as `astryx <cmd>`.lines.push(`CLI: run every command as \`${run} <cmd>\` (shown below as \`astryx ...\`).`,);diff --git a/packages/cli/foundation/agent-docs/computer-agent-text.mjs b/packages/cli/foundation/agent-docs/computer-agent-text.mjsnew file mode 100644index 0000000000..188c71455c--- /dev/null+++ b/packages/cli/foundation/agent-docs/computer-agent-text.mjs@@ -0,0 +1,623 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file The computer-level agent text (spec AST-081 FR8): one skill file,+ * `~/.agents/skills/astryx/SKILL.md`, which most coding agents read, linked+ * into the skill folder of each agent that reads only its own+ * (`SKILL_LINKS`), so every agent on the computer knows Astryx is there.+ *+ * - One file is written. Each other folder gets a link to its folder: a+ * directory symlink, or a junction on Windows, which needs no+ * administrator rights. A refresh rewrites only the file; the links follow.+ * - `SKILL_LINKS` is the one table of link targets: a folder relative to the+ * home folder, and the folder that must already exist for it to be linked+ * (`null`: always). The writer, the remover, doctor, and the docs all read it.+ * - The text is version-free and names only stable entry points+ * (`STABLE_COMMANDS`), so an older file never misleads. It is short: the+ * skill only has to say that Astryx is here, when to use it, and where to+ * start; the CLI's own docs carry the rest.+ * - The file keeps the Astryx markers, which tell a file Astryx wrote from one+ * a person wrote, and records inside them a hash of its text, which tells an+ * edited file from an older rendering. A file without the markers, an+ * edited file, and a symlinked file are never changed. A link target that+ * holds anything Astryx did not create is never replaced; doctor names it.+ * - The links Astryx made are recorded in the settings file, so removal+ * removes exactly those.+ *+ * `astryx init --user` writes and removes them, and the global copy's+ * background step (`foundation/release/agent-text-worker.mjs`) keeps the file+ * on its release (FR7, FR8). Both honor the settings file+ * (`foundation/env/user-settings.mjs`). This module names fixed paths in the+ * home folder and nothing else.+ *+ * @input the home folder, the host's door (if any), the settings file+ * @output the rendered text, its state on disk, and the write/remove receipt rows+ * @position foundation/agent-docs — read by `init --user`, by the background+ * step, and by `doctor`.+ */++import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {createHash} from 'node:crypto';+import {cliDoor} from '../env/cli-command.mjs';+import {astryxCommandsOnSearchPath} from '../env/search-path.mjs';+import {samePath} from '../fs/path-compare.mjs';+import {MARKER_START, MARKER_END} from './agent-doc-state.mjs';++/** The command the computer-level text uses when no host door is set. */+export const COMPUTER_COMMAND = 'astryx';++/** The install step for the CLI copy the computer-level text relies on. */+export const COMPUTER_INSTALL_STEP = 'npm i -g @astryxdesign/cli';++/** The skill folder, relative to the home folder, that holds the one file. */+const SKILL_FOLDER = path.join('.agents', 'skills', 'astryx');++/**+ * Where the skill folder reaches agents that read only their own skills+ * folder, each relative to the home folder: the agent's skills folder, the+ * folder that must already exist for it to be used (`null`: always), and how:+ * `link`, a folder link to the skill folder with a relative target, or `copy`,+ * a managed copy of the file for an agent whose scanner skips links. Public+ * agents only. Never a store another tool manages, such as `~/.codex/skills`.+ * @type {ReadonlyArray<{skills: string, when: string | null, mode: 'link' | 'copy'}>}+ */+export const SKILL_LINKS = Object.freeze([+ {skills: path.join('.claude', 'skills'), when: null, mode: 'link'},+ {skills: path.join('.kiro', 'skills'), when: '.kiro', mode: 'link'},+ {+ skills: path.join('.codeium', 'windsurf', 'skills'),+ when: path.join('.codeium', 'windsurf'),+ mode: 'link',+ },+ {skills: path.join('.letta', 'skills'), when: '.letta', mode: 'link'},+ {+ skills: path.join(+ 'Library',+ 'Developer',+ 'Xcode',+ 'CodingAssistant',+ 'ClaudeAgentConfig',+ 'skills',+ ),+ when: path.join('Library', 'Developer', 'Xcode', 'CodingAssistant'),+ mode: 'link',+ },+ // Kimi reads only the first of `~/.config/agents/skills` and+ // `~/.agents/skills` that exists.+ {+ skills: path.join('.config', 'agents', 'skills'),+ when: path.join('.config', 'agents', 'skills'),+ mode: 'link',+ },+ {skills: path.join('.continue', 'skills'), when: '.continue', mode: 'copy'},+]);++/**+ * The commands the text may name: stable entry points every release keeps.+ * computer-agent-text.test.mjs fails on any other.+ */+export const STABLE_COMMANDS = Object.freeze([+ 'search',+ 'docs',+ 'component',+ 'template',+ 'build',+ 'theme',+ 'init',+ 'doctor',+ 'help',+]);++/**+ * When an agent should load the skill; the frontmatter `description`. One+ * sentence.+ */+const SKILL_DESCRIPTION =+ 'Astryx, a design system and UI library, is available on this computer through the astryx command; use it when building or changing UI, choosing components, layout, styling or theming, working with a design system, or in any project that depends on @astryxdesign packages or mentions Astryx.';++/**+ * A home-folder path as a person reads it: `~/.claude/skills/astryx`.+ * @param {string} file+ * @param {string} [home]+ * @returns {string}+ */+export function displayHomePath(file, home = os.homedir()) {+ const rel = path.relative(home, file);+ return rel && !rel.startsWith('..') && !path.isAbsolute(rel)+ ? `~${path.sep}${rel}`+ : file;+}++/**+ * The skill file's absolute path.+ * @param {string} [home]+ * @returns {string}+ */+export function computerSkillFile(home = os.homedir()) {+ return path.join(home, SKILL_FOLDER, 'SKILL.md');+}++/**+ * The absolute path of each link the table names, and whether it is wanted+ * on this computer (its condition folder exists).+ * @param {string} [home]+ * @returns {Array<{path: string, wanted: boolean, mode: 'link' | 'copy'}>}+ */+export function computerSkillLinks(home = os.homedir()) {+ return SKILL_LINKS.map(({skills, when, mode}) => ({+ path: path.join(home, skills, 'astryx'),+ wanted: when == null || fs.existsSync(path.join(home, when)),+ mode,+ }));+}++/**+ * The command the computer-level text tells agents to run: the host's door+ * when one started this run, else `astryx`. An integration's `cliCommand`+ * never applies: no project, so no integration, is in scope.+ * @returns {string}+ */+export function computerAgentCommand() {+ return cliDoor() ?? COMPUTER_COMMAND;+}++/**+ * The body lines, with `run` as the command.+ * @param {string} run+ * @returns {string[]}+ */+function bodyLines(run) {+ return [+ 'Astryx, a design system and UI library, is available on this computer.',+ 'Use it when you build or change UI, pick components, or style or theme an app.',+ `Its docs, components, templates, and themes are all reachable through \`${run}\`. Start with \`${run} search '<what you need>'\`.`,+ `Then read \`${run} component <Name>\` or \`${run} docs <topic>\`, not the package's files.`,+ "In a project, the project's version of Astryx answers automatically.",+ ];+}++/**+ * The full skill file.+ * @param {{command?: string}} [options]+ * @returns {string}+ */+export function renderComputerAgentText({+ command = computerAgentCommand(),+} = {}) {+ return withHash(+ [+ '---',+ 'name: astryx',+ // Quoted: the description holds `: ` and `;`, which strict YAML parsers+ // can misread, and an agent tool that fails to parse drops the skill.+ `description: ${JSON.stringify(SKILL_DESCRIPTION)}`,+ '---',+ '',+ MARKER_START,+ ...bodyLines(command),+ MARKER_END,+ '',+ ].join('\n'),+ );+}++/** The line, right after the start marker, that records the file's hash. */+const HASH_LINE = /^<!-- astryx-managed sha256:([0-9a-f]{64}) -->\n/mu;++/**+ * The sha256 of a file's text without its hash line.+ * @param {string} text+ * @returns {string}+ */+function hashOf(text) {+ return createHash('sha256').update(text).digest('hex');+}++/**+ * Insert the hash line after the start marker.+ * @param {string} text a rendering without a hash line+ * @returns {string}+ */+function withHash(text) {+ const at = text.indexOf(MARKER_START);+ if (at === -1) return text;+ const lineEnd = text.indexOf('\n', at);+ const cut = lineEnd === -1 ? text.length : lineEnd + 1;+ return `${text.slice(0, cut)}<!-- astryx-managed sha256:${hashOf(text)} -->\n${text.slice(cut)}`;+}++/**+ * Whether a file with the markers is unedited: it carries a hash line, and+ * the hash matches the rest of its text.+ * @param {string} content+ * @returns {boolean}+ */+function isUnedited(content) {+ const match = HASH_LINE.exec(content);+ if (!match) return false;+ return hashOf(content.replace(HASH_LINE, '')) === match[1];+}++/**+ * What is at one path of the computer-level text.+ * - `absent`: nothing there.+ * - `current`: an Astryx file with exactly this release's rendering.+ * - `differs`: an unedited Astryx file (its recorded hash matches) with+ * another rendering, such as another release's.+ * - `edited`: an Astryx file (it has the markers) whose text no longer+ * matches its recorded hash, or that records none: a person changed it.+ * Never changed.+ * - `foreign`: a file without the Astryx markers, a symlink, or something+ * other than a regular file. Never changed.+ * - `linked`, `dangling` (a link only): a link to the skill folder, or one+ * whose folder is missing (see linkStateOf).+ * @typedef {'absent' | 'current' | 'differs' | 'edited' | 'foreign' | 'linked' | 'dangling'} ComputerAgentTextState+ */++/**+ * @param {string} content+ * @returns {boolean}+ */+function hasMarkers(content) {+ const start = content.indexOf(MARKER_START);+ return start !== -1 && content.indexOf(MARKER_END, start) !== -1;+}++/**+ * The state of one path, read without following a symlinked file.+ * @param {string} file+ * @param {string} expected+ * @returns {ComputerAgentTextState}+ */+function stateOf(file, expected) {+ /** @type {fs.Stats} */+ let stat;+ try {+ stat = fs.lstatSync(file);+ } catch {+ return 'absent';+ }+ if (!stat.isFile()) return 'foreign';+ let content;+ try {+ content = fs.readFileSync(file, 'utf8');+ } catch {+ return 'foreign';+ }+ if (!hasMarkers(content)) return 'foreign';+ if (content === expected) return 'current';+ return isUnedited(content) ? 'differs' : 'edited';+}++/**+ * The state of one link target.+ * - `linked`: a link to the skill folder.+ * - `dangling`: a link to the skill folder, which is not there, as in a+ * container that mounts only the agent's own folder.+ * - `absent`: nothing there.+ * - `differs`: a real folder holding only an unedited Astryx skill file, as a+ * copy left it; replaced by the link.+ * - `foreign`: anything else. Never changed.+ * @param {string} at+ * @param {string} folder the skill folder+ * @returns {ComputerAgentTextState}+ */+function linkStateOf(at, folder) {+ /** @type {fs.Stats} */+ let stat;+ try {+ stat = fs.lstatSync(at);+ } catch {+ return 'absent';+ }+ if (stat.isSymbolicLink()) {+ const leads = pointsAt(at, folder);+ if (leads == null) return 'foreign';+ // A link the system cannot follow to the folder is broken, whatever its+ // text says.+ if (leads === 'names') return 'dangling';+ return fs.existsSync(path.join(folder, 'SKILL.md')) ? 'linked' : 'dangling';+ }+ if (!stat.isDirectory()) return 'foreign';+ return copyStateOf(at, '') === 'differs' ? 'differs' : 'foreign';+}++/**+ * The state of a managed copy: a real folder at `at` holding only the skill+ * file, read like the skill file itself.+ * @param {string} at+ * @param {string} expected+ * @returns {ComputerAgentTextState}+ */+function copyStateOf(at, expected) {+ /** @type {fs.Stats} */+ let stat;+ try {+ stat = fs.lstatSync(at);+ } catch {+ return 'absent';+ }+ if (!stat.isDirectory()) return 'foreign';+ let names;+ try {+ names = fs.readdirSync(at);+ } catch {+ return 'foreign';+ }+ if (names.length === 0) return 'absent';+ if (names.length !== 1 || names[0] !== 'SKILL.md') return 'foreign';+ const state = stateOf(path.join(at, 'SKILL.md'), expected);+ return state === 'current' && expected === '' ? 'differs' : state;+}++/**+ * Where the link at `at` leads `folder`'s way, as the system follows it: a+ * relative target resolves from the folder the link really sits in, which+ * differs from its path when a folder above it is itself a link (such as+ * `~/.claude` linked to a dotfiles folder). `reaches`: the system reaches+ * `folder` (which may be missing). `names`: only the target's text, read from+ * the link's path, names `folder`, as a link an earlier release made under a+ * linked folder does; the system cannot follow it. Otherwise null.+ * @param {string} at+ * @param {string} folder+ * @returns {'reaches' | 'names' | null}+ */+function pointsAt(at, folder) {+ try {+ const text = fs.readlinkSync(at);+ const followed = path.resolve(realPath(path.dirname(at)), text);+ const wanted = realPath(folder);+ if (samePath(followed.replace(/[\\/]+$/u, ''), wanted)) return 'reaches';+ const named = path.resolve(path.dirname(at), text);+ return samePath(named.replace(/[\\/]+$/u, ''), folder) ? 'names' : null;+ } catch {+ return null;+ }+}++/**+ * `p` with every link in it resolved, as far as it exists: a missing tail is+ * kept as written.+ * @param {string} p+ * @returns {string}+ */+function realPath(p) {+ try {+ return fs.realpathSync(p);+ } catch {+ const parent = path.dirname(p);+ return parent === p ? p : path.join(realPath(parent), path.basename(p));+ }+}++/**+ * Read-only: the state of the skill file against this release's rendering,+ * then of each place the table wants on this computer, or that Astryx linked.+ * @param {{home?: string, command?: string, links?: readonly string[]}} [options]+ * `links`: the links Astryx made, from the settings file+ * @returns {Array<{path: string, state: ComputerAgentTextState, link?: true}>}+ */+export function inspectComputerAgentText({+ home = os.homedir(),+ command,+ links = [],+} = {}) {+ const expected = renderComputerAgentText({command});+ const folder = path.join(home, SKILL_FOLDER);+ const made = new Set(links);+ return [+ {+ path: computerSkillFile(home),+ state: stateOf(computerSkillFile(home), expected),+ },+ ...computerSkillLinks(home)+ .filter(place => place.wanted || made.has(place.path))+ .map(place => {+ const linkState = linkStateOf(place.path, folder);+ const state =+ place.mode === 'copy' && linkState !== 'linked'+ ? copyStateOf(place.path, expected)+ : linkState;+ return {path: place.path, state, link: /** @type {const} */ (true)};+ }),+ ];+}++/**+ * Write `content` to `file` without following a symlink planted at it.+ * @param {string} file+ * @param {string} content+ */+function writeNoFollow(file, content) {+ const flags =+ fs.constants.O_WRONLY |+ fs.constants.O_CREAT |+ fs.constants.O_TRUNC |+ (fs.constants.O_NOFOLLOW ?? 0);+ const fd = fs.openSync(file, flags, 0o644);+ try {+ fs.writeFileSync(fd, content);+ } finally {+ fs.closeSync(fd);+ }+}++/**+ * Why a path was kept: a person edited it, or Astryx did not create it.+ * @param {ComputerAgentTextState} state+ * @returns {'edited' | 'not-astryx'}+ */+const keptReason = state => (state === 'edited' ? 'edited' : 'not-astryx');++/**+ * Remove an unedited Astryx file, or a folder holding only one, and its+ * emptied folder.+ * @param {string} file+ */+function removeFile(file) {+ fs.unlinkSync(file);+ try {+ fs.rmdirSync(path.dirname(file));+ } catch {+ // The folder holds something else; leave it.+ }+}++/**+ * Link `at` to `folder`: a folder symlink with a relative target, which+ * survives a moved or synced home folder, or a junction (absolute) on Windows.+ * The target is relative to the folder the link really sits in, because the+ * system resolves it from there: with `~/.claude` linked to+ * `~/dotfiles/.claude`, a target worked out from `~/.claude/skills` would+ * dangle. With no common base between the two, the target is absolute.+ * @param {string} at+ * @param {string} folder+ */+function makeLink(at, folder) {+ fs.mkdirSync(path.dirname(at), {recursive: true});+ if (process.platform === 'win32') {+ fs.symlinkSync(folder, at, 'junction');+ return;+ }+ const realFolder = fs.realpathSync(folder);+ const relative = path.relative(fs.realpathSync(path.dirname(at)), realFolder);+ fs.symlinkSync(path.isAbsolute(relative) ? realFolder : relative, at, 'dir');+}++/**+ * Write or refresh a managed copy of the skill file in the folder `at`.+ * @param {string} at+ * @param {string} expected+ * @returns {import('../../api/init/init.type.mjs').InitUserFile}+ */+function writeCopy(at, expected) {+ const state = copyStateOf(at, expected);+ if (state === 'current') return {path: at, action: 'unchanged'};+ if (state === 'foreign' || state === 'edited') {+ return {path: at, action: 'kept', reason: keptReason(state)};+ }+ try {+ fs.mkdirSync(at, {recursive: true});+ writeNoFollow(path.join(at, 'SKILL.md'), expected);+ return {path: at, action: 'written'};+ } catch {+ return {path: at, action: 'kept', reason: 'not-astryx'};+ }+}++/**+ * Write or refresh the skill file, and link it into every folder the table+ * wants on this computer. A file without the Astryx markers, an edited one, a+ * symlinked one, and a link target holding anything Astryx did not create are+ * kept as they are. Returns the receipt rows and the links that now point at+ * the skill folder, for the settings file.+ * @param {{home?: string, command?: string}} [options]+ * @returns {{rows: import('../../api/init/init.type.mjs').InitUserFile[], links: string[]}}+ */+export function writeComputerAgentText({home = os.homedir(), command} = {}) {+ const expected = renderComputerAgentText({command});+ const file = computerSkillFile(home);+ const folder = path.dirname(file);+ /** @type {import('../../api/init/init.type.mjs').InitUserFile[]} */+ const rows = [];+ const state = stateOf(file, expected);+ if (state === 'foreign' || state === 'edited') {+ rows.push({path: file, action: 'kept', reason: keptReason(state)});+ } else if (state === 'current') {+ rows.push({path: file, action: 'unchanged'});+ } else {+ fs.mkdirSync(folder, {recursive: true});+ writeNoFollow(file, expected);+ rows.push({path: file, action: 'written'});+ }+ /** @type {string[]} */+ const links = [];+ for (const place of computerSkillLinks(home)) {+ if (!place.wanted) continue;+ const at = place.path;+ const linkState = linkStateOf(at, folder);+ if (linkState === 'linked') {+ links.push(at);+ rows.push({path: at, action: 'unchanged'});+ continue;+ }+ if (place.mode === 'copy') {+ rows.push(writeCopy(at, expected));+ continue;+ }+ if (linkState === 'foreign') {+ rows.push({path: at, action: 'kept', reason: 'not-astryx'});+ continue;+ }+ if (linkState === 'differs') removeFile(path.join(at, 'SKILL.md'));+ // The skill folder exists now, so a link still dangling here is one+ // whose target the system resolves from a linked folder above it: an+ // Astryx link, remade so that it resolves.+ if (linkState === 'dangling') fs.unlinkSync(at);+ try {+ makeLink(at, folder);+ links.push(at);+ rows.push({path: at, action: 'linked'});+ } catch {+ // A folder link that cannot be made (Windows without a junction, a+ // file system without links) gets a managed copy instead.+ rows.push(writeCopy(at, expected));+ }+ }+ return {rows, links};+}++/**+ * Remove the skill file and every link Astryx made that still points at its+ * folder. A file without the Astryx markers, an edited one, or a symlinked+ * one, and any link Astryx did not make, are kept.+ * @param {{home?: string, links?: readonly string[]}} [options]+ * @returns {import('../../api/init/init.type.mjs').InitUserFile[]}+ */+export function removeComputerAgentText({+ home = os.homedir(),+ links = [],+} = {}) {+ const file = computerSkillFile(home);+ const folder = path.dirname(file);+ /** @type {import('../../api/init/init.type.mjs').InitUserFile[]} */+ const rows = [];+ for (const at of links) {+ const linkState = linkStateOf(at, folder);+ if (linkState !== 'linked' && linkState !== 'dangling') continue;+ try {+ fs.unlinkSync(at);+ rows.push({path: at, action: 'removed'});+ } catch {+ rows.push({path: at, action: 'kept', reason: 'not-astryx'});+ }+ }+ // Managed copies are told apart by their markers and hash, like the file.+ for (const place of computerSkillLinks(home)) {+ if (copyStateOf(place.path, '') !== 'differs') continue;+ removeFile(path.join(place.path, 'SKILL.md'));+ rows.push({path: place.path, action: 'removed'});+ }+ const state = stateOf(file, '');+ if (state === 'absent') {+ rows.unshift({path: file, action: 'absent'});+ } else if (state === 'foreign' || state === 'edited') {+ rows.unshift({path: file, action: 'kept', reason: keptReason(state)});+ } else {+ removeFile(file);+ rows.unshift({path: file, action: 'removed'});+ }+ return rows;+}++/**+ * Whether the `astryx` a shell would run from this computer's search path is+ * the Astryx CLI: the first `astryx` found is the one that runs.+ * @param {{searchPath?: string, platform?: NodeJS.Platform}} [options]+ * @returns {boolean}+ */+export function astryxOnSearchPath(options = {}) {+ return astryxCommandsOnSearchPath(options)[0]?.astryx ?? false;+}diff --git a/packages/cli/foundation/agent-docs/computer-agent-text.test.mjs b/packages/cli/foundation/agent-docs/computer-agent-text.test.mjsnew file mode 100644index 0000000000..6adaacc21d--- /dev/null+++ b/packages/cli/foundation/agent-docs/computer-agent-text.test.mjs@@ -0,0 +1,602 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file The computer-level agent text (spec AST-081 FR7, FR8): its two+ * renderings, version-free and naming only stable commands; the one file it+ * writes and the links it makes from the one table; what it keeps; exact+ * removal; the search-path check behind its warning; and the rule that only+ * `init --user` and the background step write it. Every test uses a temporary+ * home folder.+ */++import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {spawnSync} from 'node:child_process';+import {createHash} from 'node:crypto';+import {fileURLToPath} from 'node:url';+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import {+ SKILL_LINKS,+ STABLE_COMMANDS,+ astryxOnSearchPath,+ computerSkillFile,+ computerSkillLinks,+ inspectComputerAgentText,+ removeComputerAgentText,+ renderComputerAgentText,+ writeComputerAgentText,+} from './computer-agent-text.mjs';+import {MARKER_END, MARKER_START} from './agent-doc-state.mjs';+import {runWithCliDoor} from '../env/cli-command.mjs';+import {runCli} from '../../test-utils/run-cli.mjs';+import {parse as parseYaml} from 'yaml';++const HERE = path.dirname(fileURLToPath(import.meta.url));+const CLI_ROOT = path.resolve(HERE, '../..');+const CORE_ROOT = path.resolve(CLI_ROOT, '../core');++/**+ * An Astryx file as some other release would write it: the given text with+ * its hash line recorded.+ * @param {string} text+ * @returns {string}+ */+function unedited(text) {+ const hash = createHash('sha256').update(text).digest('hex');+ return text.replace(+ `${MARKER_START}\n`,+ `${MARKER_START}\n<!-- astryx-managed sha256:${hash} -->\n`,+ );+}++/** @type {string[]} */+const dirs = [];+/** @param {string} label */+function tmp(label) {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), `astryx-user-${label}-`));+ dirs.push(dir);+ return dir;+}++let home = '';+beforeEach(() => {+ home = tmp('home');+ vi.stubEnv('HOME', home);+ vi.stubEnv('USERPROFILE', home);+});+afterEach(() => {+ vi.unstubAllEnvs();+ while (dirs.length) {+ fs.rmSync(/** @type {string} */ (dirs.pop()), {+ recursive: true,+ force: true,+ });+ }+});++const FILE = () => computerSkillFile(home);+const FOLDER = () => path.dirname(FILE());+const CLAUDE = () => path.join(home, '.claude', 'skills', 'astryx');++/** @param {string} at */+const isLinkToFolder = at =>+ fs.lstatSync(at).isSymbolicLink() &&+ fs.realpathSync(at) === fs.realpathSync(FOLDER());++describe('renderComputerAgentText', () => {+ it('a skill named astryx with a one-sentence when-to-use description, in strict YAML', () => {+ {+ const text = renderComputerAgentText({command: 'astryx'});+ const [, front] = text.split('---\n');+ const meta = parseYaml(front);+ expect(meta.name).toBe('astryx');+ expect(meta.description).toMatch(/design system and UI library/);+ expect(meta.description).toMatch(/building or changing UI/);+ expect(meta.description).toMatch(/@astryxdesign/);+ expect(+ meta.description.split(/[.!?](\s|$)/u).filter(Boolean),+ ).toHaveLength(1);+ expect(text).toContain(MARKER_START);+ expect(text).toContain(MARKER_END);+ expect(text).toContain(+ 'Astryx, a design system and UI library, is available on this computer.',+ );+ expect(text).toContain(+ 'Use it when you build or change UI, pick components, or style or theme an app.',+ );+ expect(text).toContain("Start with `astryx search '<what you need>'`.");+ }+ });++ it('is version-free and names only stable commands', () => {+ {+ const text = renderComputerAgentText({command: 'astryx'});+ // No version string anywhere: not a release, a Node range, or a tag.+ expect(text).not.toMatch(/\bv?\d+\.\d+(\.\d+)?\b/u);+ expect(text).not.toMatch(/@(latest|next|canary)\b/u);+ const commands = [...text.matchAll(/`astryx ([a-z-]+)/gu)].map(m => m[1]);+ expect(commands.length).toBeGreaterThan(0);+ expect(commands.filter(c => !STABLE_COMMANDS.includes(c))).toEqual([]);+ }+ });++ it('stays short, and tells agents to read docs through the CLI', () => {+ const text = renderComputerAgentText({command: 'astryx'});+ expect(text.split('\n').length).toBeLessThanOrEqual(15);+ expect(text).toContain(+ "Then read `astryx component <Name>` or `astryx docs <topic>`, not the package's files.",+ );+ });++ it("uses the host's door when one is set", () => {+ const text = runWithCliDoor('acme astryx', () => renderComputerAgentText());+ expect(text).toContain("`acme astryx search '<what you need>'`");+ expect(text).not.toMatch(/`astryx /u);+ });+});++describe('the link table', () => {+ it('is data: each entry names a skills folder, the folder it needs, and link or copy; Claude Code always', () => {+ expect(SKILL_LINKS[0]).toEqual({+ skills: path.join('.claude', 'skills'),+ when: null,+ mode: 'link',+ });+ for (const place of SKILL_LINKS) {+ expect(path.isAbsolute(place.skills)).toBe(false);+ expect(place.skills.endsWith('skills')).toBe(true);+ expect(['link', 'copy']).toContain(place.mode);+ }+ // Continue's scanner skips links, so it is the one copy.+ expect(+ SKILL_LINKS.filter(p => p.mode === 'copy').map(p => p.skills),+ ).toEqual([path.join('.continue', 'skills')]);+ // Never a store another tool manages.+ for (const place of SKILL_LINKS) {+ expect(place.skills).not.toBe(path.join('.codex', 'skills'));+ expect(place.skills).not.toBe(path.join('.config', 'muse', 'skills'));+ }+ expect(computerSkillLinks(home).map(l => l.wanted)).toEqual(+ SKILL_LINKS.map(l => l.when == null),+ );+ });+});++describe('links and the copy', () => {+ it.skipIf(process.platform === 'win32')(+ 'links with a relative target',+ () => {+ writeComputerAgentText({home, command: 'astryx'});+ expect(fs.readlinkSync(CLAUDE())).toBe(+ path.join('..', '..', '.agents', 'skills', 'astryx'),+ );+ },+ );++ it('links ~/.config/agents/skills only when that folder already exists', () => {+ const kimi = path.join(home, '.config', 'agents', 'skills');+ expect(writeComputerAgentText({home, command: 'astryx'}).links).toEqual([+ CLAUDE(),+ ]);+ fs.mkdirSync(kimi, {recursive: true});+ expect(writeComputerAgentText({home, command: 'astryx'}).links).toEqual([+ CLAUDE(),+ path.join(kimi, 'astryx'),+ ]);+ });++ it('writes, refreshes, and removes a managed copy for Continue, whose scanner skips links', () => {+ fs.mkdirSync(path.join(home, '.continue'));+ const copy = path.join(home, '.continue', 'skills', 'astryx');+ const {rows, links} = writeComputerAgentText({home, command: 'astryx'});+ expect(rows).toContainEqual({path: copy, action: 'written'});+ expect(links).not.toContain(copy);+ expect(fs.lstatSync(copy).isSymbolicLink()).toBe(false);+ expect(fs.readFileSync(path.join(copy, 'SKILL.md'), 'utf8')).toBe(+ fs.readFileSync(FILE(), 'utf8'),+ );+ expect(+ writeComputerAgentText({home, command: 'astryx'}).rows,+ ).toContainEqual({+ path: copy,+ action: 'unchanged',+ });+ expect(removeComputerAgentText({home, links})).toContainEqual({+ path: copy,+ action: 'removed',+ });+ expect(fs.existsSync(copy)).toBe(false);+ });++ it.skipIf(process.platform === 'win32')(+ 'links from a ~/.claude that is itself a link to a dotfiles folder, with a target that resolves',+ () => {+ const dotfiles = path.join(home, 'dotfiles', '.claude');+ fs.mkdirSync(dotfiles, {recursive: true});+ fs.symlinkSync(dotfiles, path.join(home, '.claude'), 'dir');++ const {rows, links} = writeComputerAgentText({home, command: 'astryx'});++ expect(rows).toContainEqual({path: CLAUDE(), action: 'linked'});+ // The system resolves the link from the dotfiles folder, and it reaches+ // the skill folder.+ expect(isLinkToFolder(CLAUDE())).toBe(true);+ expect(fs.readFileSync(path.join(CLAUDE(), 'SKILL.md'), 'utf8')).toBe(+ fs.readFileSync(FILE(), 'utf8'),+ );+ expect(+ inspectComputerAgentText({home, command: 'astryx', links}),+ ).toContainEqual({+ path: CLAUDE(),+ state: 'linked',+ link: true,+ });+ },+ );++ it.skipIf(process.platform === 'win32')(+ 'reports a link the system cannot follow as dangling, even when its text names the folder from the path',+ () => {+ const dotfiles = path.join(home, 'dotfiles', '.claude');+ fs.mkdirSync(path.join(dotfiles, 'skills'), {recursive: true});+ fs.symlinkSync(dotfiles, path.join(home, '.claude'), 'dir');+ writeComputerAgentText({home, command: 'astryx'});+ // A link as 0.7.x wrote it: relative to ~/.claude/skills, which the+ // system reads from ~/dotfiles/.claude/skills, so it dangles.+ fs.rmSync(CLAUDE());+ fs.symlinkSync(+ path.relative(path.dirname(CLAUDE()), FOLDER()),+ CLAUDE(),+ 'dir',+ );+ expect(fs.existsSync(path.join(CLAUDE(), 'SKILL.md'))).toBe(false);++ const rows = inspectComputerAgentText({+ home,+ command: 'astryx',+ links: [CLAUDE()],+ });+ expect(rows.find(row => row.path === CLAUDE())?.state).toBe('dangling');+ // init --user remakes it so that it resolves.+ expect(+ writeComputerAgentText({home, command: 'astryx'}).rows,+ ).toContainEqual({+ path: CLAUDE(),+ action: 'linked',+ });+ expect(isLinkToFolder(CLAUDE())).toBe(true);+ },+ );++ it.skipIf(process.platform === 'win32')(+ 'writes the managed copy into a ~/.continue that is itself a link',+ () => {+ const real = path.join(home, 'dotfiles', '.continue');+ fs.mkdirSync(real, {recursive: true});+ fs.symlinkSync(real, path.join(home, '.continue'), 'dir');+ const copy = path.join(home, '.continue', 'skills', 'astryx');++ const {rows} = writeComputerAgentText({home, command: 'astryx'});++ expect(rows).toContainEqual({path: copy, action: 'written'});+ expect(+ fs.readFileSync(+ path.join(real, 'skills', 'astryx', 'SKILL.md'),+ 'utf8',+ ),+ ).toBe(fs.readFileSync(FILE(), 'utf8'));+ },+ );++ it('reports a link whose folder is missing as dangling', () => {+ const {links} = writeComputerAgentText({home, command: 'astryx'});+ fs.rmSync(FOLDER(), {recursive: true});+ expect(inspectComputerAgentText({home, command: 'astryx', links})).toEqual([+ {path: FILE(), state: 'absent'},+ {path: CLAUDE(), state: 'dangling', link: true},+ ]);+ });+});++describe('write, refresh, keep, remove', () => {+ it('writes one file, links Claude Code to its folder, then reports both unchanged', () => {+ const first = writeComputerAgentText({home, command: 'astryx'});+ expect(first.rows).toEqual([+ {path: FILE(), action: 'written'},+ {path: CLAUDE(), action: 'linked'},+ ]);+ expect(first.links).toEqual([CLAUDE()]);+ expect(isLinkToFolder(CLAUDE())).toBe(true);+ // An agent reading the linked folder reads the one file.+ expect(fs.readFileSync(path.join(CLAUDE(), 'SKILL.md'), 'utf8')).toBe(+ fs.readFileSync(FILE(), 'utf8'),+ );+ expect(writeComputerAgentText({home, command: 'astryx'}).rows).toEqual([+ {path: FILE(), action: 'unchanged'},+ {path: CLAUDE(), action: 'unchanged'},+ ]);+ });++ it("links another agent's folder only when that agent's folder exists", () => {+ fs.mkdirSync(path.join(home, '.kiro'));+ const {links} = writeComputerAgentText({home, command: 'astryx'});+ expect(links).toEqual([+ CLAUDE(),+ path.join(home, '.kiro', 'skills', 'astryx'),+ ]);+ expect(fs.existsSync(path.join(home, '.continue'))).toBe(false);+ });++ it('refreshes only the file; the links follow', () => {+ writeComputerAgentText({home, command: 'astryx'});+ fs.writeFileSync(+ FILE(),+ unedited(+ `---\nname: astryx\n---\n\n${MARKER_START}\nold\n${MARKER_END}\n`,+ ),+ );+ expect(inspectComputerAgentText({home, command: 'astryx'})[0].state).toBe(+ 'differs',+ );+ expect(writeComputerAgentText({home, command: 'astryx'}).rows).toEqual([+ {path: FILE(), action: 'written'},+ {path: CLAUDE(), action: 'unchanged'},+ ]);+ expect(fs.readFileSync(path.join(CLAUDE(), 'SKILL.md'), 'utf8')).toBe(+ renderComputerAgentText({command: 'astryx'}),+ );+ });++ it('keeps an edited file, a file without the markers, and anything at a link target Astryx did not create', () => {+ fs.mkdirSync(FOLDER(), {recursive: true});+ fs.writeFileSync(FILE(), 'my own notes\n');+ fs.mkdirSync(CLAUDE(), {recursive: true});+ fs.writeFileSync(path.join(CLAUDE(), 'SKILL.md'), 'my own skill\n');+ const {rows, links} = writeComputerAgentText({home, command: 'astryx'});+ expect(rows).toEqual([+ {path: FILE(), action: 'kept', reason: 'not-astryx'},+ {path: CLAUDE(), action: 'kept', reason: 'not-astryx'},+ ]);+ expect(links).toEqual([]);+ expect(fs.readFileSync(FILE(), 'utf8')).toBe('my own notes\n');+ expect(+ inspectComputerAgentText({home, command: 'astryx'}).map(e => e.state),+ ).toEqual(['foreign', 'foreign']);++ fs.writeFileSync(+ FILE(),+ `${renderComputerAgentText({command: 'astryx'})}edit\n`,+ );+ expect(writeComputerAgentText({home, command: 'astryx'}).rows[0]).toEqual({+ path: FILE(),+ action: 'kept',+ reason: 'edited',+ });+ });++ it('keeps a link that points somewhere else', () => {+ const elsewhere = tmp('elsewhere');+ fs.mkdirSync(path.dirname(CLAUDE()), {recursive: true});+ fs.symlinkSync(elsewhere, CLAUDE(), 'dir');+ const {rows} = writeComputerAgentText({home, command: 'astryx'});+ expect(rows[1]).toEqual({+ path: CLAUDE(),+ action: 'kept',+ reason: 'not-astryx',+ });+ expect(fs.realpathSync(CLAUDE())).toBe(fs.realpathSync(elsewhere));+ });++ it('replaces an unedited copy an earlier release left at a link target with the link', () => {+ fs.mkdirSync(CLAUDE(), {recursive: true});+ fs.writeFileSync(+ path.join(CLAUDE(), 'SKILL.md'),+ unedited(+ `---\nname: astryx\n---\n\n${MARKER_START}\nold\n${MARKER_END}\n`,+ ),+ );+ expect(writeComputerAgentText({home, command: 'astryx'}).rows[1]).toEqual({+ path: CLAUDE(),+ action: 'linked',+ });+ expect(isLinkToFolder(CLAUDE())).toBe(true);+ });++ it('removes the file and exactly the links it made, then reports the file absent', () => {+ const {links} = writeComputerAgentText({home, command: 'astryx'});+ // A link someone else made to the same folder is not Astryx's to remove.+ const theirs = path.join(home, 'mine', 'astryx');+ fs.mkdirSync(path.dirname(theirs), {recursive: true});+ fs.symlinkSync(FOLDER(), theirs, 'dir');+ expect(removeComputerAgentText({home, links})).toEqual([+ {path: FILE(), action: 'removed'},+ {path: CLAUDE(), action: 'removed'},+ ]);+ expect(fs.existsSync(CLAUDE())).toBe(false);+ expect(fs.existsSync(FOLDER())).toBe(false);+ expect(fs.lstatSync(theirs).isSymbolicLink()).toBe(true);+ expect(removeComputerAgentText({home, links: []})).toEqual([+ {path: FILE(), action: 'absent'},+ ]);+ });++ it('keeps an edited file on remove, and a recorded link someone repointed', () => {+ const {links} = writeComputerAgentText({home, command: 'astryx'});+ fs.unlinkSync(CLAUDE());+ fs.symlinkSync(tmp('other'), CLAUDE(), 'dir');+ fs.appendFileSync(FILE(), 'edit\n');+ expect(removeComputerAgentText({home, links})).toEqual([+ {path: FILE(), action: 'kept', reason: 'edited'},+ ]);+ expect(fs.existsSync(FILE())).toBe(true);+ expect(fs.lstatSync(CLAUDE()).isSymbolicLink()).toBe(true);+ });+});++describe.skipIf(process.platform === 'win32')('astryxOnSearchPath', () => {+ /** @param {string} file @param {string} content */+ function executable(file, content) {+ fs.mkdirSync(path.dirname(file), {recursive: true});+ fs.writeFileSync(file, content);+ fs.chmodSync(file, 0o755);+ }++ /** A global prefix with the CLI package linked into its bin folder. */+ function linkedCli() {+ const prefix = tmp('prefix');+ const pkg = path.join(+ prefix,+ 'lib',+ 'node_modules',+ '@astryxdesign',+ 'cli',+ );+ fs.mkdirSync(pkg, {recursive: true});+ fs.writeFileSync(+ path.join(pkg, 'package.json'),+ '{"name":"@astryxdesign/cli","version":"0.0.0"}',+ );+ executable(path.join(pkg, 'bin.mjs'), '#!/usr/bin/env node\n');+ fs.mkdirSync(path.join(prefix, 'bin'));+ fs.symlinkSync(+ path.join(pkg, 'bin.mjs'),+ path.join(prefix, 'bin', 'astryx'),+ );+ return path.join(prefix, 'bin');+ }++ it('finds a linked CLI', () => {+ expect(+ astryxOnSearchPath({searchPath: linkedCli(), platform: 'linux'}),+ ).toBe(true);+ });++ it("finds a package manager's shim that starts the CLI", () => {+ const bin = tmp('shim');+ executable(+ path.join(bin, 'astryx'),+ '#!/bin/sh\nexec node "$basedir/global/5/node_modules/@astryxdesign/cli/clients/cli/bin/astryx.mjs" "$@"\n',+ );+ expect(astryxOnSearchPath({searchPath: bin, platform: 'linux'})).toBe(true);+ });++ it('is false with no astryx, or when the first astryx is another program', () => {+ expect(+ astryxOnSearchPath({searchPath: tmp('empty'), platform: 'linux'}),+ ).toBe(false);+ const other = tmp('other');+ executable(path.join(other, 'astryx'), '#!/bin/sh\necho other\n');+ expect(+ astryxOnSearchPath({+ searchPath: [other, linkedCli()].join(path.delimiter),+ platform: 'linux',+ }),+ ).toBe(false);+ });++ it('skips a file that cannot run', () => {+ const bin = tmp('noexec');+ fs.writeFileSync(path.join(bin, 'astryx'), 'not a program');+ expect(+ astryxOnSearchPath({+ searchPath: [bin, linkedCli()].join(path.delimiter),+ platform: 'linux',+ }),+ ).toBe(true);+ });+});++describe('only `init --user` writes the computer-level text (FR7)', () => {+ /** @returns {string[]} the skill paths present in the temp home */+ const present = () =>+ [+ computerSkillFile(home),+ path.join(home, '.claude', 'skills', 'astryx'),+ ].filter(p => fs.existsSync(p));++ /** A project that installs this release's Core. */+ function project() {+ const dir = tmp('project');+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ JSON.stringify({+ name: 'app',+ private: true,+ dependencies: {'@astryxdesign/core': '*'},+ }),+ );+ fs.mkdirSync(path.join(dir, 'node_modules', '@astryxdesign'), {+ recursive: true,+ });+ fs.symlinkSync(+ CORE_ROOT,+ path.join(dir, 'node_modules', '@astryxdesign', 'core'),+ 'dir',+ );+ return dir;+ }++ it('no source outside init --user (its adapter) and the background step imports the write or remove functions', () => {+ /** @type {string[]} */+ const importers = [];+ /** @param {string} dir */+ const walk = dir => {+ for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {+ if (entry.name === 'node_modules' || entry.name.startsWith('.'))+ continue;+ const file = path.join(dir, entry.name);+ if (entry.isDirectory()) walk(file);+ else if (+ /\.m?[jt]s$/.test(entry.name) &&+ !/\.test\.m?[jt]s$/.test(entry.name) &&+ // Generated declarations (sync:api-types) import nothing.+ !/\.d\.m?ts$/.test(entry.name)+ ) {+ const text = fs.readFileSync(file, 'utf8');+ if (+ /\b(writeComputerAgentText|removeComputerAgentText)\b/.test(text)+ ) {+ importers.push(path.relative(CLI_ROOT, file));+ }+ }+ }+ };+ for (const top of [+ 'api',+ 'clients',+ 'foundation',+ 'scripts',+ 'authoring',+ ]) {+ walk(path.join(CLI_ROOT, top));+ }+ expect(importers.sort()).toEqual(+ [+ path.join('api', 'init', '_adapter.mjs'),+ path.join('foundation', 'agent-docs', 'computer-agent-text.mjs'),+ path.join('foundation', 'release', 'agent-text-worker.mjs'),+ ].sort(),+ );+ });++ it('install (postinstall), project init, and upgrade write none of it', async () => {+ const dir = project();+ const postinstall = spawnSync(+ process.execPath,+ [path.join(CLI_ROOT, 'scripts', 'postinstall.mjs')],+ {+ env: {...process.env, HOME: home, USERPROFILE: home, INIT_CWD: dir},+ encoding: 'utf8',+ },+ );+ expect(postinstall.status).toBe(0);+ expect((await runCli(['--json', 'init'], dir)).status).toBe(0);+ expect((await runCli(['--json', 'init', '--all'], dir)).status).toBe(0);+ await runCli(['--json', 'upgrade'], dir);+ await runCli(['--json', 'init'], tmp('outside'));+ expect(present()).toEqual([]);+ expect(fs.existsSync(path.join(home, '.agents'))).toBe(false);+ expect(fs.existsSync(path.join(home, '.claude'))).toBe(false);+ }, 60_000);+});diff --git a/packages/cli/foundation/config/project.mjs b/packages/cli/foundation/config/project.mjsindex 66aacd97d6..b7da2188e9 100644--- a/packages/cli/foundation/config/project.mjs+++ b/packages/cli/foundation/config/project.mjs@@ -43,6 +43,16 @@ import {resolvePackageDir,} from '../integrations/integrations.mjs';import {loadAutolinkCandidates} from '../integrations/autolink.mjs';+import {+ computerInstallRoots,+ loadComputerIntegrations,+ scanComputerIntegrations,+} from '../integrations/computer-integrations.mjs';+import {relativeWithin, samePath} from '../fs/path-compare.mjs';+import {isOutsideProject} from '../env/project-scope.mjs';+import {cliVersion} from '../release/run-context.mjs';+import {isGlobalCopy} from '../release/choose.mjs';+import {astryxCommandsOnSearchPath} from '../env/search-path.mjs';import {resolveProviders} from '../integrations/provider-resolution.mjs';import {setProject as setDebugProject,@@ -55,7 +65,7 @@ import {discoverValidIntegrationComponents,} from '../discovery/component-discovery.mjs';import {resolveComponentReplacements} from '../discovery/component-replacement.mjs';-import {findCoreDir} from '../fs/paths.mjs';+import {CLI_ROOT, findCoreDir, findProjectCoreDir} from '../fs/paths.mjs';import {applyTemplateReplacements,effectiveTemplateDiscovery,@@ -78,6 +88,7 @@ import {selectIntegrationCodemods,} from '../../assets/codemods/integration-discovery.mjs';import {validateLoadedIntegration} from '../integrations/validate-contributions.mjs';+import {recordDeclaredCliCommands} from '../env/cli-command.mjs';import {InMemoryConfigCache,cacheKey,@@ -100,6 +111,80 @@ function errorMessage(err) {return message == null ? String(err) : String(message);}+/**+ * The computer-level integrations (spec AST-081 FR12), read from package.json+ * files only. Outside a project, those installed beside the running CLI;+ * inside one, where the project's own CLI may be the copy that answers, those+ * installed beside the CLI installed for the computer (see globalCliRoot).+ * @param {string} [cwd]+ * @returns {import('../integrations/computer-integrations.mjs').ComputerIntegrationCandidate[]}+ */+export function computerIntegrationCandidates(cwd = process.cwd()) {+ try {+ const cliRoot = isOutsideProject(cwd) ? CLI_ROOT : globalCliRoot(cwd);+ return cliRoot+ ? scanComputerIntegrations({cliRoot, release: cliVersion()})+ : [];+ } catch {+ return [];+ }+}++/**+ * The CLI package whose install root holds the computer-level integrations+ * for a folder inside a project: this copy when it was installed outside the+ * project (installed for the computer, or in a tool's package set), else the+ * first `astryx` on the search path that is installed for the computer. A+ * project's own CLI and a release from the per-user cache are neither.+ * @param {string} cwd+ * @returns {string | null}+ */+function globalCliRoot(cwd) {+ let folder = path.resolve(cwd);+ try {+ folder = fs.realpathSync(folder);+ } catch {+ // A folder that cannot be resolved is compared as written.+ }+ const own = computerInstallRoots(CLI_ROOT);+ if (+ own.length > 0 &&+ !own.some(+ root => samePath(root, folder) || relativeWithin(root, folder) != null,+ )+ ) {+ return CLI_ROOT;+ }+ for (const command of astryxCommandsOnSearchPath()) {+ if (command.cliRoot && isGlobalCopy(command.cliRoot)) {+ return command.cliRoot;+ }+ }+ return null;+}++/**+ * The computer-level integrations a project could add (spec AST-081 FR12):+ * those it does not install, whose peer ranges admit the release that+ * answers, and whose manifest loads.+ * @param {string} cwd+ * @param {Set<string>} installed package names the project loads or declares+ * @returns {Promise<import('../integrations/computer-integrations.mjs').ComputerIntegrationCandidate[]>}+ */+export async function availableComputerIntegrations(cwd, installed) {+ const candidates = computerIntegrationCandidates(cwd).filter(+ c => !c.incompatible && !installed.has(c.name),+ );+ if (candidates.length === 0) return [];+ const loaded = await loadComputerIntegrations(candidates);+ const usable = new Set(+ loaded.flatMap(entry =>+ entry.integration && !entry.integration.__loadError ? [entry.spec] : [],+ ),+ );+ return candidates.filter(c => usable.has(c.name));+}+/*** Load the configured integrations one at a time, so a package that cannot* load at all (not installed, no manifest, more than one manifest, not a bare@@ -338,6 +423,12 @@ export class Project {#cache;/** @type {string} */#hash;+ /**+ * Which Core the project reads: `any`, its installed Core else the Core the+ * answering release carries, or `project`, its installed Core only.+ * @type {'any' | 'project'}+ */+ #core = 'any';/** @type {ProjectIntegrationIssue[]} */#issues = [];/**@@ -360,6 +451,7 @@ export class Project {* @param {import('../integrations/integrations.mjs').LoadedIntegration[]} init.loadedIntegrations* @param {import('./config-cache.mjs').ConfigCache} init.cache* @param {string} init.hash config content hash+ * @param {'any' | 'project'} [init.core] which Core it reads*/constructor({cwd,@@ -369,7 +461,9 @@ export class Project {loadedIntegrations,cache,hash,+ core = 'any',}) {+ this.#core = core;this.#cwd = cwd;this.#configPath = configPath;this.#config = config;@@ -384,11 +478,15 @@ export class Project {* and loads the configured integrations. Discovery is NOT run here — it is* lazy and memoized on the returned instance.*+ * `core: 'project'` reads only the project's installed Core, never the Core+ * the answering release carries: the commands that judge or change a+ * project (`doctor`, `swizzle`, `upgrade`) load it so (spec AST-081 FR3).+ ** @param {string} [cwd]- * @param {{cache?: import('./config-cache.mjs').ConfigCache, fresh?: boolean}} [options]+ * @param {{cache?: import('./config-cache.mjs').ConfigCache, fresh?: boolean, core?: 'any' | 'project'}} [options]* @returns {Promise<Project>}*/- static async load(cwd = process.cwd(), {cache, fresh = false} = {}) {+ static async load(cwd = process.cwd(), {cache, fresh = false, core = 'any'} = {}) {const resolvedCache = fresh? new InMemoryConfigCache(): (cache ?? new InMemoryConfigCache());@@ -440,7 +538,26 @@ export class Project {// existing consumer command doubles as the author's preview. A local copy// replaces the same installed package in place, preserving configured// precedence while making the source being edited authoritative.- const localIntegration = await loadLocalIntegrationSafely(projectDir, fresh);+ const localIntegration = await loadLocalIntegrationSafely(+ projectDir,+ fresh,+ );++ // Outside a project, the integrations installed beside the running CLI+ // load too (spec AST-081 FR12); a package the folder already loads keeps+ // its own copy. Inside a project they never load.+ const computer = isOutsideProject(cwd)+ ? await loadComputerIntegrations(computerIntegrationCandidates(cwd), {+ fresh,+ exclude: [+ ...loadedIntegrations.map(integration => integration.name),+ ...autolinked.flatMap(candidate =>+ candidate.integration ? [candidate.integration.name] : [],+ ),+ ...(localIntegration ? [localIntegration.name] : []),+ ],+ })+ : [];// Autolinked and local packages can claim a provider ID that a configured// package already holds, so identity is resolved once over the final set.@@ -451,6 +568,7 @@ export class Project {spec: integration.__spec,})),...autolinked,+ ...computer,...(localIntegration? [{@@ -462,6 +580,9 @@ export class Project {: []),]);loadedIntegrations = resolution.integrations;+ // The picker (getCliInvocation) is synchronous, so the commands these+ // integrations declare are recorded here, where they become known.+ recordDeclaredCliCommands(projectDir, loadedIntegrations);// The debug recorder resolves its settings synchronously, long before any// command gets here, so this is where a project's `debug` block gets a@@ -500,6 +621,7 @@ export class Project {loadedIntegrations,cache: resolvedCache,hash,+ core,});PROVIDER_LEDGERS.set(project, resolution.ledger);return project;@@ -634,6 +756,18 @@ export class Project {}}+ /**+ * The Core this project reads: its installed Core, else, unless it was+ * loaded with `core: 'project'`, the Core the answering release carries+ * (spec AST-081 FR3). Null when there is none.+ * @returns {string | null}+ */+ coreDir() {+ return this.#core === 'project'+ ? findProjectCoreDir(this.#cwd)+ : findCoreDir(this.#cwd);+ }+/*** Core + integration component ownership records. Wraps* discoverOwnedComponents for core and discoverIntegrationComponents (via@@ -645,7 +779,7 @@ export class Project {*/async components() {return this.#memo('components', async () => {- const coreDir = findCoreDir(this.#cwd);+ const coreDir = this.coreDir();/** @type {Array<{name: string, package: string, group: string|null, docPath: string|null, sourcePath: string|null, issuesUrl: string|undefined}>} */const records = [];@@ -696,7 +830,7 @@ export class Project {async componentReplacements() {return this.#memo('componentReplacements', async () => {const replacements = await resolveComponentReplacements(- findCoreDir(this.#cwd),+ this.coreDir(),this.#loadedIntegrations,);for (const finding of replacements.findings) {@@ -846,7 +980,7 @@ export class Project {const replacing = new Map();if (this.#loadedIntegrations.length > 0) {const {active} = await resolveComponentReplacements(- findCoreDir(this.#cwd),+ this.coreDir(),this.#loadedIntegrations,);for (const each of active) {@@ -943,7 +1077,10 @@ export class Project {// nothing and a reader gets the topic it was meant to replace.if (errors.length > 0) {for (const e of errors) {- catalog.addIssue({package: integration.name ?? pkg, message: e.message});+ catalog.addIssue({+ package: integration.name ?? pkg,+ message: e.message,+ });}continue;}diff --git a/packages/cli/foundation/config/project.test.mjs b/packages/cli/foundation/config/project.test.mjsindex d33b1e61c0..72067f66a9 100644--- a/packages/cli/foundation/config/project.test.mjs+++ b/packages/cli/foundation/config/project.test.mjs@@ -2,9 +2,11 @@import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';import * as fs from 'node:fs';+import * as os from 'node:os';import * as path from 'node:path';import {Project, DEFAULT_ISSUES_URL, findConfigPath} from './project.mjs';import {InMemoryConfigCache} from './config-cache.mjs';+import {getCliInvocation} from '../env/package-manager.mjs';import * as componentDiscovery from '../discovery/component-discovery.mjs';import {discoverCoreTemplates} from '../discovery/template-adapter.mjs';@@ -31,6 +33,7 @@ function scaffold({docs = null,unknownKeys = null,agentDocs = null,+ cliCommand = null,integrationIssuesUrl = 'https://example.com/widgets/issues',} = {}) {fs.writeFileSync(@@ -57,6 +60,7 @@ function scaffold({if (withCodemods) manifest.codemods = './codemods';if (docs) manifest.docs = './docs';if (agentDocs != null) manifest.agentDocs = agentDocs;+ if (cliCommand != null) manifest.cliCommand = cliCommand;if (unknownKeys) Object.assign(manifest, unknownKeys);if (integrationIssuesUrl) manifest.issuesUrl = integrationIssuesUrl;fs.writeFileSync(@@ -287,6 +291,68 @@ describe('Project.load', () => {});});+describe('Project.load and the cliCommand an integration declares', () => {+ it('records it, so the picker prints commands with it', async () => {+ scaffold({cliCommand: 'acme astryx'});+ const project = await Project.load(tmpDir);+ expect(project.loadedIntegrations[0].cliCommand).toBe('acme astryx');+ expect(getCliInvocation(tmpDir)).toBe('acme astryx');+ });++ it('ignores an invalid one with a warning and keeps the rest of the package', async () => {+ scaffold({cliCommand: ' acme astryx\n'});+ const project = await Project.load(tmpDir);+ const [widgets] = project.loadedIntegrations;+ expect(widgets.__loadError).toBeUndefined();+ expect(widgets.cliCommand).toBeUndefined();+ expect(widgets.components).toBeDefined();+ expect(getCliInvocation(tmpDir)).not.toContain('acme astryx');+ const issues = await project.issues();+ expect(issues).toContainEqual(+ expect.objectContaining({+ code: 'invalid_cli_command',+ severity: 'warning',+ }),+ );+ });++ it('drops a previous load once the declaration is gone', async () => {+ scaffold({cliCommand: 'acme astryx'});+ await Project.load(tmpDir);+ scaffold();+ await Project.load(tmpDir, {fresh: true});+ expect(getCliInvocation(tmpDir)).not.toBe('acme astryx');+ });+});++describe("Project.load({core: 'project'})", () => {+ it('reads only the installed Core, never the Core the answering release carries', async () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-project-core-'));+ try {+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ JSON.stringify({name: 'a', dependencies: {'@astryxdesign/core': '^0.7.0'}}),+ );+ const any = await Project.load(dir);+ const own = await Project.load(dir, {core: 'project'});+ // The CLI in this repository carries the Core beside it.+ expect(any.coreDir()).not.toBeNull();+ expect(own.coreDir()).toBeNull();+ expect((await own.components()).filter(c => c.package === '@astryxdesign/core')).toEqual([]);++ const core = path.join(dir, 'node_modules', '@astryxdesign', 'core');+ fs.mkdirSync(core, {recursive: true});+ fs.writeFileSync(+ path.join(core, 'package.json'),+ JSON.stringify({name: '@astryxdesign/core', version: '0.7.0'}),+ );+ expect((await Project.load(dir, {core: 'project'})).coreDir()).toBe(fs.realpathSync(core));+ } finally {+ fs.rmSync(dir, {recursive: true, force: true});+ }+ });+});+describe('findConfigPath', () => {it('rejects multiple config files at the same root', () => {fs.writeFileSync(diff --git a/packages/cli/foundation/config/theme-state.mjs b/packages/cli/foundation/config/theme-state.mjsindex b8125165ff..e76493f3f2 100644--- a/packages/cli/foundation/config/theme-state.mjs+++ b/packages/cli/foundation/config/theme-state.mjs@@ -16,6 +16,7 @@import * as fs from 'node:fs';import * as path from 'node:path';import {assertWithin, PathSafetyError} from '../fs/path-safety.mjs';+import {formatCliCommand} from '../env/package-manager.mjs';export const LOCAL_THEME_ROOT = './src/themes';export const THEME_MODULE_BASENAME = 'astryx-themes';@@ -106,7 +107,7 @@ export function themeModuleCandidates(projectDir) {function validThemeRecord(value, label) {if (!isRecord(value) || !isRecord(value.themes)) {throw new ThemeStateError(- `${label} must carry a static ${THEME_RECORD_MARKER} header. Regenerate it with \`astryx theme add <slug>\`.`,+ `${label} must carry a static ${THEME_RECORD_MARKER} header. Regenerate it with \`${formatCliCommand('theme add <slug>')}\`.`,);}const keys = Object.keys(value);@@ -139,7 +140,7 @@ function validThemeRecord(value, label) {!THEME_SLUG_RE.test(value.defaultThemeSlug)) {throw new ThemeStateError(- `${label} defaultThemeSlug must be a lowercase kebab-case slug. Regenerate it with \`astryx theme use <slug>\`.`,+ `${label} defaultThemeSlug must be a lowercase kebab-case slug. Regenerate it with \`${formatCliCommand('theme use <slug>')}\`.`,);}return {themes, defaultSlug: value.defaultThemeSlug};@@ -159,7 +160,7 @@ export function parseThemeModuleRecord(source, label = 'theme module') {.filter(line => /^\s*\*\s*@astryx-theme-record\s+/u.test(line));if (recordLines.length !== 1) {throw new ThemeStateError(- `${label} must carry exactly one static ${THEME_RECORD_MARKER} header. Regenerate it with \`astryx theme add <slug>\`.`,+ `${label} must carry exactly one static ${THEME_RECORD_MARKER} header. Regenerate it with \`${formatCliCommand('theme add <slug>')}\`.`,);}const payload = recordLines[0].replace(@@ -318,7 +319,7 @@ export function readThemeState(cwd = process.cwd()) {export function renderThemeModule(themes, defaultSlug, typescript) {if (!themes.some(theme => theme.slug === defaultSlug)) {throw new ThemeStateError(- `Default theme "${defaultSlug}" is not added. Run \`astryx theme add ${defaultSlug}\` first.`,+ `Default theme "${defaultSlug}" is not added. Run \`${formatCliCommand(`theme add ${defaultSlug}`)}\` first.`,);}/** @type {string[]} */diff --git a/packages/cli/foundation/discovery/cli-self-docs.mjs b/packages/cli/foundation/discovery/cli-self-docs.mjsindex c56d296b7e..c754f7cb78 100644--- a/packages/cli/foundation/discovery/cli-self-docs.mjs+++ b/packages/cli/foundation/discovery/cli-self-docs.mjs@@ -25,6 +25,7 @@ import {oversizedDocSections,} from './docs-output-budget.mjs';import {routeSegment} from './docs-section-key.mjs';+import {formatCliCommand} from '../env/package-manager.mjs';/** The directories, relative to the CLI root, that hold the CLI's own docs. */export const CLI_SELF_DOC_DIRS = [@@ -187,6 +188,19 @@ function sentence(text, more) {return more && text !== '' && !/[.!?:]$/.test(text) ? `${text}.` : text;}+/**+ * The line a command doc prints for what it does outside a project (spec+ * AST-081 FR4). A group that only holds subcommands declares nothing and+ * prints nothing.+ * @type {Record<string, string>}+ */+const OUTSIDE_PROJECT_TEXT = {+ same: "Outside a project (`same`): it answers as it would in a new project on this release, reading this release's Core, as it does in a project with nothing installed: the one installed beside the CLI, else one in the per-user cache, which a global install downloads in the background after a command run online (in CI, the first command that needs it downloads it).",+ refuse:+ 'Outside a project (`refuse`): it writes nothing and fails, naming the app project or integration package it needs.',+ own: 'Outside a project (`own`): it does what the description above says it does outside a project.',+};+/** @param {any[]} notes */function noteBlocks(notes) {return (notes ?? []).filter(note => TOPIC_BLOCKS.has(note?.type));@@ -251,6 +265,8 @@ function commandSection(cmd, index) {rows: exitCodes.map((/** @type {any} */ e) => [String(e.code), e.when]),});}+ const outside = OUTSIDE_PROJECT_TEXT[cmd.outsideProject];+ if (outside) content.push({type: 'prose', text: outside});// Links name docs by identity; the route in each command is derived when// the doc is read (spec:AST-047 FR9).const subcommands = (cmd.subcommands ?? []).filter(@@ -318,7 +334,8 @@ function functionSection(fn, index) {// A Default column only when some parameter declares a default, so a// function with none keeps a three-column table.const defaults = params.some(- (/** @type {any} */ p) => typeof p.default === 'string' && p.default !== '',+ (/** @type {any} */ p) =>+ typeof p.default === 'string' && p.default !== '',);content.push({type: 'table',@@ -475,13 +492,13 @@ export async function auditCliSelfDocs({else {misfiled.push({source,- message: `${source} has namespace "authoring", but \`astryx docs authoring\` does not list it`,+ message: `${source} has namespace "authoring", but \`${formatCliCommand('docs authoring')}\` does not list it`,});}} else if (inAuthoring) {misfiled.push({source,- message: `${source} is read in \`astryx docs authoring\`, but its namespace is "${namespace}"`,+ message: `${source} is read in \`${formatCliCommand('docs authoring')}\`, but its namespace is "${namespace}"`,});} else {treeDocs.push(doc);diff --git a/packages/cli/foundation/discovery/cli-self-docs.test.mjs b/packages/cli/foundation/discovery/cli-self-docs.test.mjsindex f1d851bf7f..3131ef4900 100644--- a/packages/cli/foundation/discovery/cli-self-docs.test.mjs+++ b/packages/cli/foundation/discovery/cli-self-docs.test.mjs@@ -25,6 +25,7 @@ import {discoverCliSelfDocSources,} from './cli-self-docs.mjs';import {routeSegment} from './docs-section-key.mjs';+import {formatCliCommand} from '../env/package-manager.mjs';const SLOW = 60_000;@@ -145,8 +146,8 @@ describe('auditCliSelfDocs', () => {});const result = await audit(root, ['y/y.doc.mjs', 'z/z.doc.mjs']);expect(result.misfiled.map(entry => entry.message)).toEqual([- 'authoring/x/x.doc.mjs has namespace "authoring", but `astryx docs authoring` does not list it',- 'authoring/y/y.doc.mjs is read in `astryx docs authoring`, but its namespace is "cli/api"',+ `authoring/x/x.doc.mjs has namespace "authoring", but \`${formatCliCommand('docs authoring')}\` does not list it`,+ `authoring/y/y.doc.mjs is read in \`${formatCliCommand('docs authoring')}\`, but its namespace is "cli/api"`,]);expect(result.authoring).toBe(1);expect(result.tree).toBe(0);diff --git a/packages/cli/foundation/discovery/component-replacement.mjs b/packages/cli/foundation/discovery/component-replacement.mjsindex 9ad45968a7..01e156c889 100644--- a/packages/cli/foundation/discovery/component-replacement.mjs+++ b/packages/cli/foundation/discovery/component-replacement.mjs@@ -30,6 +30,7 @@ import {COMPONENT_REPLACES_CLI,componentReplacesCliProblem,} from '../integrations/cli-requirement.mjs';+import {formatCliCommand} from '../env/package-manager.mjs';/*** @typedef {import('../integrations/integrations.mjs').LoadedIntegration} LoadedIntegration@@ -292,7 +293,7 @@ export async function resolveComponentReplacements('missing_component_replacement_target',differentCase? `Component "${name}" replaces "${replaces}", which is not a Core component name. Core names it "${differentCase}".`- : `Component "${name}" replaces "${replaces}", which is not a Core component. Run \`astryx component --list\` for Core component names.`,+ : `Component "${name}" replaces "${replaces}", which is not a Core component. Run \`${formatCliCommand('component --list')}\` for Core component names.`,);if (declaration.optedIn) {const key = differentCase ?? replaces;diff --git a/packages/cli/foundation/discovery/runner-allowlist.mjs b/packages/cli/foundation/discovery/runner-allowlist.mjsnew file mode 100644index 0000000000..be76828ce3--- /dev/null+++ b/packages/cli/foundation/discovery/runner-allowlist.mjs@@ -0,0 +1,53 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Where a runner may stand in front of an Astryx command in Astryx's own+ * docs. Docs write commands bare (`astryx <command>`): the CLI prefixes each+ * one with the reader's command when it prints a doc, and the docsite with+ * `npx @astryxdesign/cli`. A few files show a runner on purpose, and some files+ * are not docs at all. The rules, checked by test/runner-commands.test.mjs:+ *+ * - npx (or another download runner) with the unscoped name `astryx` is never+ * written outside `skip`: it fetches an unrelated npm package.+ * - In a doc (`*.doc.mjs`, and Core's docs.mjs), no runner precedes an Astryx+ * command, except in `runnerExamples`, where `npx @astryxdesign/cli …` and a+ * project's runner may (still never the unscoped name through npx).+ *+ * TODO(doctor-runner-check): the Doctor lane's integration-docs runner check+ * (foundation/discovery/runner-commands.mjs) becomes the single rule; then the+ * repo test runs that check over Core's and the CLI's own docs with this+ * allowlist.+ *+ * @input nothing+ * @output the allowlist+ * @position packages/cli/foundation/discovery — data shared by the repo test+ * and the Doctor runner check+ */++export const RUNNER_COMMAND_ALLOWLIST = Object.freeze({+ /** Files never scanned: release notes, tests, and the helpers that build runner forms. */+ skip: Object.freeze([+ /(^|\/)CHANGELOG\.md$/u,+ /\.test\.[cm]?[jt]sx?$/u,+ /(^|\/)__tests__\//u,+ /^packages\/cli\/test\//u,+ /^packages\/cli\/foundation\/env\/package-manager\.mjs$/u,+ ]),+ /** Docs that show a runner on purpose, and why. */+ runnerExamples: Object.freeze({+ 'packages/core/docs.mjs':+ "Core's setup banner, for a project that has no CLI installed yet",+ 'packages/cli/assets/docs/tree/updates.doc.mjs':+ "quotes the CLI's own update notice, which names the project's runner",+ 'packages/cli/assets/docs/tree/cli-command.doc.mjs':+ 'explains how printed commands start, the pinned `npx @astryxdesign/cli@<version>` among them',+ 'packages/cli/assets/docs/tree/who-answers.doc.mjs':+ 'explains how printed commands start, the pinned `npx @astryxdesign/cli@<version>` among them',+ 'packages/cli/assets/docs/tree/project-global-or-both.doc.mjs':+ 'compares running the CLI with npx to installing it, and is found by searching for that command',+ 'packages/cli/assets/docs/tree/install-once.doc.mjs':+ 'names a pinned release, `npx @astryxdesign/cli@<version>`, which answers as that version',+ 'packages/cli/clients/cli/commands/upgrade.doc.mjs':+ 'quotes the command upgrade prints when the CLI is older than Core, pinned to the matching release',+ }),+});diff --git a/packages/cli/foundation/discovery/template-needs.mjs b/packages/cli/foundation/discovery/template-needs.mjsindex 0310a98862..43944e43f2 100644--- a/packages/cli/foundation/discovery/template-needs.mjs+++ b/packages/cli/foundation/discovery/template-needs.mjs@@ -20,7 +20,10 @@ import * as path from 'node:path';import module from 'node:module';import {CLI_ROOT} from '../fs/paths.mjs';import {detectStylingSystem} from '../agent-docs/agent-docs.mjs';-import {decidePackageManagerIn} from '../env/package-manager.mjs';+import {+ decidePackageManagerIn,+ formatCliCommand,+} from '../env/package-manager.mjs';// ── Known packages that a template may import without the user installing them.// react and react-dom are the framework; @astryxdesign/* is the design system@@ -230,7 +233,7 @@ export function analyzeTemplateNeeds(source, cwd) {}if (stylexCompilerNeeded) {notes.push(- 'This template uses StyleX. Your project needs a StyleX compiler plugin \u2014 see `astryx docs styling-overview` for setup steps.',+ `This template uses StyleX. Your project needs a StyleX compiler plugin \u2014 see \`${formatCliCommand('docs styling-overview')}\` for setup steps.`,);}diff --git a/packages/cli/foundation/discovery/theme-imports.mjs b/packages/cli/foundation/discovery/theme-imports.mjsindex 607cab958d..e4b5983f10 100644--- a/packages/cli/foundation/discovery/theme-imports.mjs+++ b/packages/cli/foundation/discovery/theme-imports.mjs@@ -19,6 +19,7 @@ import {moduleExportsName} from './module-exports.mjs';import {inspectPackageExport} from './package-exports.mjs';import {themeImportPackage} from './theme-discovery.mjs';import {isLocalThemeOwner, projectPath} from '../config/theme-state.mjs';+import {formatCliCommand} from '../env/package-manager.mjs';export class ThemeImportError extends Error {}@@ -59,7 +60,7 @@ function resolveLocalTheme(theme, cwd) {path.relative(cwd, path.join(theme.sourceDir, theme.entry)),);throw new ThemeImportError(- `Local theme "${theme.slug}" is not built. Run \`astryx theme build ${source}\` and try again. Missing: ${missing+ `Local theme "${theme.slug}" is not built. Run \`${formatCliCommand(`theme build ${source}`, cwd)}\` and try again. Missing: ${missing.map(file => projectPath(path.relative(cwd, file))).join(', ')}.`,);@@ -68,8 +69,11 @@ function resolveLocalTheme(theme, cwd) {throw new ThemeImportError(`Local theme "${theme.slug}" built module ${projectPath(path.relative(cwd, moduleFile),- )} does not export "${theme.exportName}". Rebuild it with \`astryx theme build ${projectPath(- path.relative(cwd, path.join(theme.sourceDir, theme.entry)),+ )} does not export "${theme.exportName}". Rebuild it with \`${formatCliCommand(+ `theme build ${projectPath(+ path.relative(cwd, path.join(theme.sourceDir, theme.entry)),+ )}`,+ cwd,)}\`.`,);}@@ -130,7 +134,7 @@ function resolvePackageTheme(theme, cwd, ownerThemeCount) {findInstalledPackage(cwd, importPackage);if (!packageDir) {throw new ThemeImportError(- `Theme package "${importPackage}" is not installed. Run \`npm install ${importPackage}\` (or yarn/pnpm/bun), then run \`astryx theme add ${theme.slug}\`.`,+ `Theme package "${importPackage}" is not installed. Run \`npm install ${importPackage}\` (or yarn/pnpm/bun), then run \`${formatCliCommand(`theme add ${theme.slug}`, cwd)}\`.`,);}const pkg = readPackage(path.join(packageDir, 'package.json'));diff --git a/packages/cli/foundation/discovery/theme-imports.test.mjs b/packages/cli/foundation/discovery/theme-imports.test.mjsindex f50ce4d729..31009533fc 100644--- a/packages/cli/foundation/discovery/theme-imports.test.mjs+++ b/packages/cli/foundation/discovery/theme-imports.test.mjs@@ -148,7 +148,7 @@ describe('resolveThemeImports', () => {});expect(() => resolveThemeImports(theme, {cwd: dir})).toThrow(- /astryx theme build src\/themes\/ocean\/oceanTheme\.ts/i,+ / theme build src\/themes\/ocean\/oceanTheme\.ts`/i,);fs.writeFileSync(path.join(sourceDir, 'ocean.js'),diff --git a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs b/packages/cli/foundation/doc-compiler/doc-loads.test.mjsindex 02d4987d5a..0db4192e23 100644--- a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs+++ b/packages/cli/foundation/doc-compiler/doc-loads.test.mjs@@ -248,6 +248,10 @@ const RUNNERS = {runs: 'astryx.config, through the config parser',sites: ['loadModuleWithParser(..., parseConfig)'],},+ 'foundation/fs/file-protection.mjs': {+ runs: 'the ignore matcher (CommonJS), loaded when a resolver first reads an ignore file',+ sites: ['require(ignore)'],+ },'foundation/discovery/component-discovery.mjs': {runs: '@babel/parser, on first use, to read the members a family doc lists in its components without running the doc',sites: ['require(@babel/parser)'],@@ -319,6 +323,22 @@ const RUNNERS = {runs: "each installed integration's manifest",sites: ['importUserModule'],},+ 'foundation/release/cache.mjs': {+ runs: 'npm (under npm-guard.mjs), to install and look up CLI releases in the per-user cache; each installed release once, to check it starts and reports its version; and ps (tasklist on Windows), to confirm the process a stale lock records is node or npm before ending it',+ sites: ['child_process.spawnSync ×5'],+ },+ 'foundation/release/npm-guard.mjs': {+ runs: 'npm, in a process group of its own that it ends at the time limit, on Ctrl-C, or when the run that started it goes away',+ sites: ['child_process.spawn'],+ },+ 'foundation/release/global-state.mjs': {+ runs: "the background check of the registry's `latest` release, the agent-text step, and the step that installs the global copy's own Core into the release cache, each detached",+ sites: ['child_process.spawn'],+ },+ 'foundation/release/handoff.mjs': {+ runs: "the CLI release that answers a project's run, when it is not this copy",+ sites: ['child_process.spawn'],+ },'scripts/generate-cli-readme.mjs': {runs: '`astryx manifest` and the error-code and response-type docs, to write the README tables (build time, not shipped)',sites: ['child_process.spawnSync', 'import(<computed>)'],diff --git a/packages/cli/foundation/doc-compiler/inputs.mjs b/packages/cli/foundation/doc-compiler/inputs.mjsindex 3330cebb34..6040460d33 100644--- a/packages/cli/foundation/doc-compiler/inputs.mjs+++ b/packages/cli/foundation/doc-compiler/inputs.mjs@@ -109,7 +109,10 @@ export async function collectDocInputs(project) {list.add('components', record.name, record.package, record.docPath);}- const coreDir = findCoreDir(project.cwd);+ const coreDir =+ typeof project.coreDir === 'function'+ ? project.coreDir()+ : findCoreDir(project.cwd);if (coreDir != null) {for (const name of Object.values(discoverHooks(coreDir)).flat()) {const file = findHookDoc(coreDir, name);diff --git a/packages/cli/foundation/doc-compiler/tree.test.mjs b/packages/cli/foundation/doc-compiler/tree.test.mjsindex bd651d6c2a..ff35b6d22b 100644--- a/packages/cli/foundation/doc-compiler/tree.test.mjs+++ b/packages/cli/foundation/doc-compiler/tree.test.mjs@@ -502,7 +502,7 @@ describe("the CLI's own docs tree", () => {async () => {const tree = await loadDocsTree({fresh: true});expect(tree.diagnostics).toEqual([]);- expect(tree.roots().map(node => node.route)).toEqual(['cli', 'internationalization', 'layout', 'migration', 'styling', 'styling-libraries', 'tokens', 'typography']);+ expect(tree.roots().map(node => node.route)).toEqual(['cli', 'global', 'internationalization', 'layout', 'migration', 'styling', 'styling-libraries', 'tokens', 'typography']);// Every slot child is a node one level below the namespace that places// it, and every node but the root is placed. Read from the tree, so a// restructure of the guides does not need this test edited.diff --git a/packages/cli/foundation/env/cli-command.mjs b/packages/cli/foundation/env/cli-command.mjsnew file mode 100644index 0000000000..a7169cbc55--- /dev/null+++ b/packages/cli/foundation/env/cli-command.mjs@@ -0,0 +1,152 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file The command that runs the CLI for this project, when something other+ * than the package-manager guess says what it is.+ *+ * `getCliInvocation` (package-manager.mjs) is the one picker every printed+ * command goes through. It asks, in order:+ *+ * 1. **The integrations** — the `cliCommand` field of each loaded+ * integration's manifest. `Project.load` records them per project with+ * {@link recordDeclaredCliCommands}. One command, declared by one or more+ * integrations, is used. Two different commands cancel each other out: the+ * picker falls back to its guess, even when a host set a door, and+ * `astryx doctor` warns.+ * 2. **The door** — the command a host ran this call through. A host sets it+ * for the duration of one call with {@link runWithCliDoor}; nothing in the+ * public API sets it yet, so it is empty in every plain run.+ * 3. **The guess** — the package-manager prefix, as before.+ *+ * @input A host's door name; the loaded integrations of a project.+ * @output The declared command for a directory, or the conflict.+ * @position foundation/env — read by the picker and by `astryx doctor`.+ */++import {AsyncLocalStorage} from 'node:async_hooks';+import * as fs from 'node:fs';+import * as path from 'node:path';++/**+ * One integration's declared command.+ * @typedef {object} DeclaredCliCommand+ * @property {string} package the integration package that declared it+ * @property {string} command its `cliCommand` value+ */++/** @type {AsyncLocalStorage<{command: string}>} */+const doorScope = new AsyncLocalStorage();++/**+ * Run `fn` with `command` as the door printed commands start with. The slot a+ * host fills for one call. An integration's `cliCommand` still comes first,+ * and conflicting ones still fall back to the guess.+ * @template T+ * @param {string} command e.g. `astryx` for a global launcher+ * @param {() => T} fn+ * @returns {T}+ */+export function runWithCliDoor(command, fn) {+ return doorScope.run({command}, fn);+}++/**+ * The door of the current call, if a host set one.+ * @returns {string | undefined}+ */+export function cliDoor() {+ return doorScope.getStore()?.command;+}++/** @type {Map<string, DeclaredCliCommand[]>} */+const declaredByProject = new Map();++/**+ * The directory a project is keyed by: the nearest one with a package.json,+ * the same root `Project.load` resolves; otherwise the directory itself.+ * @param {string} dir+ * @returns {string}+ */+function projectKey(dir) {+ const start = path.resolve(dir);+ let current = start;+ for (;;) {+ if (fs.existsSync(path.join(current, 'package.json'))) return current;+ const parent = path.dirname(current);+ if (parent === current) return start;+ current = parent;+ }+}++/**+ * The commands a set of loaded integrations declares, in load order. An+ * integration that failed to load, or was set aside for a provider conflict,+ * contributes nothing, so it declares nothing either.+ * @param {ReadonlyArray<{name?: string, __spec?: string, cliCommand?: string, __loadError?: string, __providerConflict?: unknown}>} integrations+ * @returns {DeclaredCliCommand[]}+ */+export function declaredCliCommandsOf(integrations) {+ /** @type {DeclaredCliCommand[]} */+ const declared = [];+ for (const integration of integrations) {+ if (integration.__loadError != null) continue;+ if (integration.__providerConflict != null) continue;+ if (typeof integration.cliCommand !== 'string') continue;+ declared.push({+ package: integration.name ?? integration.__spec ?? '(unnamed)',+ command: integration.cliCommand,+ });+ }+ return declared;+}++/**+ * Choose among declarations: one command, declared by one or more+ * integrations, is used; different commands are a conflict.+ * @param {DeclaredCliCommand[]} declared+ * @returns {{command?: string, conflict: boolean, declared: DeclaredCliCommand[]}}+ */+export function chooseDeclaredCliCommand(declared) {+ const commands = new Set(declared.map(entry => entry.command));+ if (commands.size === 1) {+ return {command: declared[0].command, conflict: false, declared};+ }+ return {conflict: commands.size > 1, declared};+}++/**+ * Record the commands a project's loaded integrations declare. Called by+ * `Project.load` each time it resolves the integration set; the latest load+ * wins.+ * @param {string} projectDir+ * @param {Parameters<typeof declaredCliCommandsOf>[0]} integrations+ * @returns {void}+ */+export function recordDeclaredCliCommands(projectDir, integrations) {+ declaredByProject.set(+ projectKey(projectDir),+ declaredCliCommandsOf(integrations),+ );+}++/**+ * Whether this process has loaded the project at `targetDir`.+ * @param {string} [targetDir=process.cwd()]+ * @returns {boolean}+ */+export function hasRecordedProject(targetDir = process.cwd()) {+ return declaredByProject.has(projectKey(targetDir));+}++/**+ * What the integrations of the project at `targetDir` declare, as recorded by+ * its last `Project.load` in this process; see+ * {@link chooseDeclaredCliCommand}.+ * @param {string} [targetDir=process.cwd()]+ * @returns {{command?: string, conflict: boolean, declared: DeclaredCliCommand[]}}+ */+export function declaredCliCommand(targetDir = process.cwd()) {+ return chooseDeclaredCliCommand(+ declaredByProject.get(projectKey(targetDir)) ?? [],+ );+}diff --git a/packages/cli/foundation/env/cli-command.test.mjs b/packages/cli/foundation/env/cli-command.test.mjsnew file mode 100644index 0000000000..ced7146a13--- /dev/null+++ b/packages/cli/foundation/env/cli-command.test.mjs@@ -0,0 +1,129 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, it, expect, afterEach} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import * as os from 'node:os';+import {+ chooseDeclaredCliCommand,+ cliDoor,+ declaredCliCommand,+ declaredCliCommandsOf,+ hasRecordedProject,+ recordDeclaredCliCommands,+ runWithCliDoor,+} from './cli-command.mjs';++/** @type {string[]} */+const dirs = [];++afterEach(() => {+ for (const dir of dirs.splice(0)) {+ fs.rmSync(dir, {recursive: true, force: true});+ }+});++/** A project directory with a package.json, and a folder inside it. */+function makeProject() {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-cli-command-'));+ dirs.push(dir);+ fs.writeFileSync(path.join(dir, 'package.json'), '{"name":"app"}');+ fs.mkdirSync(path.join(dir, 'src'));+ return dir;+}++describe('runWithCliDoor', () => {+ it('sets the door for the call, and only for it', async () => {+ expect(cliDoor()).toBeUndefined();+ const inside = await runWithCliDoor('astryx', async () => {+ await Promise.resolve();+ return cliDoor();+ });+ expect(inside).toBe('astryx');+ expect(cliDoor()).toBeUndefined();+ });+});++describe('declaredCliCommandsOf', () => {+ it('skips integrations that failed to load or were set aside', () => {+ expect(+ declaredCliCommandsOf([+ {name: '@acme/a', cliCommand: 'acme astryx'},+ {name: '@acme/b'},+ {name: '@acme/c', cliCommand: 'c astryx', __loadError: 'boom'},+ {name: '@acme/d', cliCommand: 'd astryx', __providerConflict: {}},+ {__spec: '@acme/e', cliCommand: 'acme astryx'},+ ]),+ ).toEqual([+ {package: '@acme/a', command: 'acme astryx'},+ {package: '@acme/e', command: 'acme astryx'},+ ]);+ });+});++describe('chooseDeclaredCliCommand', () => {+ it('uses one command, however many packages declare it', () => {+ const declared = [+ {package: '@acme/a', command: 'acme astryx'},+ {package: '@acme/b', command: 'acme astryx'},+ ];+ expect(chooseDeclaredCliCommand(declared)).toEqual({+ command: 'acme astryx',+ conflict: false,+ declared,+ });+ });++ it('uses neither of two different commands, and calls it a conflict', () => {+ const result = chooseDeclaredCliCommand([+ {package: '@acme/a', command: 'acme astryx'},+ {package: '@acme/b', command: 'other astryx'},+ ]);+ expect(result.command).toBeUndefined();+ expect(result.conflict).toBe(true);+ });++ it('has nothing to choose with no declarations', () => {+ expect(chooseDeclaredCliCommand([])).toEqual({+ conflict: false,+ declared: [],+ });+ });+});++describe('recordDeclaredCliCommands', () => {+ it('answers for the project and any folder inside it', () => {+ const dir = makeProject();+ expect(hasRecordedProject(dir)).toBe(false);+ recordDeclaredCliCommands(dir, [+ {name: '@acme/a', cliCommand: 'acme astryx'},+ ]);+ expect(hasRecordedProject(dir)).toBe(true);+ expect(declaredCliCommand(dir).command).toBe('acme astryx');+ expect(declaredCliCommand(path.join(dir, 'src')).command).toBe(+ 'acme astryx',+ );+ });++ it('lets the latest load win', () => {+ const dir = makeProject();+ recordDeclaredCliCommands(dir, [+ {name: '@acme/a', cliCommand: 'acme astryx'},+ ]);+ recordDeclaredCliCommands(dir, []);+ expect(hasRecordedProject(dir)).toBe(true);+ expect(declaredCliCommand(dir).command).toBeUndefined();+ });++ it('does not answer for a nested project of its own', () => {+ const dir = makeProject();+ const nested = path.join(dir, 'packages', 'web');+ fs.mkdirSync(nested, {recursive: true});+ fs.writeFileSync(path.join(nested, 'package.json'), '{"name":"web"}');+ recordDeclaredCliCommands(dir, [+ {name: '@acme/a', cliCommand: 'acme astryx'},+ ]);+ expect(hasRecordedProject(nested)).toBe(false);+ expect(declaredCliCommand(nested).command).toBeUndefined();+ });+});diff --git a/packages/cli/foundation/env/node-version.test.mjs b/packages/cli/foundation/env/node-version.test.mjsindex 89618aefc6..e8c5affbf4 100644--- a/packages/cli/foundation/env/node-version.test.mjs+++ b/packages/cli/foundation/env/node-version.test.mjs@@ -20,15 +20,27 @@ import {describe('parseNodeVersion', () => {it('parses a plain semver string', () => {- expect(parseNodeVersion('22.14.1')).toEqual({major: 22, minor: 14, patch: 1});+ expect(parseNodeVersion('22.14.1')).toEqual({+ major: 22,+ minor: 14,+ patch: 1,+ });});it('strips a leading v', () => {- expect(parseNodeVersion('v20.10.0')).toEqual({major: 20, minor: 10, patch: 0});+ expect(parseNodeVersion('v20.10.0')).toEqual({+ major: 20,+ minor: 10,+ patch: 0,+ });});it('ignores a prerelease/build suffix on the patch segment', () => {- expect(parseNodeVersion('16.20.2-nightly')).toEqual({major: 16, minor: 20, patch: 2});+ expect(parseNodeVersion('16.20.2-nightly')).toEqual({+ major: 16,+ minor: 20,+ patch: 2,+ });});it('defaults missing segments to 0', () => {diff --git a/packages/cli/foundation/env/package-manager.global.test.mjs b/packages/cli/foundation/env/package-manager.global.test.mjsnew file mode 100644index 0000000000..0c474b1350--- /dev/null+++ b/packages/cli/foundation/env/package-manager.global.test.mjs@@ -0,0 +1,66 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file The picker's guess when the CLI installed for the computer answers:+ * `astryx` outside a project, and the pinned package inside one, where the+ * global copy never answers for itself (spec AST-081 FR5).+ */++import {describe, it, expect, vi, afterEach} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {guessCliInvocation} from './package-manager.mjs';+import {+ CLI_VERSION,+ cleanupFixtures,+ installCore,+ project,+ tempDir,+} from '../../test-utils/release-fixtures.mjs';++vi.mock('../release/choose.mjs', async importOriginal => ({+ .../** @type {object} */ (await importOriginal()),+ isGlobalCopy: () => true,+}));++afterEach(cleanupFixtures);++describe('guessCliInvocation for the copy installed for the computer', () => {+ it('prints the bare `astryx` command outside a project', () => {+ const empty = tempDir('empty');+ fs.writeFileSync(path.join(empty, 'package-lock.json'), '{}');+ const before = process.cwd();+ process.chdir(empty);+ try {+ expect(guessCliInvocation(empty)).toBe('astryx');+ } finally {+ process.chdir(before);+ }+ });++ it('prints the pinned package inside a project it answers as the matched release', () => {+ const root = project(tempDir(), {'@astryxdesign/core': CLI_VERSION});+ installCore(root, CLI_VERSION);+ fs.writeFileSync(path.join(root, 'package-lock.json'), '{}');+ expect(guessCliInvocation(root)).toBe(+ `npx @astryxdesign/cli@${CLI_VERSION}`,+ );+ });+});++describe('one stem per run', () => {+ it('names the release that answered the run, whichever folder a line names', () => {+ // The run answers outside a project; a line about a project folder whose+ // own CLI sits beyond the read reach still gets the same stem.+ const empty = tempDir('empty');+ const other = project(tempDir(), {'@astryxdesign/core': CLI_VERSION});+ installCore(other, CLI_VERSION);+ const before = process.cwd();+ process.chdir(empty);+ try {+ expect(guessCliInvocation(other)).toBe(guessCliInvocation(empty));+ } finally {+ process.chdir(before);+ }+ });+});diff --git a/packages/cli/foundation/env/package-manager.mjs b/packages/cli/foundation/env/package-manager.mjsindex d3286f4813..a4fc556f14 100644--- a/packages/cli/foundation/env/package-manager.mjs+++ b/packages/cli/foundation/env/package-manager.mjs@@ -8,11 +8,17 @@* the runner that launched us. Returns the correct command prefix for running* package binaries (e.g. 'npx astryx', 'yarn astryx', 'pnpm exec astryx'), and* the scoped one-off form ('npx @astryxdesign/cli') when the `astryx` bin does- * not resolve from the project.+ * not resolve from the project. An integration's declared `cliCommand`, then+ * a host's door name, come first (see cli-command.mjs).*/import * as fs from 'node:fs';import * as path from 'node:path';+import {cliDoor, declaredCliCommand} from './cli-command.mjs';+import {CLI_ROOT} from '../fs/paths.mjs';+import {cliVersion, runChoice} from '../release/run-context.mjs';+import {isGlobalCopy} from '../release/choose.mjs';+import {isInReleaseCache} from '../release/cache.mjs';/*** A package manager we can install with and run binaries through.@@ -473,25 +479,73 @@ export function cliBinResolves(targetDir = process.cwd()) {}/**- * The safe, install-aware CLI invocation stem to suggest to users.+ * The CLI invocation stem every printed command starts with. The one picker:+ * every hint, error, Doctor fix and doc line that names a command goes through+ * it (directly, or through {@link formatCliCommand} and+ * {@link formatCliCommandsIn}). JSON fields that carry a command stay bare.*- * - The `astryx` bin resolves from `targetDir`: `<run-prefix> astryx`- * (e.g. `pnpm exec astryx`).- * - Launched one-off (npx/dlx cache), or the bin does not resolve from- * `targetDir` (a global install, a fresh package in a workspace):- * `<dlx-prefix> @astryxdesign/cli`. The bare `astryx` name would make npm- * fetch an unrelated registry package; the scoped package always resolves- * to this CLI.+ * In order:+ *+ * - The `cliCommand` an integration loaded in this project declares, e.g.+ * `acme astryx`. When two integrations declare different commands,+ * neither is used, the guess below is (even when a host set a door), and+ * `astryx doctor` warns.+ * - The door a host ran this call through (see cli-command.mjs). Empty in a+ * plain run.+ * - Otherwise the guess below.+ *+ * The guess names a command that, run from `targetDir`, reaches the release+ * that answered (spec AST-081 FR5):+ *+ * - The project's own CLI answered and its `astryx` bin resolves from+ * `targetDir`: `<run-prefix> astryx` (e.g. `pnpm exec astryx`).+ * - Outside a project, the CLI installed for the computer (or the release it+ * keeps) answered: `astryx`.+ * - Otherwise: `<dlx-prefix> @astryxdesign/cli@<answering version>`, pinned so+ * the package runner starts the same release. The bare `astryx` name would+ * make npm fetch an unrelated registry package, and the unpinned scoped+ * package the newest release.+ *+ * With `installed`, the line follows a step that installs the project's own+ * CLI (an update notice, the hint that matches a project's CLI to its Core),+ * so the guess is that CLI: `<run-prefix> astryx`. A declared `cliCommand`+ * and a host's door still come first.** @param {string} [targetDir] the project the printed command runs in;* defaults to the working directory+ * @param {{installed?: boolean}} [options]* @returns {string}*/-export function getCliInvocation(targetDir) {- if (isCliOneOff() || !cliBinResolves(targetDir)) {- return `${getDlxPrefix(targetDir)} ${CLI_PACKAGE}`;+export function getCliInvocation(targetDir, {installed = false} = {}) {+ const declared = declaredCliCommand(targetDir);+ if (declared.command) return declared.command;+ const guess = () =>+ installed+ ? `${getRunPrefix(targetDir)} ${CLI_BIN}`+ : guessCliInvocation(targetDir);+ if (declared.conflict) return guess();+ return cliDoor() ?? guess();+}++/**+ * The package-manager guess alone, without any integration's `cliCommand` or+ * a host's door. The picker falls back to it when declared commands conflict,+ * and Doctor names it then.+ *+ * @param {string} [targetDir]+ * @returns {string}+ */+export function guessCliInvocation(targetDir) {+ // Who answered this run decides the stem, so every command one run prints+ // reaches the same release, whichever folder a line names.+ const choice = runChoice(process.cwd());+ if (choice.copy === 'project' && !isCliOneOff() && cliBinResolves(targetDir)) {+ return `${getRunPrefix(targetDir)} ${CLI_BIN}`;+ }+ if (!choice.inProject && (isGlobalCopy(CLI_ROOT) || isInReleaseCache(CLI_ROOT))) {+ return CLI_BIN;}- return `${getRunPrefix(targetDir)} ${CLI_BIN}`;+ return `${getDlxPrefix(targetDir)} ${CLI_PACKAGE}@${cliVersion()}`;}/**@@ -513,6 +567,76 @@ export function formatCliCommand(command, targetDir) {return sub ? `${stem} ${sub}` : stem;}+/** Code-fence languages whose lines are shell commands. */+const SHELL_FENCES = new Set(['', 'bash', 'sh', 'shell', 'zsh', 'console']);++/** Code-fence languages that hold prose, such as a prompt to paste. */+const PROSE_FENCES = new Set(['text', 'txt', 'markdown', 'md']);++/** `astryx` where a shell line starts a command: line start, `$ `, `&&`, `||`, `;`, `|`. */+const SHELL_COMMAND = /(^\s*(?:\$\s+)?|(?:&&|\|\||;|\|)\s*)astryx(?=\s|$)/g;++/** `astryx` opening an inline code span: `` `astryx docs` `` or `` `astryx` ``. */+const INLINE_COMMAND = /`astryx(?=[\s`])/g;++/**+ * Prefix the CLI commands in one line.+ * @param {string} line+ * @param {string} stem+ * @param {string | null} lang the fence the line sits in; null for prose+ * @returns {string}+ */+function prefixLine(line, stem, lang) {+ if (lang == null) return line.replace(INLINE_COMMAND, `\`${stem}`);+ if (SHELL_FENCES.has(lang)) return line.replace(SHELL_COMMAND, `$1${stem}`);+ if (PROSE_FENCES.has(lang)) {+ return line+ .replace(INLINE_COMMAND, `\`${stem}`)+ .replace(SHELL_COMMAND, `$1${stem}`);+ }+ return line;+}++/**+ * Prefix every CLI command in doc text with `stem`, the invocation from+ * {@link getCliInvocation}.+ *+ * Docs, including an integration's, are written with bare `astryx ...`+ * commands; this rewrites them when they are shown. In prose, an inline code+ * span that starts with `astryx`. In a shell code fence (no language, `bash`,+ * `sh`, `shell`, `zsh`, `console`), each `astryx` that starts a command. In a+ * `text` or `markdown` fence, both. Other fences, and plain words, are left+ * alone. JSON output keeps the authored text.+ *+ * @param {string} text Markdown-style doc text, or the body of one code block.+ * @param {string} stem e.g. `pnpm exec astryx`+ * @param {string | null} [lang] the code block's language when `text` is one+ * block's body; omit for Markdown, whose fences are followed+ * @returns {string}+ */+export function prefixCliCommands(text, stem, lang = null) {+ if (stem === CLI_BIN) return String(text);+ const blockLang = lang == null ? null : lang.toLowerCase();+ /** @type {{marker: string, lang: string} | null} */+ let fence = null;+ return String(text)+ .split('\n')+ .map(line => {+ if (blockLang != null) return prefixLine(line, stem, blockLang);+ const marker = /^\s*(`{3,}|~{3,})\s*([\w-]*)/.exec(line);+ if (marker) {+ if (fence == null) {+ fence = {marker: marker[1], lang: marker[2].toLowerCase()};+ } else if (marker[1].startsWith(fence.marker)) {+ fence = null;+ }+ return line;+ }+ return prefixLine(line, stem, fence?.lang ?? null);+ })+ .join('\n');+}+/*** Quote one argument of a printed command so the shell it is pasted into* passes it on unchanged. Printed commands target a POSIX shell (sh, bash,diff --git a/packages/cli/foundation/env/package-manager.test.mjs b/packages/cli/foundation/env/package-manager.test.mjsindex 601a69ff80..6abb18ef9e 100644--- a/packages/cli/foundation/env/package-manager.test.mjs+++ b/packages/cli/foundation/env/package-manager.test.mjs@@ -12,10 +12,14 @@ import {isCliOneOff,cliBinResolves,getCliInvocation,+ guessCliInvocation,formatCliCommand,+ prefixCliCommands,quoteCommandArgument,commandInFolder,} from './package-manager.mjs';+import {recordDeclaredCliCommands, runWithCliDoor} from './cli-command.mjs';+import {CLI_VERSION} from '../../test-utils/release-fixtures.mjs';let tmpDir;const ORIGINAL_ARGV1 = process.argv[1];@@ -59,8 +63,16 @@ function linkCliBin(dir, name = 'astryx') {const binDir = path.join(dir, 'node_modules', '.bin');fs.mkdirSync(binDir, {recursive: true});fs.writeFileSync(path.join(binDir, name), '');+ // The installed package the bin belongs to: this copy, so the project's own+ // CLI is the one answering (spec AST-081 FR5's run-prefix case).+ const pkg = path.join(dir, 'node_modules', '@astryxdesign', 'cli');+ fs.mkdirSync(path.dirname(pkg), {recursive: true});+ if (!fs.existsSync(pkg)) fs.symlinkSync(THIS_CLI, pkg, 'dir');}+/** This CLI package's folder. */+const THIS_CLI = path.resolve(import.meta.dirname, '..', '..');+/** The header a classic Yarn (1.x) lockfile starts with. */const YARN_V1_LOCK ='# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.\n# yarn lockfile v1\n\n';@@ -534,11 +546,11 @@ describe('getCliInvocation', () => {// fresh package), the CLI used to print `npx astryx` for a project where that// bin does not resolve, so following the hint fetched someone else's package.it.each([- ['package-lock.json', '{}', 'npx @astryxdesign/cli'],- ['pnpm-lock.yaml', '', 'pnpm dlx @astryxdesign/cli'],- ['yarn.lock', YARN_BERRY_LOCK, 'yarn dlx @astryxdesign/cli'],- ['yarn.lock', YARN_V1_LOCK, 'npx @astryxdesign/cli'],- ['bun.lockb', '', 'bunx @astryxdesign/cli'],+ ['package-lock.json', '{}', `npx @astryxdesign/cli@${CLI_VERSION}`],+ ['pnpm-lock.yaml', '', `pnpm dlx @astryxdesign/cli@${CLI_VERSION}`],+ ['yarn.lock', YARN_BERRY_LOCK, `yarn dlx @astryxdesign/cli@${CLI_VERSION}`],+ ['yarn.lock', YARN_V1_LOCK, `npx @astryxdesign/cli@${CLI_VERSION}`],+ ['bun.lockb', '', `bunx @astryxdesign/cli@${CLI_VERSION}`],])('prints the scoped package for a project with no local CLI (%s), launched from an installed path',(lockfile, contents, expected) => {@@ -555,14 +567,14 @@ describe('getCliInvocation', () => {const dir = makeTmpDir();delete process.env.npm_config_user_agent;fs.writeFileSync(path.join(dir, 'package.json'), '{"name":"fresh"}');- expect(getCliInvocation(dir)).toBe('npx @astryxdesign/cli');+ expect(getCliInvocation(dir)).toBe(`npx @astryxdesign/cli@${CLI_VERSION}`);});it('uses the dlx runner + scoped package when run one-off', () => {process.argv[1] = '/home/u/.npm/_npx/a1b2/node_modules/.bin/astryx';const dir = makeTmpDir();delete process.env.npm_config_user_agent;- expect(getCliInvocation(dir)).toBe('npx @astryxdesign/cli');+ expect(getCliInvocation(dir)).toBe(`npx @astryxdesign/cli@${CLI_VERSION}`);});it('pairs the dlx runner with the scoped package for pnpm one-off', () => {@@ -570,7 +582,9 @@ describe('getCliInvocation', () => {'/home/u/.cache/pnpm/dlx/9f/node_modules/@astryxdesign/cli/bin/astryx.mjs';const dir = makeTmpDir();fs.writeFileSync(path.join(dir, 'pnpm-lock.yaml'), '');- expect(getCliInvocation(dir)).toBe('pnpm dlx @astryxdesign/cli');+ expect(getCliInvocation(dir)).toBe(+ `pnpm dlx @astryxdesign/cli@${CLI_VERSION}`,+ );});});@@ -598,9 +612,134 @@ describe('formatCliCommand', () => {const dir = makeTmpDir();fs.writeFileSync(path.join(dir, 'package-lock.json'), '{}');expect(formatCliCommand('astryx component Button', dir)).toBe(- 'npx @astryxdesign/cli component Button',+ `npx @astryxdesign/cli@${CLI_VERSION} component Button`,+ );+ });+});++describe('the picker: declared cliCommand, then the door, then the guess', () => {+ /** A pnpm project with the CLI installed: the guess is `pnpm exec astryx`. */+ function pnpmProject() {+ process.argv[1] = INSTALLED_ENTRY;+ const dir = makeTmpDir();+ fs.writeFileSync(path.join(dir, 'package.json'), '{"name":"app"}');+ fs.writeFileSync(path.join(dir, 'pnpm-lock.yaml'), '');+ linkCliBin(dir);+ return dir;+ }++ it('guesses when nothing is declared', () => {+ const dir = pnpmProject();+ recordDeclaredCliCommands(dir, [{name: '@acme/a'}]);+ expect(getCliInvocation(dir)).toBe('pnpm exec astryx');+ });++ it("uses an integration's cliCommand over the guess", () => {+ const dir = pnpmProject();+ recordDeclaredCliCommands(dir, [+ {name: '@acme/a', cliCommand: 'acme astryx'},+ {name: '@acme/b', cliCommand: 'acme astryx'},+ ]);+ expect(getCliInvocation(dir)).toBe('acme astryx');+ expect(formatCliCommand('astryx docs tokens', dir)).toBe(+ 'acme astryx docs tokens',+ );+ expect(guessCliInvocation(dir)).toBe('pnpm exec astryx');+ });++ it('falls back to the guess when integrations declare different commands', () => {+ const dir = pnpmProject();+ recordDeclaredCliCommands(dir, [+ {name: '@acme/a', cliCommand: 'acme astryx'},+ {name: '@acme/b', cliCommand: 'other astryx'},+ ]);+ expect(getCliInvocation(dir)).toBe('pnpm exec astryx');+ });++ it("puts a declared command ahead of a host's door", () => {+ const dir = pnpmProject();+ recordDeclaredCliCommands(dir, [+ {name: '@acme/a', cliCommand: 'acme astryx'},+ ]);+ expect(runWithCliDoor('astryx', () => getCliInvocation(dir))).toBe(+ 'acme astryx',);});++ it("uses a host's door when nothing is declared", () => {+ const dir = pnpmProject();+ recordDeclaredCliCommands(dir, []);+ expect(runWithCliDoor('astryx', () => getCliInvocation(dir))).toBe(+ 'astryx',+ );+ });++ it('guesses on a conflict even when a host set a door', () => {+ const dir = pnpmProject();+ recordDeclaredCliCommands(dir, [+ {name: '@acme/a', cliCommand: 'acme astryx'},+ {name: '@acme/b', cliCommand: 'other astryx'},+ ]);+ expect(runWithCliDoor('astryx', () => getCliInvocation(dir))).toBe(+ 'pnpm exec astryx',+ );+ });+});++describe('prefixCliCommands', () => {+ /** @param {string} text @param {string | null} [lang] */+ const shown = (text, lang) => prefixCliCommands(text, 'acme astryx', lang);++ it('prefixes inline code spans that run the CLI', () => {+ expect(+ shown('Run `astryx docs theme`, then `astryx`. Not `astryx.config.ts`.'),+ ).toBe(+ 'Run `acme astryx docs theme`, then `acme astryx`. Not `astryx.config.ts`.',+ );+ });++ it('prefixes commands in shell fences and leaves code fences alone', () => {+ const text = [+ '```bash',+ '# astryx in a comment stays',+ 'astryx doctor && astryx integration verify',+ '$ astryx docs',+ 'npm install @astryxdesign/cli',+ '```',+ '```tsx',+ 'astryx docs',+ '```',+ ].join('\n');+ expect(shown(text).split('\n')).toEqual([+ '```bash',+ '# astryx in a comment stays',+ 'acme astryx doctor && acme astryx integration verify',+ '$ acme astryx docs',+ 'npm install @astryxdesign/cli',+ '```',+ '```tsx',+ 'astryx docs',+ '```',+ ]);+ });++ it("follows one code block's language", () => {+ expect(shown('astryx docs', 'bash')).toBe('acme astryx docs');+ expect(shown('1. Read `astryx docs cli`.', 'text')).toBe(+ '1. Read `acme astryx docs cli`.',+ );+ expect(shown("const run = 'astryx docs';", 'ts')).toBe(+ "const run = 'astryx docs';",+ );+ });++ it('leaves plain prose alone', () => {+ expect(shown('Astryx and astryx themes')).toBe('Astryx and astryx themes');+ });++ it('changes nothing when the stem is the bare bin', () => {+ expect(prefixCliCommands('`astryx docs`', 'astryx')).toBe('`astryx docs`');+ });});describe('quoteCommandArgument', () => {diff --git a/packages/cli/foundation/env/project-scope.mjs b/packages/cli/foundation/env/project-scope.mjsnew file mode 100644index 0000000000..1f90013dfa--- /dev/null+++ b/packages/cli/foundation/env/project-scope.mjs@@ -0,0 +1,33 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Whether a folder is outside a project (spec AST-081 FR3).+ *+ * A folder is inside a project when the CLI finds a Core or a CLI installed+ * there or above it, or a package.json above it that declares either one; the+ * release choice already worked that out (foundation/release/run-context.mjs).+ * Outside a project, output never gives advice that works only inside one, such+ * as the setup reminder, the getting-started steps, or a step that adds a theme+ * to an app; each surface that prints such a step asks here first.+ *+ * @input a folder+ * @output whether it is outside a project+ * @position foundation/env — read by the setup reminder, init, doctor, upgrade,+ * and the theme, search, discover, and integration-check surfaces.+ */++import {runChoice} from '../release/run-context.mjs';++/**+ * True when `cwd` is outside any project.+ * @param {string} [cwd]+ * @returns {boolean}+ */+export function isOutsideProject(cwd = process.cwd()) {+ try {+ return !runChoice(cwd).inProject;+ } catch {+ // A folder the release choice cannot read keeps its in-project output.+ return false;+ }+}diff --git a/packages/cli/foundation/env/search-path.mjs b/packages/cli/foundation/env/search-path.mjsnew file mode 100644index 0000000000..02930d0fce--- /dev/null+++ b/packages/cli/foundation/env/search-path.mjs@@ -0,0 +1,205 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file The `astryx` commands on the computer's search path (spec AST-081+ * FR10, FR11): which program each one starts, in the order a shell tries+ * them, so `doctor`, `init --user`, and the update notices can tell the Astryx CLI+ * apart from another program and a release that predates the hand-off from+ * one that hands a project's run to the project's release.+ *+ * A command belongs to the Astryx CLI when its real file sits in the CLI+ * package (npm and Bun link it), or when it is a package manager's small shim+ * script that starts the CLI package's bin (npm on Windows, pnpm, Yarn); the+ * package folder is read from the shim's text.+ *+ * @input the search path and, on Windows, its executable names+ * @output one row per `astryx` command found+ * @position packages/cli/foundation/env — read by doctor, init --user, and+ * the update notices.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';++/** The CLI package whose bin the `astryx` command starts. */+const CLI_PACKAGE = '@astryxdesign/cli';++/** The bare command name. */+const COMMAND = 'astryx';++/** Shims are small; anything larger is a program, not a shim. */+const MAX_SHIM_BYTES = 64 * 1024;++/**+ * A CLI package folder named in a shim's text, with the shim's own folder+ * written as `$basedir` (sh), `%~dp0` or `%dp0%` (cmd), or `$PSScriptRoot`+ * (PowerShell).+ */+const SHIM_PACKAGE =+ /((?:\$basedir(?:_abs|_win)?|%~dp0|%dp0%|\$PSScriptRoot)?[^"'\s:;$%]*node_modules[\\/]@astryxdesign[\\/]cli)(?=[\\/"'])/gu;++/** The shim folder written in a shim's text, in each shell's spelling. */+const SHIM_BASE =+ /^(?:\$basedir(?:_abs|_win)?|%~dp0|%dp0%|\$PSScriptRoot)[\\/]?/u;++/**+ * The absolute target some package managers record in a shim's comment+ * (`# cmd-shim-target=<file>`).+ */+const SHIM_TARGET_LINE = /^\s*(?:#|@?rem|::)\s*cmd-shim-target=(.+?)\s*$/imu;++/**+ * @typedef {object} SearchPathCommand+ * @property {string} file the command as the shell finds it+ * @property {boolean} astryx whether it starts the Astryx CLI+ * @property {string | null} cliRoot the CLI package it starts, when known+ * @property {string | null} version that package's version, when known+ * @property {boolean | null} handsOff whether that release hands a project's+ * run to the project's release (spec AST-081 FR9); `null` when unknown+ */++/**+ * The CLI package's version, when `dir` is the Astryx CLI package.+ * @param {string} dir+ * @returns {string | null}+ */+function cliVersionAt(dir) {+ try {+ const pkg = JSON.parse(+ fs.readFileSync(path.join(dir, 'package.json'), 'utf8'),+ );+ return pkg?.name === CLI_PACKAGE ? String(pkg.version ?? '') : null;+ } catch {+ return null;+ }+}++/**+ * Releases that hand off carry the release-choice module.+ * @param {string} dir+ * @returns {boolean}+ */+function handsOffAt(dir) {+ return fs.existsSync(path.join(dir, 'foundation', 'release', 'choose.mjs'));+}++/**+ * The Astryx CLI package an executable starts, or null.+ * @param {string} file+ * @returns {string | null}+ */+export function astryxCliRootOf(file) {+ let real;+ try {+ real = fs.realpathSync(file);+ } catch {+ return null;+ }+ for (let dir = path.dirname(real); ;) {+ if (cliVersionAt(dir) !== null) return dir;+ const parent = path.dirname(dir);+ if (parent === dir) break;+ dir = parent;+ }+ let text;+ try {+ if (fs.statSync(real).size > MAX_SHIM_BYTES) return null;+ text = fs.readFileSync(real, 'utf8');+ } catch {+ return null;+ }+ const base = path.dirname(file);+ const target = SHIM_TARGET_LINE.exec(text)?.[1];+ if (target && path.isAbsolute(target)) {+ for (let dir = path.dirname(target); ;) {+ if (cliVersionAt(dir) !== null) return dir;+ const parent = path.dirname(dir);+ if (parent === dir) break;+ dir = parent;+ }+ }+ for (const match of text.matchAll(SHIM_PACKAGE)) {+ const named = match[1]+ .replace(SHIM_BASE, `${base}${path.sep}`)+ .replace(/[\\/]/gu, path.sep);+ const dir = path.resolve(base, named);+ if (cliVersionAt(dir) !== null) return dir;+ }+ return null;+}++/**+ * Whether a small script names the CLI package's files, even when that+ * package cannot be read from here.+ * @param {string} file+ * @returns {boolean}+ */+function namesCliPackage(file) {+ try {+ const real = fs.realpathSync(file);+ if (fs.statSync(real).size > MAX_SHIM_BYTES) return false;+ return /node_modules[\\/]@astryxdesign[\\/]cli[\\/]/u.test(+ fs.readFileSync(real, 'utf8'),+ );+ } catch {+ return false;+ }+}++/**+ * Every `astryx` command on the search path, in the order a shell tries+ * them. The first row is the one that runs.+ * @param {{searchPath?: string, platform?: NodeJS.Platform}} [options]+ * @returns {SearchPathCommand[]}+ */+export function astryxCommandsOnSearchPath({+ searchPath = process.env.PATH ?? process.env.Path ?? '',+ platform = process.platform,+} = {}) {+ const windows = platform === 'win32';+ const names = windows+ ? ['astryx.cmd', 'astryx.exe', 'astryx.ps1', 'astryx']+ : [COMMAND];+ /** @type {SearchPathCommand[]} */+ const rows = [];+ const seen = new Set();+ for (const dir of searchPath.split(windows ? ';' : path.delimiter)) {+ if (!dir) continue;+ for (const name of names) {+ const file = path.join(dir, name);+ let stat;+ try {+ stat = fs.statSync(file);+ } catch {+ continue;+ }+ if (!stat.isFile()) continue;+ if (!windows) {+ try {+ fs.accessSync(file, fs.constants.X_OK);+ } catch {+ continue;+ }+ }+ let key = file;+ try {+ key = fs.realpathSync(file);+ } catch {+ // Keep the path as found.+ }+ if (seen.has(key)) break;+ seen.add(key);+ const cliRoot = astryxCliRootOf(file);+ rows.push({+ file,+ astryx: cliRoot !== null || namesCliPackage(file),+ cliRoot,+ version: cliRoot ? cliVersionAt(cliRoot) : null,+ handsOff: cliRoot ? handsOffAt(cliRoot) : null,+ });+ // One command per folder: the shell runs the first name it finds.+ break;+ }+ }+ return rows;+}diff --git a/packages/cli/foundation/env/search-path.test.mjs b/packages/cli/foundation/env/search-path.test.mjsnew file mode 100644index 0000000000..0d4cbcef40--- /dev/null+++ b/packages/cli/foundation/env/search-path.test.mjs@@ -0,0 +1,122 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Reading the `astryx` commands on the search path (spec AST-081+ * FR11): links, and each package manager's shim, down to the CLI package and+ * its version.+ */++import {afterEach, describe, expect, it} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {astryxCommandsOnSearchPath, astryxCliRootOf} from './search-path.mjs';+import {+ cleanupFixtures,+ tempDir,+ writeJson,+} from '../../test-utils/release-fixtures.mjs';++afterEach(cleanupFixtures);++/**+ * A CLI package at `dir`, with or without the hand-off.+ * @param {string} dir+ * @param {string} version+ * @param {boolean} [handsOff]+ */+function cliPackage(dir, version, handsOff = false) {+ writeJson(path.join(dir, 'package.json'), {+ name: '@astryxdesign/cli',+ version,+ });+ if (handsOff) {+ fs.mkdirSync(path.join(dir, 'foundation', 'release'), {recursive: true});+ fs.writeFileSync(path.join(dir, 'foundation', 'release', 'choose.mjs'), '');+ }+ return dir;+}++/**+ * An executable shim at `file` with `text`.+ * @param {string} file+ * @param {string} text+ */+function shim(file, text) {+ fs.mkdirSync(path.dirname(file), {recursive: true});+ fs.writeFileSync(file, text);+ fs.chmodSync(file, 0o755);+ return file;+}++describe.skipIf(process.platform === 'win32')('astryxCliRootOf', () => {+ it('reads a pnpm 10 shim ($basedir)', () => {+ const home = tempDir('pnpm');+ const pkg = cliPackage(+ path.join(home, 'global', '5', 'node_modules', '@astryxdesign', 'cli'),+ '0.6.8',+ );+ const bin = shim(+ path.join(home, 'astryx'),+ '#!/bin/sh\nbasedir=$(dirname "$0")\nexec node "$basedir/global/5/node_modules/@astryxdesign/cli/clients/cli/bin/astryx.mjs" "$@"\n',+ );+ expect(astryxCliRootOf(bin)).toBe(pkg);+ });++ it('reads a pnpm 12 shim ($basedir_abs, a folder above the shim)', () => {+ const home = tempDir('pnpm12');+ const pkg = cliPackage(+ path.join(+ home,+ 'global',+ 'v11',+ '3f2a',+ 'node_modules',+ '@astryxdesign',+ 'cli',+ ),+ '0.6.8',+ );+ const bin = shim(+ path.join(home, 'bin', 'astryx'),+ [+ '#!/bin/sh',+ 'basedir=$(dirname "$(echo "$0" | sed -e \'s,\\\\,/,g\')")',+ 'basedir_abs=$(cd "$basedir" && pwd)',+ 'exec node "$basedir_abs/../global/v11/3f2a/node_modules/@astryxdesign/cli/clients/cli/bin/astryx.mjs" "$@"',+ '',+ ].join('\n'),+ );+ expect(astryxCliRootOf(bin)).toBe(pkg);+ const [row] = astryxCommandsOnSearchPath({+ searchPath: path.dirname(bin),+ platform: 'linux',+ });+ expect(row).toEqual({+ file: bin,+ astryx: true,+ cliRoot: pkg,+ version: '0.6.8',+ handsOff: false,+ });+ });++ it('reads a cmd-shim-target comment with an absolute target', () => {+ const elsewhere = tempDir('target');+ const pkg = cliPackage(+ path.join(elsewhere, 'node_modules', '@astryxdesign', 'cli'),+ '0.8.0',+ true,+ );+ const bin = shim(+ path.join(tempDir('bin'), 'astryx'),+ `#!/bin/sh\n# cmd-shim-target=${path.join(pkg, 'clients', 'cli', 'bin', 'astryx.mjs')}\nexec node "$TARGET" "$@"\n`,+ );+ expect(astryxCliRootOf(bin)).toBe(pkg);+ expect(+ astryxCommandsOnSearchPath({+ searchPath: path.dirname(bin),+ platform: 'linux',+ })[0],+ ).toMatchObject({version: '0.8.0', handsOff: true});+ });+});diff --git a/packages/cli/foundation/env/user-dirs.mjs b/packages/cli/foundation/env/user-dirs.mjsnew file mode 100644index 0000000000..787bd73913--- /dev/null+++ b/packages/cli/foundation/env/user-dirs.mjs@@ -0,0 +1,93 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file The per-user folders the CLI may write to (spec AST-081 FR7): the+ * platform's cache directory and its configuration directory, each with an+ * `astryx` folder of its own.+ *+ * A folder named by the platform's own environment setting+ * (`XDG_CACHE_HOME`, `XDG_CONFIG_HOME`, `LOCALAPPDATA`, `APPDATA`) is used+ * only when it is an absolute path; a relative one is ignored, as the XDG+ * base directory rules require, so a run never writes into the folder it+ * starts in.+ *+ * @input the home folder, the platform, and those standard settings+ * @output absolute folder paths+ * @position packages/cli/foundation/env+ */++import * as os from 'node:os';+import * as path from 'node:path';++/**+ * An environment folder setting, when it names an absolute path.+ * @param {string | undefined} value+ * @returns {string | null}+ */+export function absoluteDirSetting(value) {+ return typeof value === 'string' && value !== '' && path.isAbsolute(value)+ ? value+ : null;+}++/**+ * @typedef {object} UserDirOptions+ * @property {string} [home] the home folder; defaults to the current user's+ * @property {NodeJS.Platform} [platform]+ * @property {Record<string, string | undefined>} [env]+ */++/**+ * The CLI's per-user cache folder: `~/.cache/astryx` on Linux (or+ * `$XDG_CACHE_HOME/astryx`), `~/Library/Caches/astryx` on macOS, and+ * `%LOCALAPPDATA%\astryx\Cache` on Windows.+ * @param {UserDirOptions} [options]+ * @returns {string}+ */+export function userCacheDir({+ home = os.homedir(),+ platform = process.platform,+ env = process.env,+} = {}) {+ const join = platform === 'win32' ? path.win32.join : path.join;+ if (platform === 'win32') {+ return join(+ absoluteDirSetting(env.LOCALAPPDATA) ?? join(home, 'AppData', 'Local'),+ 'astryx',+ 'Cache',+ );+ }+ if (platform === 'darwin') return join(home, 'Library', 'Caches', 'astryx');+ return join(+ absoluteDirSetting(env.XDG_CACHE_HOME) ?? join(home, '.cache'),+ 'astryx',+ );+}++/**+ * The CLI's per-user configuration folder: `~/.config/astryx` on Linux (or+ * `$XDG_CONFIG_HOME/astryx`), `~/Library/Application Support/astryx` on+ * macOS, and `%APPDATA%\astryx` on Windows.+ * @param {UserDirOptions} [options]+ * @returns {string}+ */+export function userConfigDir({+ home = os.homedir(),+ platform = process.platform,+ env = process.env,+} = {}) {+ const join = platform === 'win32' ? path.win32.join : path.join;+ if (platform === 'win32') {+ return join(+ absoluteDirSetting(env.APPDATA) ?? join(home, 'AppData', 'Roaming'),+ 'astryx',+ );+ }+ if (platform === 'darwin') {+ return join(home, 'Library', 'Application Support', 'astryx');+ }+ return join(+ absoluteDirSetting(env.XDG_CONFIG_HOME) ?? join(home, '.config'),+ 'astryx',+ );+}diff --git a/packages/cli/foundation/env/user-dirs.test.mjs b/packages/cli/foundation/env/user-dirs.test.mjsnew file mode 100644index 0000000000..b791321b24--- /dev/null+++ b/packages/cli/foundation/env/user-dirs.test.mjs@@ -0,0 +1,72 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import * as path from 'node:path';+import {describe, expect, it} from 'vitest';+import {absoluteDirSetting, userCacheDir, userConfigDir} from './user-dirs.mjs';++const home = path.join(path.sep, 'home', 'ada');++describe('per-user folders (spec AST-081 FR7)', () => {+ it('uses the platform defaults', () => {+ expect(userCacheDir({home, platform: 'linux', env: {}})).toBe(+ path.join(home, '.cache', 'astryx'),+ );+ expect(userConfigDir({home, platform: 'linux', env: {}})).toBe(+ path.join(home, '.config', 'astryx'),+ );+ expect(userCacheDir({home, platform: 'darwin', env: {}})).toBe(+ path.join(home, 'Library', 'Caches', 'astryx'),+ );+ expect(userConfigDir({home, platform: 'darwin', env: {}})).toBe(+ path.join(home, 'Library', 'Application Support', 'astryx'),+ );+ });++ it('uses an absolute XDG setting and ignores a relative or empty one', () => {+ const xdg = path.join(path.sep, 'xdg');+ expect(+ userCacheDir({home, platform: 'linux', env: {XDG_CACHE_HOME: xdg}}),+ ).toBe(path.join(xdg, 'astryx'));+ expect(+ userConfigDir({home, platform: 'linux', env: {XDG_CONFIG_HOME: xdg}}),+ ).toBe(path.join(xdg, 'astryx'));+ for (const value of ['rel-cache', './cache', '']) {+ expect(+ userCacheDir({home, platform: 'linux', env: {XDG_CACHE_HOME: value}}),+ ).toBe(path.join(home, '.cache', 'astryx'));+ expect(+ userConfigDir({home, platform: 'linux', env: {XDG_CONFIG_HOME: value}}),+ ).toBe(path.join(home, '.config', 'astryx'));+ }+ });++ it.skipIf(process.platform !== 'win32')(+ 'uses LOCALAPPDATA and APPDATA on Windows only when absolute',+ () => {+ const winHome = 'C:\\Users\\ada';+ expect(+ userCacheDir({+ home: winHome,+ platform: 'win32',+ env: {LOCALAPPDATA: 'D:\\Local'},+ }),+ ).toBe('D:\\Local\\astryx\\Cache');+ expect(+ userConfigDir({+ home: winHome,+ platform: 'win32',+ env: {APPDATA: 'Roaming'},+ }),+ ).toBe('C:\\Users\\ada\\AppData\\Roaming\\astryx');+ },+ );++ it('reads only absolute folder settings', () => {+ expect(absoluteDirSetting(undefined)).toBeNull();+ expect(absoluteDirSetting('')).toBeNull();+ expect(absoluteDirSetting('cache')).toBeNull();+ expect(absoluteDirSetting(path.resolve('cache'))).toBe(+ path.resolve('cache'),+ );+ });+});diff --git a/packages/cli/foundation/env/user-settings.mjs b/packages/cli/foundation/env/user-settings.mjsnew file mode 100644index 0000000000..e479d8f12d--- /dev/null+++ b/packages/cli/foundation/env/user-settings.mjs@@ -0,0 +1,106 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file The CLI's per-user settings file (spec AST-081 FR8):+ * `astryx/settings.json` in the platform's per-user configuration folder.+ *+ * It holds the person's choices about the computer-level agent text:+ *+ * ```json+ * {"computerAgentText": {"install": true, "links": ["/home/me/.claude/skills/astryx"]}}+ * ```+ *+ * - `computerAgentText.install`: `false` after `astryx init --user+ * --remove-agents`, `true` after `astryx init --user`. A missing file or+ * value means install.+ * - `computerAgentText.links`: the links to the skill folder Astryx made, so+ * removal removes exactly those.+ *+ * Only `astryx init --user` and the global copy's refresh change it. No environment variable or option+ * does. A file that cannot be read or parsed counts as missing, and one that+ * cannot be written never fails a run.+ *+ * @input the per-user configuration folder+ * @output the settings, and writes to them+ * @position packages/cli/foundation/env+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {userConfigDir} from './user-dirs.mjs';++/**+ * @typedef {object} ComputerAgentTextSettings+ * @property {boolean} install Whether the computer-level text is wanted.+ * @property {string[]} links The links to its skill folder Astryx made, so+ * removal removes exactly those.+ */++/**+ * The settings file's path.+ * @param {string} [configDir]+ * @returns {string}+ */+export function settingsFile(configDir = userConfigDir()) {+ return path.join(configDir, 'settings.json');+}++/**+ * The whole settings object; `{}` when the file is missing or unreadable.+ * @param {string} [configDir]+ * @returns {Record<string, unknown>}+ */+export function readSettings(configDir = userConfigDir()) {+ try {+ const value = JSON.parse(fs.readFileSync(settingsFile(configDir), 'utf8'));+ return value && typeof value === 'object' && !Array.isArray(value)+ ? value+ : {};+ } catch {+ return {};+ }+}++/**+ * The person's choices about the computer-level agent text.+ * @param {string} [configDir]+ * @returns {ComputerAgentTextSettings}+ */+export function computerAgentTextSettings(configDir = userConfigDir()) {+ const raw = readSettings(configDir).computerAgentText;+ const value =+ raw && typeof raw === 'object' && !Array.isArray(raw)+ ? /** @type {Record<string, unknown>} */ (raw)+ : {};+ const links = Array.isArray(value.links)+ ? value.links.filter(link => typeof link === 'string')+ : [];+ return {install: value.install !== false, links};+}++/**+ * Record the person's choices about the computer-level agent text, keeping+ * every other setting. Returns whether the file was written.+ * @param {ComputerAgentTextSettings} choice+ * @param {string} [configDir]+ * @returns {boolean}+ */+export function recordComputerAgentTextSettings(+ choice,+ configDir = userConfigDir(),+) {+ const next = {+ ...readSettings(configDir),+ computerAgentText: {install: choice.install, links: choice.links},+ };+ const file = settingsFile(configDir);+ try {+ fs.mkdirSync(path.dirname(file), {recursive: true});+ const tmp = `${file}.${process.pid}.tmp`;+ fs.writeFileSync(tmp, `${JSON.stringify(next, null, 2)}\n`);+ fs.renameSync(tmp, file);+ return true;+ } catch {+ return false;+ }+}diff --git a/packages/cli/foundation/env/user-settings.test.mjs b/packages/cli/foundation/env/user-settings.test.mjsnew file mode 100644index 0000000000..ba08990aac--- /dev/null+++ b/packages/cli/foundation/env/user-settings.test.mjs@@ -0,0 +1,64 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {afterEach, describe, expect, it} from 'vitest';+import {+ computerAgentTextSettings,+ readSettings,+ recordComputerAgentTextSettings,+ settingsFile,+} from './user-settings.mjs';++/** @type {string[]} */+const dirs = [];+const tmp = () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-settings-'));+ dirs.push(dir);+ return dir;+};+afterEach(() => {+ for (const dir of dirs.splice(0)) {+ fs.rmSync(dir, {recursive: true, force: true});+ }+});++describe('the settings file (spec AST-081 FR8)', () => {+ it('means install, with no links, when missing or unreadable', () => {+ const dir = tmp();+ expect(computerAgentTextSettings(dir)).toEqual({install: true, links: []});+ fs.writeFileSync(settingsFile(dir), 'not json');+ expect(readSettings(dir)).toEqual({});+ expect(computerAgentTextSettings(dir)).toEqual({install: true, links: []});+ });++ it('records and reads the choice and the links Astryx made, keeping other settings', () => {+ const dir = tmp();+ fs.writeFileSync(settingsFile(dir), '{"other":true}');+ expect(+ recordComputerAgentTextSettings(+ {install: true, links: ['/h/.claude/skills/astryx']},+ dir,+ ),+ ).toBe(true);+ expect(JSON.parse(fs.readFileSync(settingsFile(dir), 'utf8'))).toEqual({+ other: true,+ computerAgentText: {install: true, links: ['/h/.claude/skills/astryx']},+ });+ expect(computerAgentTextSettings(dir)).toEqual({+ install: true,+ links: ['/h/.claude/skills/astryx'],+ });+ recordComputerAgentTextSettings({install: false, links: []}, dir);+ expect(computerAgentTextSettings(dir)).toEqual({install: false, links: []});+ });++ it('never fails when the folder cannot be written', () => {+ const file = path.join(tmp(), 'file');+ fs.writeFileSync(file, '');+ expect(+ recordComputerAgentTextSettings({install: false, links: []}, file),+ ).toBe(false);+ });+});diff --git a/packages/cli/foundation/fs/file-protection.mjs b/packages/cli/foundation/fs/file-protection.mjsindex 739e79d331..208557efc8 100644--- a/packages/cli/foundation/fs/file-protection.mjs+++ b/packages/cli/foundation/fs/file-protection.mjs@@ -9,8 +9,22 @@*/import * as fs from 'node:fs';+import {createRequire} from 'node:module';import * as path from 'node:path';-import ignore from 'ignore';++/**+ * The `ignore` matcher factory, loaded on first use: this module is reached+ * from every CLI run through the agent-docs helpers, and only a run that+ * classifies a file needs the matcher.+ * @type {typeof import('ignore') | undefined}+ */+let ignoreFactory;++/** @param {import('ignore').Options} [options] */+function ignore(options) {+ ignoreFactory ??= createRequire(import.meta.url)('ignore');+ return /** @type {typeof import('ignore')} */ (ignoreFactory)(options);+}const DEPENDENCY_DIRS = new Set(['node_modules',diff --git a/packages/cli/foundation/fs/module-loader.stdout.test.mjs b/packages/cli/foundation/fs/module-loader.stdout.test.mjsindex ac52809253..66dedeb1f9 100644--- a/packages/cli/foundation/fs/module-loader.stdout.test.mjs+++ b/packages/cli/foundation/fs/module-loader.stdout.test.mjs@@ -14,6 +14,7 @@ import * as fs from 'node:fs';import * as os from 'node:os';import * as path from 'node:path';import {fileURLToPath, pathToFileURL} from 'node:url';+import {CLI_VERSION} from '../../test-utils/release-fixtures.mjs';const HERE = path.dirname(fileURLToPath(import.meta.url));const LOADER_URL = pathToFileURL(path.join(HERE, 'module-loader.mjs')).href;@@ -268,7 +269,7 @@ describe('--json stdout stays one envelope when project modules print', () => {write('package.json', JSON.stringify({name: 'consumer', private: true}));write('node_modules/@astryxdesign/core/package.json',- JSON.stringify({name: '@astryxdesign/core', version: '0.6.3'}),+ JSON.stringify({name: '@astryxdesign/core', version: CLI_VERSION}),);write('astryx.config.js',@@ -289,7 +290,7 @@ describe('--json stdout stays one envelope when project modules print', () => {);write('node_modules/@astryxdesign/core/package.json',- JSON.stringify({name: '@astryxdesign/core', version: '0.6.3'}),+ JSON.stringify({name: '@astryxdesign/core', version: CLI_VERSION}),);write('astryx.config.mjs',diff --git a/packages/cli/foundation/fs/path-compare.mjs b/packages/cli/foundation/fs/path-compare.mjsnew file mode 100644index 0000000000..4338b50c6a--- /dev/null+++ b/packages/cli/foundation/fs/path-compare.mjs@@ -0,0 +1,73 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Path comparison that matches the file system (spec AST-081 FR11):+ * Windows and macOS file systems ignore letter case by default, so two+ * spellings that differ only in case name the same folder there, and the+ * release choice must treat them as one.+ *+ * @input paths and the platform+ * @output whether two paths are the same, and a path relative to a folder+ * @position packages/cli/foundation/fs — used by the release choice and the+ * release cache.+ */++import * as path from 'node:path';++/**+ * Whether the platform's file systems ignore letter case by default.+ * @param {NodeJS.Platform} [platform]+ * @returns {boolean}+ */+export function ignoresCase(platform = process.platform) {+ return platform === 'win32' || platform === 'darwin';+}++/**+ * The path module of a platform.+ * @param {NodeJS.Platform} platform+ * @returns {typeof path.posix}+ */+function pathsOf(platform) {+ return platform === 'win32' ? path.win32 : path.posix;+}++/**+ * A path in the form two spellings of one folder share.+ * @param {string} p+ * @param {NodeJS.Platform} [platform]+ * @returns {string}+ */+export function pathKey(p, platform = process.platform) {+ const normal = pathsOf(platform).normalize(p);+ return ignoresCase(platform) ? normal.toLowerCase() : normal;+}++/**+ * Whether two paths name the same folder or file.+ * @param {string} a+ * @param {string} b+ * @param {NodeJS.Platform} [platform]+ * @returns {boolean}+ */+export function samePath(a, b, platform = process.platform) {+ return pathKey(a, platform) === pathKey(b, platform);+}++/**+ * `child` relative to `parent`, compared the way the file system compares+ * names; `null` when `child` is not inside `parent` (or is `parent`).+ * @param {string} parent+ * @param {string} child+ * @param {NodeJS.Platform} [platform]+ * @returns {string | null}+ */+export function relativeWithin(parent, child, platform = process.platform) {+ const paths = pathsOf(platform);+ const rel = paths.relative(+ pathKey(parent, platform),+ pathKey(child, platform),+ );+ if (rel === '' || rel.startsWith('..') || paths.isAbsolute(rel)) return null;+ return rel;+}diff --git a/packages/cli/foundation/fs/paths.mjs b/packages/cli/foundation/fs/paths.mjsindex 1232336830..8c99105b03 100644--- a/packages/cli/foundation/fs/paths.mjs+++ b/packages/cli/foundation/fs/paths.mjs@@ -11,17 +11,144 @@ import {createRequire} from 'node:module';import * as path from 'node:path';import {fileURLToPath} from 'node:url';import {listDir, pathExists} from './listing-cache.mjs';+import {ERROR_CODES} from '../response/error-codes.mjs';+import {carriedCore, runChoice} from '../release/run-context.mjs';+import {findDeclaringPackage} from '../release/project.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));/** Root of the @astryxdesign/cli package */export const CLI_ROOT = path.resolve(__dirname, '..', '..');+/**+ * The Core a command answers from: the project's (see+ * {@link findProjectCoreDir}), else, when a copy other than the project's own+ * CLI answers, the Core that copy carries (spec AST-081 FR3): the+ * `@astryxdesign/core` of its own release, beside it or in the per-user+ * release cache. Never fetches; {@link requireCoreDir} does.+ *+ * Commands that judge or change a project (`doctor`, `swizzle`, `upgrade`)+ * read {@link findProjectCoreDir} instead, so a carried Core never passes a+ * project check or lands in a folder that installed none.+ *+ * @param {string} [startDir]+ * @returns {string | null}+ */+export function findCoreDir(startDir = process.cwd()) {+ return findProjectCoreDir(startDir) ?? carriedCoreFor(startDir).dir;+}++/**+ * Why a command that reads Core cannot run, when the answering release's own+ * Core is needed and cannot be installed: outside a project, or in a project+ * with nothing installed (spec AST-081 FR3).+ * @param {{unavailable: string | null, version?: string, reason?: string}} found+ * @param {boolean} inProject+ * @returns {string}+ */+export function unavailableCoreMessage(found, inProject) {+ const unwritable = /cannot be written/.test(found.unavailable ?? '');+ if (inProject) {+ const core = found.version ? `Core ${found.version}` : 'its Core';+ const why = found.reason ? ` (${found.reason})` : '';+ return `This project has no Core installed, and ${core} could not be downloaded${why}. Install the project's dependencies${unwritable ? ', or make that folder writable' : ''}, then run again.`;+ }+ return `${found.unavailable}. Outside a project, commands that read Core use the Core of the release that answers; ${unwritable ? 'make that folder writable and run again' : 'run again when the package registry can be reached'}.`;+}++/**+ * Like {@link findCoreDir}, but a copy that carries no Core installs its+ * release's Core into the per-user cache first. Throws ERR_CORE_NOT_FOUND+ * when there is no Core to answer from, and ERR_VERSIONS_UNAVAILABLE when the+ * carried Core is needed and cannot be installed.+ *+ * @param {string} [startDir]+ * @returns {string}+ */+export function requireCoreDir(startDir = process.cwd()) {+ const found = findProjectCoreDir(startDir) ?? carriedCoreFor(startDir, true);+ if (typeof found === 'string') return found;+ if (found.unavailable) {+ throw codedError(+ unavailableCoreMessage(found, runChoice(startDir).inProject),+ ERROR_CODES.ERR_VERSIONS_UNAVAILABLE,+ );+ }+ if (found.dir) return found.dir;+ throw codedError(+ 'Could not find @astryxdesign/core package',+ ERROR_CODES.ERR_CORE_NOT_FOUND,+ );+}++/**+ * An Error carrying a stable error code, which the JSON envelope and every+ * command's error output read the way they read an API error's.+ * @param {string} message+ * @param {string} code+ * @returns {Error & {code: string}}+ */+function codedError(message, code) {+ return Object.assign(new Error(message), {code});+}++/**+ * The carried Core alone, for a caller that already looked for the project's+ * Core its own way: the folder, or null when the copy answering in `startDir`+ * is the project's own CLI or carries none.+ * @param {string} startDir+ * @param {{fetch?: boolean}} [options]+ * @returns {string | null}+ */+export function findCarriedCoreDir(startDir, {fetch = false} = {}) {+ return carriedCoreFor(startDir, fetch).dir;+}++/**+ * The carried Core for a run in `startDir`, when the copy answering there is+ * not the project's own CLI.+ * @param {string} startDir+ * @param {boolean} [fetch]+ * @returns {{dir: string | null, unavailable: string | null, version?: string, reason?: string}}+ */+function carriedCoreFor(startDir, fetch = false) {+ const carried = carriedCore({fetch: false});+ if (!carried.dir && !fetch) return carried;+ if (runChoice(startDir).copy === 'project') {+ return {dir: null, unavailable: null};+ }+ return carried.dir ? carried : carriedCore({fetch: true});+}+/*** Find packages/core directory by walking up from startDir.* Also checks node_modules/@astryxdesign/core for installed usage.+ *+ * The project's Core only: in the folder or four above it, the reach every+ * released version used, else from the folder of the package.json that makes+ * the folder part of a project, however deep the folder is.+ *+ * @param {string} [startDir]+ * @returns {string | null}*/-export function findCoreDir(startDir = process.cwd()) {+export function findProjectCoreDir(startDir = process.cwd()) {+ const near = findNearbyCoreDir(startDir);+ if (near) return near;+ // A folder deeper than that reach still belongs to the project the walk to+ // its package.json finds, so its Core is looked up from there too (spec+ // AST-081, a folder's project): never the carried Core in its place.+ const declaring = findDeclaringPackage(startDir);+ return declaring && declaring.dir !== path.resolve(startDir)+ ? findNearbyCoreDir(declaring.dir)+ : null;+}++/**+ * The Core installed in `startDir` or one of the four folders above it.+ * @param {string} startDir+ * @returns {string | null}+ */+function findNearbyCoreDir(startDir) {let dir = startDir;for (let i = 0; i < 5; i++) {@@ -153,7 +280,7 @@ export function discoverExternalPackages(startDir = process.cwd()) {if (!nodeModulesDir) return externals;/** @param {string} searchDir */- const scanDir = (searchDir) => {+ const scanDir = searchDir => {if (!fs.existsSync(searchDir)) return;const entries = fs.readdirSync(searchDir, {withFileTypes: true});@@ -236,7 +363,8 @@ export function existsCaseExact(targetPath, rootDir) {const rel = path.relative(rootDir, targetPath);if (rel === '') return true;- if (path.isAbsolute(rel) || rel === '..' || rel.startsWith(`..${path.sep}`)) return false;+ if (path.isAbsolute(rel) || rel === '..' || rel.startsWith(`..${path.sep}`))+ return false;let dir = rootDir;for (const segment of rel.split(path.sep)) {diff --git a/packages/cli/foundation/fs/paths.test.mjs b/packages/cli/foundation/fs/paths.test.mjsindex c34c9ec792..7fdcef4cef 100644--- a/packages/cli/foundation/fs/paths.test.mjs+++ b/packages/cli/foundation/fs/paths.test.mjs@@ -4,7 +4,9 @@ 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 {findCoreDir, findProjectRoot, listComponents, discoverExternalPackages, existsCaseExact, findInstalledPackage} from './paths.mjs';+import {findCoreDir, findProjectCoreDir, findProjectRoot, listComponents, discoverExternalPackages, existsCaseExact, findInstalledPackage} from './paths.mjs';+import {CLI_ROOT} from './paths.mjs';+import {linkThisCliAsProjectCli} from '../../test-utils/release-fixtures.mjs';let tmpDir;@@ -39,6 +41,13 @@ describe('findCoreDir', () => {});it('returns null when nothing found', () => {+ expect(findProjectCoreDir(tmpDir)).toBeNull();+ });++ it('falls back to the carried Core outside a project, and only there', () => {+ // This copy's carried Core is the workspace Core beside it.+ expect(findCoreDir(tmpDir)).toBe(path.resolve(CLI_ROOT, '..', 'core'));+ linkThisCliAsProjectCli(tmpDir);expect(findCoreDir(tmpDir)).toBeNull();});});diff --git a/packages/cli/foundation/integrations/computer-integrations.mjs b/packages/cli/foundation/integrations/computer-integrations.mjsnew file mode 100644index 0000000000..d714f07110--- /dev/null+++ b/packages/cli/foundation/integrations/computer-integrations.mjs@@ -0,0 +1,316 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Computer-level integrations (spec AST-081 FR12): the integration+ * packages installed in the same install root as the running copy of the CLI,+ * such as a package manager's global folder beside a global copy, or the+ * package set a door installs together.+ *+ * - The install root is the folder whose `node_modules` holds the running+ * CLI package (above pnpm's `.pnpm` store). pnpm 11 and later give each+ * global package a folder of its own, and every one of them counts. A+ * package runner's temporary install and the per-user release cache are not+ * install roots: they hold what one run asked for.+ * - When the root has a package.json, its declared dependencies are read, as+ * autolink reads a project's; otherwise (npm's global folder) every package+ * directly in its `node_modules`, scoped ones included. Either way, only a+ * package with exactly one root `astryx.integration.*` manifest counts, and+ * the CLI and Core packages never do.+ * - Outside a project they load as a project's integrations do (Project.load).+ * One whose declared `@astryxdesign/core` or `@astryxdesign/cli` peer range+ * excludes the answering release is skipped, and doctor says why.+ * - Inside a project none load; discover lists the ones the project does not+ * install as available, and doctor names them.+ *+ * Listing reads package.json files only; nothing is imported until a load.+ *+ * @input the running CLI package's folder+ * @output the computer-level integration candidates, and their loaded records+ * @position foundation/integrations — read by config/project, discover, and+ * doctor.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {findManifestPaths, loadIntegrations} from './integrations.mjs';+import {+ readDeclaredDependencies,+ resolveInstalledPackageDir,+} from './autolink.mjs';+import {installPlaceOf} from '../release/choose.mjs';+import {isInReleaseCache} from '../release/cache.mjs';+import {satisfiesRange} from '../env/semver.mjs';++/** Packages that are the CLI itself, never an integration of it. */+const NOT_INTEGRATIONS = new Set(['@astryxdesign/cli', '@astryxdesign/core']);++/** Peers whose ranges must admit the answering release. */+const RELEASE_PEERS = ['@astryxdesign/core', '@astryxdesign/cli'];++/**+ * @typedef {object} ComputerIntegrationCandidate+ * @property {string} name the package name+ * @property {string | undefined} version+ * @property {string | undefined} description+ * @property {string} packageDir+ * @property {string} hostDir the folder whose node_modules holds it+ * @property {string | null} incompatible why its peer ranges exclude the+ * answering release, or null+ */++/**+ * @param {string} p+ * @returns {string}+ */+function real(p) {+ try {+ return fs.realpathSync(p);+ } catch {+ return path.resolve(p);+ }+}++/**+ * @param {string} dir+ * @returns {Record<string, any> | null}+ */+function readPackage(dir) {+ try {+ const pkg = JSON.parse(+ fs.readFileSync(path.join(dir, 'package.json'), 'utf8'),+ );+ return pkg && typeof pkg === 'object' ? pkg : null;+ } catch {+ return null;+ }+}++/**+ * The install root of the CLI package at `cliRoot`, or null when it has none+ * that counts: it is not installed in a `node_modules` folder, or it lives in+ * a package runner's temporary install or the per-user release cache.+ * @param {string} cliRoot+ * @param {{cacheDir?: string}} [options]+ * @returns {string | null}+ */+export function computerInstallRoot(cliRoot, options = {}) {+ const root = real(cliRoot);+ const place = installPlaceOf(root);+ if (place.runner || !place.owner) return null;+ if (isInReleaseCache(root, options.cacheDir)) return null;+ return place.owner;+}++/**+ * Every install root that holds packages installed with the CLI at+ * `cliRoot`. Usually one: its install root. pnpm 11 and later install each+ * global package in a folder of its own, `<pnpm home>/global/v<N>/<id>`, with+ * its files in `<pnpm home>/store/v<N>/links` or inside that folder, so every+ * such global folder counts, provided one of them installs this CLI.+ * @param {string} cliRoot+ * @param {{cacheDir?: string}} [options]+ * @returns {string[]}+ */+export function computerInstallRoots(cliRoot, options = {}) {+ const fromPnpm = pnpmGlobalFolders(real(cliRoot));+ if (fromPnpm.length > 0) return fromPnpm;+ const root = computerInstallRoot(cliRoot, options);+ return root ? [root] : [];+}++/**+ * pnpm's global folders for a CLI installed globally by pnpm 11 or later, or+ * none. Its files are either in pnpm's store (`<home>/store/v<N>/links/...`,+ * with the global virtual store) or inside its own global folder+ * (`<home>/global/v<N>/<id>/node_modules/...`, without it).+ * @param {string} cli the CLI package's real path+ * @returns {string[]}+ */+function pnpmGlobalFolders(cli) {+ const parts = cli.split(/[\\/]/);+ /** @type {string | null} */+ let globalDir = null;+ const storeAt = parts.lastIndexOf('store');+ if (+ storeAt > 0 &&+ /^v\d+$/.test(parts[storeAt + 1] ?? '') &&+ parts[storeAt + 2] === 'links'+ ) {+ const home = parts.slice(0, storeAt).join(path.sep) || path.sep;+ globalDir = path.join(home, 'global', parts[storeAt + 1]);+ } else {+ const at = parts.findIndex(+ (part, k) =>+ part === 'global' &&+ /^v\d+$/.test(parts[k + 1] ?? '') &&+ parts[k + 3] === 'node_modules',+ );+ if (at > 0) globalDir = parts.slice(0, at + 2).join(path.sep) || path.sep;+ }+ if (globalDir == null) return [];+ /** @type {string[]} */+ let names;+ try {+ names = fs.readdirSync(globalDir).sort();+ } catch {+ return [];+ }+ const folders = names+ .map(name => path.join(globalDir, name))+ .filter(dir => fs.existsSync(path.join(dir, 'package.json')));+ const installsThisCli = folders.some(+ dir => real(path.join(dir, 'node_modules', '@astryxdesign', 'cli')) === cli,+ );+ return installsThisCli ? folders : [];+}++/**+ * Every package name directly in `<root>/node_modules`, scoped ones included.+ * @param {string} root+ * @returns {string[]}+ */+function installedNames(root) {+ const modules = path.join(root, 'node_modules');+ /** @type {string[]} */+ const names = [];+ /** @type {fs.Dirent[]} */+ let entries;+ try {+ entries = fs.readdirSync(modules, {withFileTypes: true});+ } catch {+ return names;+ }+ for (const entry of entries) {+ if (entry.name.startsWith('.')) continue;+ if (entry.name.startsWith('@')) {+ try {+ for (const scoped of fs.readdirSync(path.join(modules, entry.name))) {+ if (!scoped.startsWith('.')) names.push(`${entry.name}/${scoped}`);+ }+ } catch {+ // An unreadable scope folder holds nothing to read.+ }+ } else {+ names.push(entry.name);+ }+ }+ return names.sort();+}++/**+ * Why `pkg`'s peer ranges exclude `release`, or null when they admit it.+ * @param {Record<string, any>} pkg+ * @param {string} release the answering release's version+ * @returns {string | null}+ */+export function peerProblem(pkg, release) {+ const peers = pkg.peerDependencies;+ if (!peers || typeof peers !== 'object') return null;+ for (const peer of RELEASE_PEERS) {+ const range = peers[peer];+ if (typeof range !== 'string') continue;+ let admits;+ try {+ admits = satisfiesRange(release, range);+ } catch {+ // A range this CLI cannot read never keeps the integration out.+ admits = true;+ }+ if (!admits) {+ return `it needs ${peer} ${range}, and this computer's CLI is ${release}`;+ }+ }+ return null;+}++/**+ * The computer-level integrations installed beside the CLI at `cliRoot`, in+ * name order (declaration order when the root declares them). Reads+ * package.json files only.+ * @param {{cliRoot: string, release: string, cacheDir?: string}} options+ * @returns {ComputerIntegrationCandidate[]}+ */+export function scanComputerIntegrations({cliRoot, release, cacheDir}) {+ const self = real(cliRoot);+ /** @type {ComputerIntegrationCandidate[]} */+ const found = [];+ const seen = new Set();+ for (const root of computerInstallRoots(cliRoot, {cacheDir})) {+ scanRoot(root, {self, release, found, seen});+ }+ return found;+}++/**+ * Add the integrations installed in one install root.+ * @param {string} root+ * @param {{self: string, release: string, found: ComputerIntegrationCandidate[], seen: Set<string>}} into+ */+function scanRoot(root, {self, release, found, seen}) {+ const declared = readPackage(root)+ ? readDeclaredDependencies(root).map(d => d.name)+ : installedNames(root);+ for (const name of declared) {+ if (NOT_INTEGRATIONS.has(name)) continue;+ const resolved = resolveInstalledPackageDir(name, root);+ if (!resolved) continue;+ const identity = real(resolved.packageDir);+ if (identity === self || seen.has(identity)) continue;+ if (findManifestPaths(resolved.packageDir).length !== 1) continue;+ const pkg = readPackage(resolved.packageDir);+ if (!pkg || typeof pkg.name !== 'string') continue;+ if (NOT_INTEGRATIONS.has(pkg.name)) continue;+ seen.add(identity);+ found.push({+ name: pkg.name,+ version: typeof pkg.version === 'string' ? pkg.version : undefined,+ description:+ typeof pkg.description === 'string' ? pkg.description : undefined,+ packageDir: resolved.packageDir,+ hostDir: resolved.hostDir,+ incompatible: peerProblem(pkg, release),+ });+ }+}++/**+ * Load the compatible computer-level integrations as provider candidates,+ * each in isolation, under the autolinked policy (a broken one is recorded+ * and contributes nothing; the same package reached twice loads once). Each+ * loaded record is marked `__computer`. An incompatible one is not loaded.+ * @param {ComputerIntegrationCandidate[]} candidates+ * @param {{fresh?: boolean, exclude?: Iterable<string>}} [options] `exclude`+ * names packages the folder already loads, which keep their own copy+ * @returns {Promise<import('./provider-resolution.mjs').ProviderCandidate[]>}+ */+export async function loadComputerIntegrations(candidates, options = {}) {+ const {fresh = false, exclude = []} = options;+ const taken = new Set(exclude);+ /** @type {import('./provider-resolution.mjs').ProviderCandidate[]} */+ const loaded = [];+ for (const candidate of candidates) {+ if (candidate.incompatible || taken.has(candidate.name)) continue;+ try {+ const [integration] = await loadIntegrations([candidate.name], {+ cwd: candidate.hostDir,+ fresh,+ });+ loaded.push({+ source: 'autolinked',+ spec: candidate.name,+ packageDir: candidate.packageDir,+ ...(integration == null+ ? {}+ : {integration: {...integration, __computer: true}}),+ });+ } catch (error) {+ loaded.push({+ source: 'autolinked',+ spec: candidate.name,+ packageDir: candidate.packageDir,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ }+ return loaded;+}diff --git a/packages/cli/foundation/integrations/computer-integrations.test.mjs b/packages/cli/foundation/integrations/computer-integrations.test.mjsnew file mode 100644index 0000000000..fd9fd5b737--- /dev/null+++ b/packages/cli/foundation/integrations/computer-integrations.test.mjs@@ -0,0 +1,292 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Computer-level integrations (spec AST-081 FR12): which install root+ * counts, which packages in it are integrations, and the peer-range check.+ */++import {afterEach, describe, expect, it} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {+ computerInstallRoot,+ computerInstallRoots,+ loadComputerIntegrations,+ peerProblem,+ scanComputerIntegrations,+} from './computer-integrations.mjs';+import {+ cleanupFixtures,+ tempDir,+ writeJson,+} from '../../test-utils/release-fixtures.mjs';++afterEach(cleanupFixtures);++/**+ * A package at `dir`, with a manifest when `manifest` is set.+ * @param {string} dir+ * @param {Record<string, unknown>} pkg+ * @param {string | null} [manifest]+ */+function pkgAt(dir, pkg, manifest = 'export default {};\n') {+ writeJson(path.join(dir, 'package.json'), pkg);+ if (manifest != null) {+ fs.writeFileSync(path.join(dir, 'astryx.integration.mjs'), manifest);+ }+ return dir;+}++/** An npm-style global folder (no package.json) holding the CLI and others. */+function npmGlobal() {+ const root = path.join(tempDir('prefix'), 'lib');+ const modules = path.join(root, 'node_modules');+ const cli = pkgAt(+ path.join(modules, '@astryxdesign', 'cli'),+ {name: '@astryxdesign/cli', version: '0.8.0'},+ null,+ );+ pkgAt(path.join(modules, '@astryxdesign', 'core'), {+ name: '@astryxdesign/core',+ version: '0.8.0',+ });+ pkgAt(path.join(modules, '@acme', 'widgets'), {+ name: '@acme/widgets',+ version: '1.2.0',+ description: 'Acme widgets',+ });+ pkgAt(path.join(modules, 'plain-tool'), {name: 'plain-tool'}, null);+ pkgAt(path.join(modules, 'zeta-kit'), {+ name: 'zeta-kit',+ version: '2.0.0',+ peerDependencies: {'@astryxdesign/core': '>=9.0.0'},+ });+ return {root, cli};+}++describe('computerInstallRoot', () => {+ it('is the folder whose node_modules holds the CLI; none for a runner cache or a folder outside node_modules', () => {+ const {root, cli} = npmGlobal();+ expect(computerInstallRoot(cli)).toBe(fs.realpathSync(root));+ const runner = pkgAt(+ path.join(+ tempDir('npx'),+ '_npx',+ 'ab12',+ 'node_modules',+ '@astryxdesign',+ 'cli',+ ),+ {name: '@astryxdesign/cli', version: '0.8.0'},+ null,+ );+ expect(computerInstallRoot(runner)).toBeNull();+ expect(computerInstallRoot(tempDir('checkout'))).toBeNull();+ });++ it('is none for a release in the per-user release cache', () => {+ const cacheDir = tempDir('cache');+ const cli = pkgAt(+ path.join(+ cacheDir,+ 'releases',+ '0.8.0',+ 'node_modules',+ '@astryxdesign',+ 'cli',+ ),+ {name: '@astryxdesign/cli', version: '0.8.0'},+ null,+ );+ expect(computerInstallRoot(cli, {cacheDir})).toBeNull();+ });+});++describe('computerInstallRoots', () => {+ it("is pnpm's shared global folder before pnpm 11", () => {+ const g5 = path.join(tempDir('pnpm'), 'global', '5');+ const cli = pkgAt(+ path.join(+ g5,+ '.pnpm',+ '@[email protected]',+ 'node_modules',+ '@astryxdesign',+ 'cli',+ ),+ {name: '@astryxdesign/cli', version: '0.8.0'},+ null,+ );+ expect(computerInstallRoots(cli)).toEqual([fs.realpathSync(g5)]);+ });++ it('is every pnpm global folder since pnpm 11, when one of them installs this CLI', () => {+ const home = tempDir('pnpm-home');+ const cli = pkgAt(+ path.join(+ home,+ 'store',+ 'v11',+ 'links',+ '@astryxdesign',+ 'cli',+ '0.8.0',+ 'h',+ 'node_modules',+ '@astryxdesign',+ 'cli',+ ),+ {name: '@astryxdesign/cli', version: '0.8.0'},+ null,+ );+ const a = path.join(home, 'global', 'v11', 'a');+ const b = path.join(home, 'global', 'v11', 'b');+ writeJson(path.join(b, 'package.json'), {+ dependencies: {'@acme/widgets': '1.0.0'},+ });+ // No global folder installs this CLI yet: only its own install root.+ expect(computerInstallRoots(cli)).toHaveLength(1);+ writeJson(path.join(a, 'package.json'), {+ dependencies: {'@astryxdesign/cli': '0.8.0'},+ });+ fs.mkdirSync(path.join(a, 'node_modules', '@astryxdesign'), {+ recursive: true,+ });+ fs.symlinkSync(cli, path.join(a, 'node_modules', '@astryxdesign', 'cli'));+ expect(computerInstallRoots(cli)).toEqual([a, b]);+ });++ it("is every pnpm global folder when the CLI's files sit inside its own global folder (pnpm 12)", () => {+ const globalDir = path.join(tempDir('pnpm12'), 'global', 'v11');+ const a = path.join(globalDir, 'a');+ const b = path.join(globalDir, 'b');+ writeJson(path.join(a, 'package.json'), {+ dependencies: {'@astryxdesign/cli': '0.8.0'},+ });+ const cli = pkgAt(+ path.join(+ a,+ 'node_modules',+ '.pnpm',+ '@[email protected]',+ 'node_modules',+ '@astryxdesign',+ 'cli',+ ),+ {name: '@astryxdesign/cli', version: '0.8.0'},+ null,+ );+ fs.mkdirSync(path.join(a, 'node_modules', '@astryxdesign'), {+ recursive: true,+ });+ fs.symlinkSync(cli, path.join(a, 'node_modules', '@astryxdesign', 'cli'));+ writeJson(path.join(b, 'package.json'), {+ dependencies: {'@acme/widgets': '1.0.0'},+ });+ pkgAt(path.join(b, 'node_modules', '@acme', 'widgets'), {+ name: '@acme/widgets',+ version: '1.0.0',+ });+ expect(computerInstallRoots(cli)).toEqual([+ fs.realpathSync(a),+ fs.realpathSync(b),+ ]);+ expect(+ scanComputerIntegrations({cliRoot: cli, release: '0.8.0'}).map(+ c => c.name,+ ),+ ).toEqual(['@acme/widgets']);+ });+});++describe('scanComputerIntegrations', () => {+ it('lists every package beside the CLI that ships a manifest, never the CLI or Core, and marks an incompatible one', () => {+ const {cli} = npmGlobal();+ const found = scanComputerIntegrations({cliRoot: cli, release: '0.8.0'});+ expect(found.map(c => [c.name, c.version, c.incompatible])).toEqual([+ ['@acme/widgets', '1.2.0', null],+ [+ 'zeta-kit',+ '2.0.0',+ "it needs @astryxdesign/core >=9.0.0, and this computer's CLI is 0.8.0",+ ],+ ]);+ expect(found[0].description).toBe('Acme widgets');+ });++ it("reads a door's package set from the root's declared dependencies", () => {+ const root = tempDir('runtime');+ writeJson(path.join(root, 'package.json'), {+ name: 'runtime',+ private: true,+ dependencies: {+ '@astryxdesign/cli': '0.8.0',+ '@astryxdesign/core': '0.8.0',+ '@acme/meta-kit': '3.0.0',+ },+ });+ const modules = path.join(root, 'node_modules');+ const cli = pkgAt(+ path.join(modules, '@astryxdesign', 'cli'),+ {name: '@astryxdesign/cli', version: '0.8.0'},+ null,+ );+ pkgAt(path.join(modules, '@acme', 'meta-kit'), {+ name: '@acme/meta-kit',+ version: '3.0.0',+ });+ // Installed but not declared: not part of the set.+ pkgAt(path.join(modules, 'stray-kit'), {name: 'stray-kit'});+ expect(+ scanComputerIntegrations({cliRoot: cli, release: '0.8.0'}).map(+ c => c.name,+ ),+ ).toEqual(['@acme/meta-kit']);+ });++ it('lists nothing for a copy with no install root', () => {+ expect(+ scanComputerIntegrations({+ cliRoot: tempDir('checkout'),+ release: '0.8.0',+ }),+ ).toEqual([]);+ });+});++describe('peerProblem', () => {+ it('checks the Core and CLI peer ranges against the answering release', () => {+ expect(peerProblem({}, '0.8.0')).toBeNull();+ expect(+ peerProblem(+ {peerDependencies: {'@astryxdesign/core': '^0.8.0'}},+ '0.8.2',+ ),+ ).toBeNull();+ expect(+ peerProblem(+ {peerDependencies: {'@astryxdesign/cli': '>=0.9.0'}},+ '0.8.2',+ ),+ ).toBe(+ "it needs @astryxdesign/cli >=0.9.0, and this computer's CLI is 0.8.2",+ );+ expect(+ peerProblem({peerDependencies: {react: '>=99'}}, '0.8.2'),+ ).toBeNull();+ });+});++describe('loadComputerIntegrations', () => {+ it("loads the compatible ones, marked as the computer's, and leaves out excluded and incompatible ones", async () => {+ const {cli} = npmGlobal();+ const found = scanComputerIntegrations({cliRoot: cli, release: '0.8.0'});+ const loaded = await loadComputerIntegrations(found);+ expect(loaded.map(c => [c.spec, c.integration?.__computer])).toEqual([+ ['@acme/widgets', true],+ ]);+ expect(+ await loadComputerIntegrations(found, {exclude: ['@acme/widgets']}),+ ).toEqual([]);+ });+});diff --git a/packages/cli/foundation/integrations/integration-warnings.mjs b/packages/cli/foundation/integrations/integration-warnings.mjsindex ffbf7b3ef7..826426667d 100644--- a/packages/cli/foundation/integrations/integration-warnings.mjs+++ b/packages/cli/foundation/integrations/integration-warnings.mjs@@ -21,6 +21,7 @@*/import {validateLoadedIntegration} from './validate-contributions.mjs';+import {formatCliCommand} from '../env/package-manager.mjs';/*** For each configured (already-loaded) integration, compute its issues using@@ -81,8 +82,8 @@ export async function warnOnIntegrationIssues(source, {json = false} = {}) {for (const [pkg, count] of issueCounts) {const command = fromProject- ? 'astryx doctor'- : `astryx doctor integration validate ${pkg}`;+ ? formatCliCommand('doctor')+ : formatCliCommand(`doctor integration validate ${pkg}`);console.error(`Warning: ${pkg} has ${count} integration issue(s). Run: ${command}`,);diff --git a/packages/cli/foundation/integrations/integration-warnings.test.mjs b/packages/cli/foundation/integrations/integration-warnings.test.mjsindex 536ffd3593..9451537846 100644--- a/packages/cli/foundation/integrations/integration-warnings.test.mjs+++ b/packages/cli/foundation/integrations/integration-warnings.test.mjs@@ -61,9 +61,8 @@ describe('warnOnIntegrationIssues', () => {await warnOnIntegrationIssues([integration], {json: false});expect(errLines).toHaveLength(1);- expect(errLines[0]).toBe(- 'Warning: @acme/widgets has 1 integration issue(s). ' +- 'Run: astryx doctor integration validate @acme/widgets',+ expect(errLines[0]).toMatch(+ /^Warning: @acme\/widgets has 1 integration issue\(s\)\. Run: .+ doctor integration validate @acme\/widgets$/,);});@@ -81,9 +80,10 @@ describe('warnOnIntegrationIssues', () => {await warnOnIntegrationIssues(project, {json: false});- expect(errLines).toEqual([- 'Warning: @acme/later has 1 integration issue(s). Run: astryx doctor',- ]);+ expect(errLines).toHaveLength(1);+ expect(errLines[0]).toMatch(+ /^Warning: @acme\/later has 1 integration issue\(s\)\. Run: .+ doctor$/,+ );});it('emits nothing in --json mode (keeps stdout/JSON clean)', async () => {@@ -103,9 +103,8 @@ describe('warnOnIntegrationIssues', () => {await warnOnIntegrationIssues([integration], {json: false});expect(errLines).toHaveLength(1);- expect(errLines[0]).toBe(- 'Warning: @acme/stale has 1 integration issue(s). ' +- 'Run: astryx doctor integration validate @acme/stale',+ expect(errLines[0]).toMatch(+ /^Warning: @acme\/stale has 1 integration issue\(s\)\. Run: .+ doctor integration validate @acme\/stale$/,);});diff --git a/packages/cli/foundation/integrations/integrations.mjs b/packages/cli/foundation/integrations/integrations.mjsindex 83ccb30769..2340e1e452 100644--- a/packages/cli/foundation/integrations/integrations.mjs+++ b/packages/cli/foundation/integrations/integrations.mjs@@ -6,7 +6,8 @@* Integrations are PACKAGE NAMES listed in astryx.config.{ts,mjs,js}. Each* package declares a single conventional root manifest sibling to its* package.json — astryx.integration.{ts,mjs,js} — which contributes- * components/templates/codemods/docs/themes roots and an optional issuesUrl.+ * components/templates/codemods/docs/themes roots, an optional issuesUrl, and+ * an optional cliCommand.* Stable provider identity and package metadata come from package.json, not the* manifest.*@@ -24,6 +25,7 @@ import {normalizeProviderId} from '../identity/provider-identity.mjs';// the loader can isolate an invalid optional contribution from valid roots.import {parseAgentDocsField,+ parseCliCommandField,parseIntegrationBase,unknownIntegrationKeys,} from '../../authoring/integration/schema.mjs';@@ -51,6 +53,10 @@ import {resolveProviders} from './provider-resolution.mjs';* @property {string} [themes]* @property {string} [issuesUrl]* @property {{append?: readonly string[]}} [agentDocs]+ * @property {string} [cliCommand] the command this package's users run the+ * CLI with; read by the picker in foundation/env (see cli-command.mjs)+ * @property {string} [__cliCommandError] why a declared `cliCommand` was+ * ignored; the rest of the manifest still contributes* @property {string} [__agentDocsError] contribution-specific validation* failure; other manifest contributions remain available* @property {string} __spec@@ -70,6 +76,9 @@ import {resolveProviders} from './provider-resolution.mjs';* @property {boolean} [__autolinked] loaded because the project declares the* package as a dependency and it ships a manifest, with no astryx.config* entry naming it — see foundation/integrations/autolink.mjs+ * @property {boolean} [__computer] loaded because it is installed beside the+ * running CLI and the folder is outside a project (spec AST-081 FR12) — see+ * foundation/integrations/computer-integrations.mjs* @property {boolean} [__local] loaded from the package containing the current* working directory, so an author sees the exact bytes they are editing* @property {string} [__dependencyField] for an autolinked integration, the@@ -204,7 +213,7 @@ function parseDiscoverSourceExport(value, label) {* @param {string} file absolute manifest path* @param {string} [label] used in error messages* @param {{fresh?: boolean}} [options]- * @returns {Promise<{manifest: import('../../authoring/integration/type').AstryxIntegration, unknownKeys: string[], debug?: import('../../authoring/debug/type').DebugEventHandler, gapReport?: import('../../authoring/gap-report/type').GapReportHandler, gapReportError?: string, discover?: import('../../authoring/discover/type').DiscoverSource, discoverError?: string, agentDocsError?: string}>}+ * @returns {Promise<{manifest: import('../../authoring/integration/type').AstryxIntegration, unknownKeys: string[], debug?: import('../../authoring/debug/type').DebugEventHandler, gapReport?: import('../../authoring/gap-report/type').GapReportHandler, gapReportError?: string, discover?: import('../../authoring/discover/type').DiscoverSource, discoverError?: string, agentDocsError?: string, cliCommandError?: string}>}*/export async function loadManifest(file,@@ -239,8 +248,31 @@ export async function loadManifest(}}+ /** @type {string | undefined} */+ let cliCommand;+ /** @type {string | undefined} */+ let cliCommandError;+ const rawCliCommand =+ raw != null && typeof raw === 'object' && !Array.isArray(raw)+ ? /** @type {{cliCommand?: unknown}} */ (raw).cliCommand+ : undefined;+ if (rawCliCommand !== undefined) {+ try {+ cliCommand = parseCliCommandField(+ rawCliCommand,+ `${label} field "cliCommand"`,+ );+ } catch (err) {+ cliCommandError = err instanceof Error ? err.message : String(err);+ }+ }+return {- manifest: agentDocs == null ? baseManifest : {...baseManifest, agentDocs},+ manifest: {+ ...baseManifest,+ ...(agentDocs == null ? {} : {agentDocs}),+ ...(cliCommand == null ? {} : {cliCommand}),+ },unknownKeys: unknownIntegrationKeys(raw),debug:typeof mod?.debug === 'function'@@ -253,6 +285,7 @@ export async function loadManifest(discover: discover.source,discoverError: discover.error,agentDocsError,+ cliCommandError,};}@@ -375,6 +408,8 @@ export async function loadLocalIntegration(packageDir, {fresh = false} = {}) {let discoverError;/** @type {string | undefined} */let agentDocsError;+ /** @type {string | undefined} */+ let cliCommandError;try {({manifest,@@ -385,6 +420,7 @@ export async function loadLocalIntegration(packageDir, {fresh = false} = {}) {discover: discoverSource,discoverError,agentDocsError,+ cliCommandError,} = await loadManifest(manifestFile, `Integration ${spec}`, {fresh}));} catch (err) {return {@@ -422,6 +458,8 @@ export async function loadLocalIntegration(packageDir, {fresh = false} = {}) {themes: resolveRoot(manifest.themes),issuesUrl: manifest.issuesUrl,agentDocs: manifest.agentDocs,+ cliCommand: manifest.cliCommand,+ __cliCommandError: cliCommandError,__agentDocsError: agentDocsError,__unknownKeys: unknownKeys,__debug: debugHandler,@@ -486,6 +524,8 @@ export async function loadIntegrations(let discoverError;/** @type {string | undefined} */let agentDocsError;+ /** @type {string | undefined} */+ let cliCommandError;try {({manifest,@@ -496,6 +536,7 @@ export async function loadIntegrations(discover: discoverSource,discoverError,agentDocsError,+ cliCommandError,} = await loadManifest(manifestFile, `Integration ${spec}`, {fresh}));} catch (err) {// A manifest that throws on import or fails schema validation must NOT take@@ -540,6 +581,8 @@ export async function loadIntegrations(themes: resolveRoot(manifest.themes),issuesUrl: manifest.issuesUrl,agentDocs: manifest.agentDocs,+ cliCommand: manifest.cliCommand,+ __cliCommandError: cliCommandError,__agentDocsError: agentDocsError,__unknownKeys: unknownKeys,__debug: debugHandler,diff --git a/packages/cli/foundation/integrations/validate-contributions.mjs b/packages/cli/foundation/integrations/validate-contributions.mjsindex 1ec498918c..6836f1f42e 100644--- a/packages/cli/foundation/integrations/validate-contributions.mjs+++ b/packages/cli/foundation/integrations/validate-contributions.mjs@@ -59,6 +59,9 @@ import {discoverIntegrationThemes} from '../discovery/theme-discovery.mjs';/** Stable issue code for an invalid optional agent-doc contribution. */export const INVALID_AGENT_DOCS = 'invalid_agent_docs';+/** Stable issue code for a `cliCommand` that was ignored as invalid. */+export const INVALID_CLI_COMMAND = 'invalid_cli_command';+/** Stable issue code for a package whose provider ID is already claimed. */export const DUPLICATE_PROVIDER = 'duplicate_provider';@@ -479,6 +482,14 @@ export async function validateLoadedIntegration(loaded) {if (loaded.__agentDocsError) {issues.push(issueError(INVALID_AGENT_DOCS, loaded.__agentDocsError));}+ if (loaded.__cliCommandError) {+ issues.push(+ issueWarning(+ INVALID_CLI_COMMAND,+ `${loaded.__cliCommandError}. The command is ignored; printed commands use the package-manager prefix.`,+ ),+ );+ }checkRoots({components: loaded.components,diff --git a/packages/cli/foundation/release/agent-text-worker.mjs b/packages/cli/foundation/release/agent-text-worker.mjsnew file mode 100644index 0000000000..528951062e--- /dev/null+++ b/packages/cli/foundation/release/agent-text-worker.mjs@@ -0,0 +1,52 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file The global copy's background step that keeps the computer-level+ * agent text installed (spec AST-081 FR8), as its own detached process.+ *+ * Started by `maybeKeepAgentText` (global-state.mjs) from the global copy,+ * with one argument, the per-user configuration folder. It writes the files+ * the person's settings choose, with this release's text and the plain `astryx` command, and keeps every file a+ * person edited, every file without the Astryx markers, and every link, as+ * `astryx init --user` does. It then records this release as the one that+ * wrote the text. It writes nothing to any stream and never reaches a+ * person: it is not a command and takes no options.+ *+ * @input argv[2]: the per-user configuration folder (the state file's); the+ * settings file+ * @output the computer-level agent text and the updated global state on disk+ * @position foundation/release — one of the two detached processes the CLI+ * starts; the other is refresh-worker.mjs.+ */++import {fileURLToPath} from 'node:url';+import {+ COMPUTER_COMMAND,+ writeComputerAgentText,+} from '../agent-docs/computer-agent-text.mjs';+import {+ computerAgentTextSettings,+ recordComputerAgentTextSettings,+} from '../env/user-settings.mjs';+import {recordAgentTextWritten} from './global-state.mjs';+import {readJson} from './project.mjs';++const stateDir = process.argv[2];+if (stateDir) {+ try {+ const settings = computerAgentTextSettings();+ if (settings.install) {+ const {links} = writeComputerAgentText({command: COMPUTER_COMMAND});+ recordComputerAgentTextSettings({+ install: true,+ links: [...new Set([...settings.links, ...links])],+ });+ const pkg = readJson(+ fileURLToPath(new URL('../../package.json', import.meta.url)),+ );+ recordAgentTextWritten(pkg?.version ?? null, stateDir);+ }+ } catch {+ // A home folder that cannot be written is tried again later.+ }+}diff --git a/packages/cli/foundation/release/cache.mjs b/packages/cli/foundation/release/cache.mjsnew file mode 100644index 0000000000..a871103726--- /dev/null+++ b/packages/cli/foundation/release/cache.mjs@@ -0,0 +1,1216 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file The per-user cache of CLI releases.+ *+ * Global mode answers some runs with a release other than the copy that+ * started them (spec AST-081 FR2, FR6): the release that matches a project's+ * Core, the newest release for the global copy, or the Core a copy carries+ * outside a project. Each is installed here, once, through the package+ * manager, and reused by every later run:+ *+ * <user cache>/astryx/releases/<version>/+ * package.json (an empty private package)+ * node_modules/@astryxdesign/cli+ * node_modules/@astryxdesign/core+ * release.json (written last: the release is verified)+ *+ * A release counts only once `release.json` exists. It is written after the+ * install finished, the CLI started and reported its own version, and the+ * release supports this computer's Node. An install builds in a temporary+ * folder beside the others and is renamed into place, so a run never sees a+ * half-installed release, and a lock keeps two runs from installing the same+ * release at once.+ *+ * The package manager is npm, started from the Node that runs the CLI, so the+ * registry, proxy, and offline settings in the user's npm configuration+ * apply. No Astryx setting changes where or how releases install.+ *+ * @input a release version+ * @output the release's folder, or why it is unavailable+ * @position foundation/release — used by the bin's hand-off, by the carried+ * Core lookup, and by the background refresh worker.+ */++import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {spawnSync} from 'node:child_process';+import {createHash} from 'node:crypto';+import {fileURLToPath} from 'node:url';+import {satisfiesRange} from '../env/semver.mjs';+import {readJson} from './project.mjs';+import {userCacheDir as userCacheDirFor} from '../env/user-dirs.mjs';+import {foreignLockIsSilent} from './lock-lease.mjs';+import {relativeWithin} from '../fs/path-compare.mjs';++/**+ * The per-user cache directory every Astryx cache lives in, never inside a+ * project (`foundation/env/user-dirs.mjs`).+ * @returns {string}+ */+export function userCacheDir() {+ return userCacheDirFor();+}++/**+ * The folder all cached releases live in.+ * @param {string} [cacheDir]+ * @returns {string}+ */+export function releasesDir(cacheDir = userCacheDir()) {+ return path.join(cacheDir, 'releases');+}++/** A release version safe to use as a folder name and an npm spec. */+const VERSION_RE = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;++/**+ * Is `version` a plain release version?+ * @param {unknown} version+ * @returns {version is string}+ */+export function isReleaseVersion(version) {+ return typeof version === 'string' && VERSION_RE.test(version);+}++/**+ * A cached, verified release.+ * @typedef {object} CachedRelease+ * @property {string} version+ * @property {string} dir the release folder+ * @property {string} cliDir its `@astryxdesign/cli`+ * @property {string} coreDir its `@astryxdesign/core`+ * @property {string} bin the CLI's `astryx` entry file+ */++/**+ * The entry file a CLI package's `astryx` bin points at.+ * @param {string} cliDir+ * @returns {string | null}+ */+export function cliBinOf(cliDir) {+ const pkg = readJson(path.join(cliDir, 'package.json'));+ const bin =+ typeof pkg?.bin === 'string' ? pkg.bin : pkg?.bin && pkg.bin.astryx;+ if (typeof bin !== 'string') return null;+ const file = path.join(cliDir, bin);+ return fs.existsSync(file) ? file : null;+}++/**+ * The files whose bytes a cached release's marker records, relative to the+ * release folder: enough to notice a damaged or half-written release without+ * reading every file on each run.+ * @param {string} bin the CLI's entry file+ * @param {string} dir the release folder+ * @returns {string[]}+ */+function checkedFiles(bin, dir) {+ return [+ path.join('node_modules', '@astryxdesign', 'cli', 'package.json'),+ path.join('node_modules', '@astryxdesign', 'core', 'package.json'),+ path.relative(dir, bin),+ ];+}++/**+ * The sha256 of a file, or null when it cannot be read.+ * @param {string} file+ * @returns {string | null}+ */+function fileHash(file) {+ try {+ return createHash('sha256').update(fs.readFileSync(file)).digest('hex');+ } catch {+ return null;+ }+}++/**+ * The cached release `version`, when it is installed and verified: its+ * marker parses, names the version, and records the bytes of the CLI's and+ * Core's package.json and the CLI's entry file, and those files still have+ * them, and the number and total size of the two packages' files are the+ * ones recorded. Anything else is a damaged release, which counts as absent and is+ * replaced the next time a run needs it.+ * @param {string} version+ * @param {string} [cacheDir]+ * @returns {CachedRelease | null}+ */+export function cachedRelease(version, cacheDir = userCacheDir()) {+ if (!isReleaseVersion(version)) return null;+ const key = `${cacheDir}\0${version}`;+ if (verified.has(key)) return verified.get(key) ?? null;+ const result = verifyRelease(version, cacheDir);+ // Only a verified release is remembered; an absent one is looked at again,+ // since another run may be installing it.+ if (result) verified.set(key, result);+ return result;+}++/**+ * Releases this process already verified, so a run checks each one once.+ * @type {Map<string, CachedRelease>}+ */+const verified = new Map();++/** Forget which releases this process verified, so the next look checks again. */+export function forgetVerifiedReleases() {+ verified.clear();+}++/**+ * The number of files and their total size under a package folder.+ * @param {string} dir+ * @returns {{count: number, bytes: number}}+ */+function treeSize(dir) {+ let count = 0;+ let bytes = 0;+ /** @param {string} d */+ const walk = d => {+ for (const entry of fs.readdirSync(d, {withFileTypes: true})) {+ const p = path.join(d, entry.name);+ if (entry.isDirectory()) walk(p);+ else {+ count += 1;+ bytes += fs.statSync(p).size;+ }+ }+ };+ walk(dir);+ return {count, bytes};+}++/**+ * The size record of a release's two packages.+ * @param {string} dir the release folder+ * @returns {{cli: {count: number, bytes: number}, core: {count: number, bytes: number}} | null}+ */+export function releaseTree(dir) {+ try {+ return {+ cli: treeSize(path.join(dir, 'node_modules', '@astryxdesign', 'cli')),+ core: treeSize(path.join(dir, 'node_modules', '@astryxdesign', 'core')),+ };+ } catch {+ return null;+ }+}++/**+ * The check behind {@link cachedRelease}.+ * @param {string} version+ * @param {string} cacheDir+ * @returns {CachedRelease | null}+ */+function verifyRelease(version, cacheDir) {+ const dir = path.join(releasesDir(cacheDir), version);+ const marker = readJson(path.join(dir, 'release.json'));+ if (!marker || marker.version !== version || !marker.files) return null;+ const cliDir = path.join(dir, 'node_modules', '@astryxdesign', 'cli');+ const coreDir = path.join(dir, 'node_modules', '@astryxdesign', 'core');+ const bin = cliBinOf(cliDir);+ if (!bin) return null;+ for (const rel of checkedFiles(bin, dir)) {+ const want = marker.files[rel.split(path.sep).join('/')];+ if (typeof want !== 'string' || fileHash(path.join(dir, rel)) !== want) {+ return null;+ }+ }+ // Every other file of the two packages: a deleted or truncated module+ // changes the count or the total size.+ if (+ JSON.stringify(releaseTree(dir)) !== JSON.stringify(marker.tree ?? null)+ ) {+ return null;+ }+ return {version, dir, cliDir, coreDir, bin};+}++/**+ * Is `dir` inside the release cache? A copy that lives there was started by+ * global mode, never installed by a person.+ * @param {string} dir+ * @param {string} [cacheDir]+ * @returns {boolean}+ */+export function isInReleaseCache(dir, cacheDir = userCacheDir()) {+ return (+ relativeWithin(realOrSelf(releasesDir(cacheDir)), realOrSelf(dir)) !== null+ );+}++/**+ * @param {string} p+ * @returns {string}+ */+function realOrSelf(p) {+ try {+ return fs.realpathSync(p);+ } catch {+ return path.resolve(p);+ }+}++/**+ * How to start npm, never through a shell, so nothing a project declares is+ * read by one: npm's own entry file run with this Node, from beside the+ * running Node, else from beside an `npm` on the PATH (on Windows, npm's+ * `npm.cmd` shim sits next to its `node_modules`); else `npm` on the PATH,+ * started directly. An `npm` beside the running Node or on the PATH that+ * links to npm's entry file (as distribution packages install it, such as+ * `/usr/bin/npm` to `/usr/lib/node_modules_22/npm/bin/npm-cli.js`) counts as+ * that entry file.+ * @param {{env?: NodeJS.ProcessEnv, platform?: NodeJS.Platform, execPath?: string}} [where]+ * `execPath`: the Node that runs npm (default: this one)+ * @returns {{command: string, prefix: string[], shell: false}}+ */+export function npmCommand(where = {}) {+ const {+ env = process.env,+ platform = process.platform,+ execPath = process.execPath,+ } = where;+ const paths = platform === 'win32' ? path.win32 : path.posix;+ const nodeDir = paths.dirname(execPath);+ const entry = (/** @type {string} */ dir) =>+ paths.join(dir, 'node_modules', 'npm', 'bin', 'npm-cli.js');+ const candidates = [+ ...(platform === 'win32'+ ? [entry(nodeDir)]+ : [+ paths.join(+ nodeDir,+ '..',+ 'lib',+ 'node_modules',+ 'npm',+ 'bin',+ 'npm-cli.js',+ ),+ entry(nodeDir),+ ]),+ ...String(env.PATH ?? env.Path ?? '')+ .split(platform === 'win32' ? ';' : ':')+ .filter(Boolean)+ .filter(dir =>+ fs.existsSync(+ paths.join(dir, platform === 'win32' ? 'npm.cmd' : 'npm'),+ ),+ )+ .flatMap(dir =>+ platform === 'win32'+ ? [entry(dir)]+ : [+ paths.join(+ dir,+ '..',+ 'lib',+ 'node_modules',+ 'npm',+ 'bin',+ 'npm-cli.js',+ ),+ ],+ ),+ ];+ if (platform !== 'win32') {+ // An `npm` that links to npm's entry file: beside the running Node first.+ for (const dir of [+ nodeDir,+ ...String(env.PATH ?? '')+ .split(':')+ .filter(Boolean),+ ]) {+ try {+ const real = fs.realpathSync(paths.join(dir, 'npm'));+ if (paths.basename(real) === 'npm-cli.js') candidates.push(real);+ } catch {+ // No npm there.+ }+ }+ }+ for (const file of candidates) {+ if (fs.existsSync(file)) {+ return {command: execPath, prefix: [file], shell: false};+ }+ }+ return {command: 'npm', prefix: [], shell: false};+}++/**+ * Whether `spec` reads as an npm version range and nothing else: versions,+ * `x`/`*` wildcards, prerelease tags, the range operators, `||`, and spaces.+ * Anything a shell or npm would read as more, such as `&`, `;`, a lone `|`,+ * quotes, or a URL, is refused.+ * @param {string} spec+ * @returns {boolean}+ */+export function isVersionRange(spec) {+ if (typeof spec !== 'string' || spec.trim() === '' || spec.length > 256) {+ return false;+ }+ if (/[^0-9A-Za-z.\-+^~<>=|*\s]/u.test(spec)) return false;+ return !/(?:^|[^|])\|(?:[^|]|$)/u.test(spec);+}++/**+ * The result of running npm.+ * @typedef {object} NpmResult+ * @property {number | null} status+ * @property {NodeJS.Signals | null} [signal] the signal that ended npm, such as Ctrl-C's+ * @property {string} stdout+ * @property {string} stderr+ * @property {Error} [error]+ */++/**+ * Run npm synchronously with no output on the caller's streams.+ * @param {string[]} args+ * npm runs under npm-guard.mjs, which gives it a process group of its own+ * and ends that group when the time limit passes, when this run goes away+ * (even killed outright), or when this run receives Ctrl-C. So no install+ * outlives the run that started it.+ *+ * @param {string[]} args+ * @param {{cwd?: string, timeoutMs?: number, pidFile?: string, npm?: {command: string, prefix: string[], shell?: false}}} [options]+ * `pidFile` receives npm's process id while it runs (the release lock's+ * record); `npm` replaces how npm is started (tests).+ * @returns {NpmResult}+ */+export function runNpm(args, options = {}) {+ const {command, prefix} = options.npm ?? npmCommand();+ const timeoutMs = options.timeoutMs ?? 300_000;+ const direct = process.platform === 'win32';+ const result = direct+ ? spawnSync(command, [...prefix, ...args], {+ cwd: options.cwd ?? os.tmpdir(),+ encoding: 'utf-8',+ // Never a shell: a declared range must not reach one.+ shell: false,+ stdio: ['ignore', 'pipe', 'pipe'],+ timeout: timeoutMs,+ // npm defers SIGTERM until its work finishes, so a time limit has to+ // end it outright or the limit never takes effect.+ killSignal: 'SIGKILL',+ windowsHide: true,+ })+ : spawnSync(+ process.execPath,+ [+ GUARD,+ String(timeoutMs),+ options.pidFile ?? '',+ command,+ ...prefix,+ ...args,+ ],+ {+ cwd: options.cwd ?? os.tmpdir(),+ encoding: 'utf-8',+ stdio: ['ignore', 'pipe', 'pipe'],+ // A backstop only: the guard ends npm at the limit itself.+ timeout: timeoutMs + 30_000,+ killSignal: 'SIGKILL',+ windowsHide: true,+ },+ );+ const timedOut = !direct && result.status === 124;+ return {+ status: timedOut ? null : result.status,+ signal: result.signal ?? null,+ stdout: result.stdout ?? '',+ stderr: result.stderr ?? '',+ ...(timedOut+ ? {error: Object.assign(new Error('npm timed out'), {code: 'ETIMEDOUT'})}+ : result.error+ ? {error: result.error}+ : {}),+ };+}++/** The guard npm runs under. */+const GUARD = fileURLToPath(new URL('./npm-guard.mjs', import.meta.url));++/**+ * The newest published version that `spec` (a dist-tag or a range) names,+ * asked of the registry through npm.+ * @param {string} name e.g. `@astryxdesign/core`+ * @param {string} spec e.g. `latest`, `^0.6.8`+ * @param {{run?: typeof runNpm}} [options]+ * @returns {string | null}+ */+export function resolvePublishedVersion(name, spec, options = {}) {+ if (!isVersionRange(spec) || !/^@astryxdesign\/[a-z-]+$/u.test(name)) {+ return null;+ }+ const run = options.run ?? runNpm;+ const result = run(+ ['view', `${name}@${spec}`, 'version', '--json', ...BOUNDED_FETCH],+ {timeoutMs: 60_000},+ );+ if (result.status !== 0) return null;+ let parsed;+ try {+ parsed = JSON.parse(result.stdout || 'null');+ } catch {+ return null;+ }+ const versions = (Array.isArray(parsed) ? parsed : [parsed]).filter(+ isReleaseVersion,+ );+ return versions.length > 0 ? versions[versions.length - 1] : null;+}++/**+ * The release the registry tags `latest` for the CLI, and the Node range it+ * declares; null when the registry cannot be asked, with the reason given to+ * `onFailure`: `npm-missing` (npm cannot be started), `npm-failed: <npm's+ * error code>` (npm ran and failed, such as on ECONNREFUSED or E404), or+ * `bad-reply` (npm's answer names no release).+ * @param {{run?: typeof runNpm, onFailure?: (reason: string) => void}} [options]+ * @returns {{version: string, node: string | null} | null}+ */+export function resolveLatestRelease(options = {}) {+ const run = options.run ?? runNpm;+ const fail = (/** @type {string} */ reason) => {+ options.onFailure?.(reason);+ return null;+ };+ const result = run(+ [+ 'view',+ '@astryxdesign/cli@latest',+ 'version',+ 'engines',+ '--json',+ ...BOUNDED_FETCH,+ ],+ {timeoutMs: 60_000},+ );+ if (result.status !== 0) {+ if (/** @type {any} */ (result.error)?.code === 'ENOENT') {+ return fail('npm-missing');+ }+ const code =+ /npm (?:error|ERR!) code (\S+)/u.exec(result.stderr)?.[1] ??+ /** @type {any} */ (result.error)?.code ??+ (result.signal ? result.signal : `exit ${result.status}`);+ return fail(`npm-failed: ${code}`);+ }+ let parsed;+ try {+ parsed = JSON.parse(result.stdout || 'null');+ } catch {+ return fail('bad-reply');+ }+ const info = Array.isArray(parsed) ? parsed[parsed.length - 1] : parsed;+ if (typeof info === 'string') {+ return isReleaseVersion(info)+ ? {version: info, node: null}+ : fail('bad-reply');+ }+ if (!info || !isReleaseVersion(info.version)) return fail('bad-reply');+ const node = info.engines?.node;+ return {version: info.version, node: typeof node === 'string' ? node : null};+}++/**+ * Registry requests give up after one retry and 30 seconds each, so a run with+ * no network fails in seconds with ERR_VERSIONS_UNAVAILABLE instead of waiting+ * out npm's default retries. Registry, proxy, and offline settings still come+ * from the user's npm configuration.+ */+const BOUNDED_FETCH = [+ '--fetch-retries=1',+ '--fetch-timeout=30000',+ // One quick retry, so an offline run learns it is offline in seconds.+ '--fetch-retry-mintimeout=2000',+ '--fetch-retry-maxtimeout=10000',+];++/**+ * How long a failed install of a release is remembered, so offline runs do+ * not start npm again on every run (spec AST-081 FR2): 2 minutes after a+ * first failure, so a passing registry hiccup is retried soon, and 10 minutes+ * after a second failure in a row. A successful install forgets it.+ * @param {number} failures the failures in a row, 1 or more+ * @returns {number}+ */+export function failedInstallWaitMs(failures) {+ return (failures >= 2 ? 10 : 2) * 60_000;+}++/**+ * The record of a failed install of `version`: a file in the release cache,+ * shared by every copy of the CLI that uses this cache.+ * @param {string} version+ * @param {string} cacheDir+ * @returns {string}+ */+function failedRecordPath(version, cacheDir) {+ return path.join(releasesDir(cacheDir), `.failed-${version}.json`);+}++/**+ * The recorded failed installs of `version` in a row, when the last was+ * within its wait (failedInstallWaitMs), or null.+ * @param {string} version+ * @param {string} cacheDir+ * @param {number} [now]+ * @returns {{at: number, reason: string, failures: number, waitMs: number} | null}+ */+export function recentFailedInstall(version, cacheDir, now = Date.now()) {+ const record = readFailedInstall(version, cacheDir);+ if (!record) return null;+ const waitMs = failedInstallWaitMs(record.failures);+ const age = now - record.at;+ return age >= 0 && age < waitMs ? {...record, waitMs} : null;+}++/**+ * The record of failed installs of `version`, whatever its age, or null.+ * @param {string} version+ * @param {string} cacheDir+ * @returns {{at: number, reason: string, failures: number} | null}+ */+function readFailedInstall(version, cacheDir) {+ const record = readJson(failedRecordPath(version, cacheDir));+ if (+ !record ||+ typeof record.at !== 'number' ||+ typeof record.reason !== 'string'+ ) {+ return null;+ }+ const failures =+ Number.isInteger(record.failures) && record.failures > 0+ ? record.failures+ : 1;+ return {at: record.at, reason: record.reason, failures};+}++/**+ * Remember, or forget, a failed install of `version`. Never fails a run.+ * @param {string} version+ * @param {string} cacheDir+ * @param {string | null} reason null forgets it+ */+function recordFailedInstall(version, cacheDir, reason) {+ const file = failedRecordPath(version, cacheDir);+ try {+ if (reason === null) {+ fs.rmSync(file, {force: true});+ return;+ }+ fs.mkdirSync(path.dirname(file), {recursive: true});+ const failures = (readFailedInstall(version, cacheDir)?.failures ?? 0) + 1;+ const tmp = `${file}.${process.pid}.tmp`;+ fs.writeFileSync(+ tmp,+ `${JSON.stringify({at: Date.now(), reason, failures})}\n`,+ );+ fs.renameSync(tmp, file);+ } catch {+ // An unwritable cache already answers for itself.+ }+}++/**+ * The longest an install may take: generous, so a slow but moving download+ * finishes, while a stalled one still ends in ERR_VERSIONS_UNAVAILABLE.+ */+export const INSTALL_TIMEOUT_MS = 15 * 60_000;++/**+ * The exit statuses a package manager uses when Ctrl-C, a closed terminal, or+ * a termination request stopped it.+ * @type {Record<number, NodeJS.Signals>}+ */+const EXIT_SIGNALS = {129: 'SIGHUP', 130: 'SIGINT', 143: 'SIGTERM'};++/** Sleep the thread without spinning. @param {number} ms */+function sleep(ms) {+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);+}++/** How long a lock may stand before a run treats its holder as gone. */+const STALE_LOCK_MS = 30 * 60_000;++/**+ * How long a lock held from another computer (a shared cache) may stand,+ * however often its holder renews it; one whose holder stops renewing it is+ * taken over sooner (lock-lease.mjs).+ */+const FOREIGN_LOCK_MS = 20 * 60_000;++/** How long a lock with no owner record may stand: its holder died taking it. */+const UNOWNED_LOCK_MS = 10_000;++/**+ * Is process `pid` on this computer still running?+ * @param {number} pid+ * @returns {boolean}+ */+function isAlive(pid) {+ try {+ process.kill(pid, 0);+ return true;+ } catch (error) {+ // EPERM: it runs, as another user.+ return /** @type {NodeJS.ErrnoException} */ (error).code === 'EPERM';+ }+}++/**+ * Has the run holding `lockDir` gone? Its owner record names a process on+ * this computer that no longer runs; or there is no record and the lock is+ * older than a run needs to write one; or another computer holds it for+ * longer than an install takes, or its holder there stopped renewing it; or+ * it is older than any install.+ * @param {string} lockDir+ * @param {number} now+ * @returns {boolean}+ */+function lockIsStale(lockDir, now) {+ let age;+ try {+ age = now - fs.statSync(lockDir).mtimeMs;+ } catch {+ return false;+ }+ if (age > STALE_LOCK_MS) return true;+ const owner = readJson(path.join(lockDir, 'owner.json'));+ if (!owner) return age > UNOWNED_LOCK_MS;+ if (owner.host !== os.hostname() || !Number.isInteger(owner.pid)) {+ return age > FOREIGN_LOCK_MS || foreignLockIsSilent(lockDir, now);+ }+ // A live holder on this computer is installing, however slowly.+ return !isAlive(owner.pid);+}++/**+ * Take a lock folder, or return false when another live run holds it. A lock+ * whose holder has gone, such as a run stopped with Ctrl-C or killed, is taken+ * over at once, and one from another computer once its holder has stopped+ * renewing it. Throws when the cache folder cannot be written.+ * @param {string} lockDir+ * @param {{now?: number}} [options] the clock, for tests+ * @returns {boolean}+ */+export function tryLock(lockDir, {now = Date.now()} = {}) {+ fs.mkdirSync(path.dirname(lockDir), {recursive: true});+ try {+ fs.mkdirSync(lockDir);+ } catch (error) {+ if (/** @type {NodeJS.ErrnoException} */ (error).code !== 'EEXIST') {+ throw error;+ }+ if (!lockIsStale(lockDir, now)) return false;+ // The run that held it is gone; end the install it left running, if any,+ // before starting another.+ endRecordedInstall(lockDir, {now});+ const aside = `${lockDir}.stale-${process.pid}-${Math.random().toString(36).slice(2, 8)}`;+ try {+ fs.renameSync(lockDir, aside);+ } catch {+ // Another run took it over first.+ return false;+ }+ fs.rmSync(aside, {recursive: true, force: true});+ try {+ fs.mkdirSync(lockDir);+ } catch {+ return false;+ }+ }+ try {+ fs.writeFileSync(+ path.join(lockDir, 'owner.json'),+ JSON.stringify({pid: process.pid, host: os.hostname(), at: Date.now()}),+ );+ } catch {+ // Without a record the lock still expires on its own.+ }+ return true;+}++/**+ * What the system says about the process `pid`: its arguments (exact from+ * `/proc`; split on spaces from `ps` or PowerShell, so a path with a space in+ * it never matches), and when it started (ms since the epoch). Read from `/proc` where there is one, else from `ps` (or+ * PowerShell on Windows); null for what cannot be read.+ * @param {number} pid+ * @param {string} procRoot+ * @returns {{argv: string[] | null, startedAt: number | null}}+ */+function processFactsOf(pid, procRoot) {+ try {+ let argv = fs+ .readFileSync(path.join(procRoot, String(pid), 'cmdline'), 'utf-8')+ .split('\u0000')+ .filter(Boolean);+ // npm sets its process title to its command line, which Linux shows as+ // one argument ("npm install @astryxdesign/[email protected] …"): split it as the+ // ps path does.+ if (argv.length === 1) argv = argv[0].trim().split(/\s+/u);+ /** @type {number | null} */+ let startedAt = null;+ try {+ // Field 22 of /proc/<pid>/stat: start time in clock ticks after boot+ // (100 a second on Linux); /proc/stat's btime: boot, in seconds.+ const stat = fs.readFileSync(+ path.join(procRoot, String(pid), 'stat'),+ 'utf-8',+ );+ const ticks = Number(+ stat.slice(stat.lastIndexOf(')') + 2).split(' ')[19],+ );+ const btime = Number(+ /^btime (\d+)$/mu.exec(+ fs.readFileSync(path.join(procRoot, 'stat'), 'utf-8'),+ )?.[1],+ );+ if (Number.isFinite(ticks) && Number.isFinite(btime)) {+ startedAt = btime * 1000 + ticks * 10;+ }+ } catch {+ // Start time unknown.+ }+ return {argv, startedAt};+ } catch {+ // No process table here.+ }+ if (process.platform === 'win32') {+ const result = spawnSync(+ 'powershell.exe',+ [+ '-NoProfile',+ '-NonInteractive',+ '-Command',+ `$p = Get-CimInstance Win32_Process -Filter 'ProcessId=${pid}'; if ($p) { [DateTimeOffset]::new($p.CreationDate).ToUnixTimeMilliseconds(); $p.CommandLine }`,+ ],+ {encoding: 'utf-8', windowsHide: true, timeout: 10_000},+ );+ const [started, ...rest] = (result.stdout ?? '').trim().split(/\r?\n/u);+ const line = rest.join(' ').trim();+ return {+ argv: line+ ? line.split(/\s+/u).map(arg => arg.replace(/^"(.*)"$/u, '$1'))+ : null,+ startedAt: Number(started) || null,+ };+ }+ const result = spawnSync(+ 'ps',+ ['-o', 'lstart=', '-o', 'args=', '-p', String(pid)],+ {+ encoding: 'utf-8',+ timeout: 5000,+ },+ );+ const line = (result.stdout ?? '').split(/\r?\n/u)[0] ?? '';+ // `lstart` is a fixed 24-character date, such as `Tue Oct 20 03:52:54 2026`.+ const startedAt = Date.parse(line.slice(0, 24));+ const args = line.slice(24).trim();+ return {+ argv: args ? args.split(/\s+/u) : null,+ startedAt: Number.isFinite(startedAt) ? startedAt : null,+ };+}++/**+ * Whether a process's arguments are this CLI's install of `version`, as+ * runNpm starts it: the program (`argv[0]`) is npm, or node running npm's+ * entry file `npm-cli.js` (`argv[1]`), each exactly by name, and the arguments+ * include `install` and `@astryxdesign/cli@<version>`. A program that only has+ * `npm` somewhere in its name or arguments is not.+ * @param {string[]} argv+ * @param {string} version+ * @returns {boolean}+ */+export function isReleaseInstall(argv, version) {+ const name = (/** @type {string | undefined} */ arg) =>+ (arg ?? '')+ .split(/[\\/]/u)+ .pop()+ ?.replace(/\.(?:exe|cmd)$/iu, '')+ .toLowerCase() ?? '';+ const program = name(argv[0]);+ const npm =+ program === 'npm' ||+ (/^node(?:[-.\d]*)$/u.test(program) && name(argv[1]) === 'npm-cli.js');+ return (+ npm &&+ argv.includes('install') &&+ argv.includes(`@astryxdesign/cli@${version}`)+ );+}++/**+ * End the npm process group a stale lock records, only when that process is+ * surely the install the lock was taken for: its command line is this CLI's+ * install of the lock's release (isReleaseInstall), the lock is younger than+ * any install may take, and the process started no earlier than the lock.+ * Anything less certain is left alone, and the lock is simply taken over,+ * since a recorded process id can name an unrelated process once the install+ * ended.+ * @param {string} lockDir a `.lock-<version>` folder+ * @param {{now?: number, procRoot?: string, factsOf?: (pid: number) => {argv: string[] | null, startedAt: number | null}}} [options]+ * the clock, the process table's folder, and the fact reader, for tests+ * @returns {'ended' | 'left'} whether a process group was ended+ */+export function endRecordedInstall(+ lockDir,+ {now = Date.now(), procRoot = '/proc', factsOf} = {},+) {+ let pid;+ try {+ pid = Number(fs.readFileSync(path.join(lockDir, 'npm.pid'), 'utf-8'));+ } catch {+ return 'left';+ }+ if (!Number.isInteger(pid) || pid <= 1 || !isAlive(pid)) return 'left';+ const version = /^\.lock-(.+)$/u.exec(path.basename(lockDir))?.[1];+ if (!version) return 'left';+ const owner = readJson(path.join(lockDir, 'owner.json'));+ const at = typeof owner?.at === 'number' ? owner.at : null;+ if (at === null || !(now - at >= 0 && now - at < INSTALL_TIMEOUT_MS)) {+ return 'left';+ }+ const facts = (factsOf ?? (id => processFactsOf(id, procRoot)))(pid);+ if (!facts.argv || !isReleaseInstall(facts.argv, version)) return 'left';+ // Started before the lock was taken: an older process that reuses the id.+ // A second's slack covers clocks that round.+ if (facts.startedAt === null || facts.startedAt < at - 1000) return 'left';+ try {+ process.kill(process.platform === 'win32' ? pid : -pid, 'SIGKILL');+ return 'ended';+ } catch {+ // Already gone.+ return 'left';+ }+}++/**+ * Remove a folder by renaming it aside first, so a run never sees it half+ * removed.+ * @param {string} dir+ */+function removeAside(dir) {+ const aside = `${dir}.removing-${process.pid}-${Math.random().toString(36).slice(2, 8)}`;+ try {+ fs.renameSync(dir, aside);+ } catch {+ return;+ }+ fs.rmSync(aside, {recursive: true, force: true});+}++/**+ * Why a release could not be made available.+ * @typedef {object} ReleaseUnavailable+ * @property {string} version+ * @property {string} reason one plain sentence+ * @property {NodeJS.Signals} [signal] the install was stopped by this signal+ */++/**+ * Install release `version` into the cache, verify it, and return it. A+ * release already cached returns at once. When another run is installing the+ * same release, this waits for it.+ *+ * @param {string} version+ * @param {{cacheDir?: string, run?: typeof runNpm, nodeVersion?: string, waitMs?: number, onProgress?: (event: 'install' | 'wait', version: string) => void}} [options]+ * `onProgress` hears once when an install starts and once when the run+ * starts waiting for another run's install.+ * @returns {CachedRelease | ReleaseUnavailable}+ */+export function ensureRelease(version, options = {}) {+ const {+ cacheDir = userCacheDir(),+ run = runNpm,+ nodeVersion = process.versions.node,+ waitMs = INSTALL_TIMEOUT_MS + 60_000,+ onProgress = () => {},+ } = options;+ if (!isReleaseVersion(version)) {+ return {version: String(version), reason: 'it is not a release version'};+ }+ const existing = cachedRelease(version, cacheDir);+ if (existing) {+ // Installed by now, by any copy: forget any failure.+ if (readFailedInstall(version, cacheDir)) {+ recordFailedInstall(version, cacheDir, null);+ }+ return existing;+ }+ // A recent failed install is not retried: offline, every run would start+ // npm again and wait for it (FR2).+ const failed = recentFailedInstall(version, cacheDir);+ if (failed) {+ const minutes = Math.max(1, Math.round((Date.now() - failed.at) / 60_000));+ return {+ version,+ reason: `${failed.reason}; last tried ${minutes} minute${minutes === 1 ? '' : 's'} ago, tried again after ${failed.waitMs / 60_000} minutes`,+ };+ }+ try {+ const result = ensureLocked(version, {+ cacheDir,+ run,+ nodeVersion,+ waitMs,+ onProgress,+ });+ // Stopped with Ctrl-C (or closed): the lock and scratch folder are already+ // cleared; end the run the way the signal would have.+ if ('signal' in result && result.signal)+ process.kill(process.pid, result.signal);+ if ('bin' in result) recordFailedInstall(version, cacheDir, null);+ else if (+ 'reason' in result &&+ !('signal' in result && result.signal) &&+ result.reason !== 'another run is still installing it'+ ) {+ recordFailedInstall(version, cacheDir, result.reason);+ }+ return result;+ } catch (error) {+ const code = /** @type {NodeJS.ErrnoException} */ (error).code;+ return {+ version,+ reason: `the release cache ${releasesDir(cacheDir)} cannot be written${code ? ` (${code})` : ''}`,+ };+ }+}++/**+ * `ensureRelease` under the per-release lock.+ * @param {string} version+ * @param {{cacheDir: string, run: typeof runNpm, nodeVersion: string, waitMs: number, onProgress: (event: 'install' | 'wait', version: string) => void}} options+ * @returns {CachedRelease | ReleaseUnavailable}+ */+function ensureLocked(+ version,+ {cacheDir, run, nodeVersion, waitMs, onProgress},+) {+ const root = releasesDir(cacheDir);+ const lockDir = path.join(root, `.lock-${version}`);+ const deadline = Date.now() + waitMs;+ let waiting = false;+ while (!tryLock(lockDir)) {+ const ready = cachedRelease(version, cacheDir);+ if (ready) return ready;+ if (Date.now() > deadline) {+ return {version, reason: 'another run is still installing it'};+ }+ if (!waiting) {+ waiting = true;+ onProgress('wait', version);+ }+ sleep(200);+ }+ // A run stopped mid-install (Ctrl-C, a closed terminal) frees the lock and+ // its scratch folder on the way out; a killed one is taken over by the+ // owner check in tryLock.+ const release = () => {+ for (const entry of safeList(root)) {+ if (entry.startsWith(`.tmp-${version}-${process.pid}-`)) {+ fs.rmSync(path.join(root, entry), {recursive: true, force: true});+ }+ }+ fs.rmSync(lockDir, {recursive: true, force: true});+ };+ /** @param {NodeJS.Signals} signal */+ const onSignal = signal => {+ release();+ removeSignalHandlers();+ process.kill(process.pid, signal);+ };+ const signals = /** @type {NodeJS.Signals[]} */ ([+ 'SIGINT',+ 'SIGTERM',+ 'SIGHUP',+ ]);+ const removeSignalHandlers = () => {+ for (const signal of signals) process.off(signal, onSignal);+ };+ for (const signal of signals) process.on(signal, onSignal);+ try {+ const again = cachedRelease(version, cacheDir);+ if (again) return again;+ // Under the lock, anything left for this version is a damaged release or+ // the scratch folder of a run that stopped: clear both.+ for (const entry of safeList(root)) {+ if (+ entry.startsWith(`.tmp-${version}-`) ||+ entry.startsWith(`${version}.removing-`) ||+ entry.startsWith(`.lock-${version}.stale-`)+ ) {+ fs.rmSync(path.join(root, entry), {recursive: true, force: true});+ }+ }+ removeAside(path.join(root, version));+ verified.delete(`${cacheDir}\0${version}`);+ onProgress('install', version);+ return installLocked(version, {cacheDir, run, nodeVersion});+ } finally {+ removeSignalHandlers();+ release();+ }+}++/**+ * A folder's entries, or none.+ * @param {string} dir+ * @returns {string[]}+ */+function safeList(dir) {+ try {+ return fs.readdirSync(dir);+ } catch {+ return [];+ }+}++/**+ * The install itself, under the lock.+ * @param {string} version+ * @param {{cacheDir: string, run: typeof runNpm, nodeVersion: string}} options+ * @returns {CachedRelease | ReleaseUnavailable}+ */+function installLocked(version, {cacheDir, run, nodeVersion}) {+ const root = releasesDir(cacheDir);+ const tmp = path.join(+ root,+ `.tmp-${version}-${process.pid}-${Math.random().toString(36).slice(2, 8)}`,+ );+ fs.mkdirSync(tmp, {recursive: true});+ try {+ fs.writeFileSync(+ path.join(tmp, 'package.json'),+ `${JSON.stringify({name: 'astryx-release', private: true}, null, 2)}\n`,+ );+ const install = run(+ [+ 'install',+ '--no-save',+ '--no-package-lock',+ '--ignore-scripts',+ '--no-audit',+ '--no-fund',+ '--prefer-offline',+ ...BOUNDED_FETCH,+ '--loglevel=error',+ `@astryxdesign/cli@${version}`,+ `@astryxdesign/core@${version}`,+ ],+ {+ cwd: tmp,+ timeoutMs: INSTALL_TIMEOUT_MS,+ pidFile: path.join(root, `.lock-${version}`, 'npm.pid'),+ },+ );+ // Our own time limit ends npm: that is a timeout, not a stopped run.+ if (/** @type {any} */ (install.error)?.code === 'ETIMEDOUT') {+ return {+ version,+ reason: `the install did not finish within ${INSTALL_TIMEOUT_MS / 60_000} minutes`,+ };+ }+ const stoppedBy = install.signal ?? EXIT_SIGNALS[install.status ?? -1];+ if (stoppedBy) {+ return {version, reason: 'the install was stopped', signal: stoppedBy};+ }+ if (install.status !== 0) {+ return {version, reason: npmFailure(install)};+ }+ const cliDir = path.join(tmp, 'node_modules', '@astryxdesign', 'cli');+ const cliPkg = readJson(path.join(cliDir, 'package.json'));+ if (cliPkg?.version !== version) {+ return {version, reason: 'the package manager installed another version'};+ }+ const engine = cliPkg?.engines?.node;+ if (typeof engine === 'string' && !satisfiesRange(nodeVersion, engine)) {+ return {+ version,+ reason: `it needs Node ${engine}, and this computer runs Node ${nodeVersion}`,+ };+ }+ const bin = cliBinOf(cliDir);+ if (!bin) return {version, reason: 'its CLI has no astryx command'};+ // A check, not a person's run: the shared update-notifier variable keeps+ // a release that prints update notices from printing them here, and from+ // using up the day's notices (spec AST-081 FR10).+ const started = spawnSync(process.execPath, [bin, '--version'], {+ cwd: tmp,+ encoding: 'utf-8',+ env: {...process.env, NO_UPDATE_NOTIFIER: '1'},+ stdio: ['ignore', 'pipe', 'pipe'],+ timeout: 60_000,+ windowsHide: true,+ });+ const reported = String(started.stdout ?? '')+ .trim()+ .split(/\r?\n/)+ .pop();+ if (started.status !== 0 || reported !== version) {+ return {version, reason: 'its CLI did not start and report its version'};+ }+ /** @type {Record<string, string | null>} */+ const files = {};+ for (const rel of checkedFiles(bin, tmp)) {+ files[rel.split(path.sep).join('/')] = fileHash(path.join(tmp, rel));+ }+ fs.writeFileSync(+ path.join(tmp, 'release.json'),+ `${JSON.stringify({version, verifiedAt: new Date().toISOString(), files, tree: releaseTree(tmp)}, null, 2)}\n`,+ );++ const dest = path.join(root, version);+ try {+ fs.renameSync(tmp, dest);+ } catch {+ // A finished release already holds the name; keep that one.+ }+ return (+ cachedRelease(version, cacheDir) ?? {+ version,+ reason: 'it could not be saved in the cache',+ }+ );+ } catch (error) {+ return {+ version,+ reason: `installing it failed (${error instanceof Error ? error.message : String(error)})`,+ };+ } finally {+ fs.rmSync(tmp, {recursive: true, force: true});+ }+}++/**+ * One sentence on why npm failed.+ * @param {NpmResult} result+ * @returns {string}+ */+function npmFailure(result) {+ if (result.error && /** @type {any} */ (result.error).code === 'ENOENT') {+ return 'npm, which installs releases, was not found';+ }+ const text = `${result.stderr}\n${result.stdout}`;+ if (/E404|404 Not Found|No matching version|ETARGET/i.test(text)) {+ return 'the registry does not have it';+ }+ if (+ /ENOTFOUND|ECONNREFUSED|ETIMEDOUT|EAI_AGAIN|ENETUNREACH|offline|network/i.test(+ text,+ )+ ) {+ return 'the registry could not be reached';+ }+ return 'the package manager could not install it';+}diff --git a/packages/cli/foundation/release/cache.test.mjs b/packages/cli/foundation/release/cache.test.mjsnew file mode 100644index 0000000000..491094f105--- /dev/null+++ b/packages/cli/foundation/release/cache.test.mjs@@ -0,0 +1,920 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, it, expect, afterEach} from 'vitest';+import {spawn} from 'node:child_process';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {+ cachedRelease,+ forgetVerifiedReleases,+ ensureRelease,+ isInReleaseCache,+ releasesDir,+ resolvePublishedVersion,+ isVersionRange,+ npmCommand,+ resolveLatestRelease,+ runNpm,+ tryLock,+ endRecordedInstall,+ isReleaseInstall,+ INSTALL_TIMEOUT_MS,+} from './cache.mjs';+import {+ cleanupFixtures,+ installCore,+ installStandInCli,+ seedRelease,+ tempDir,+ writeJson,+} from '../../test-utils/release-fixtures.mjs';+import {LEASE_SILENCE_MS, renewLock} from './lock-lease.mjs';++afterEach(cleanupFixtures);++/**+ * A stand-in for npm: `install` lays down stand-in CLI and Core packages of+ * the requested version (or fails the way `outcome` says), and records each+ * call.+ * @param {{outcome?: 'ok' | 'offline' | 'missing' | 'wrong-version', engines?: string}} [options]+ */+function fakeNpm(options = {}) {+ const {outcome = 'ok', engines} = options;+ /** @type {string[][]} */+ const calls = [];+ /** @type {import('./cache.mjs').runNpm} */+ const run = (args, opts = {}) => {+ calls.push(args);+ if (outcome === 'offline') {+ return {+ status: 1,+ stdout: '',+ stderr: 'npm error code ENOTFOUND\nnpm error network request failed',+ };+ }+ if (outcome === 'missing') {+ return {+ status: 1,+ stdout: '',+ stderr:+ 'npm error code ETARGET\nnpm error notarget No matching version',+ };+ }+ const spec = args.find(a => a.startsWith('@astryxdesign/cli@')) ?? '';+ const version = spec.split('@').pop() ?? '';+ const cwd = /** @type {string} */ (opts.cwd);+ const cli = installStandInCli(+ cwd,+ outcome === 'wrong-version' ? '0.0.1' : version,+ );+ if (engines) {+ const pkg = JSON.parse(+ fs.readFileSync(path.join(cli, 'package.json'), 'utf-8'),+ );+ writeJson(path.join(cli, 'package.json'), {+ ...pkg,+ engines: {node: engines},+ });+ }+ installCore(cwd, version);+ return {status: 0, stdout: '', stderr: ''};+ };+ return {run, calls};+}++describe('ensureRelease', () => {+ it('verifies a release with update notices off, so the check prints and uses up none (FR10)', () => {+ const cacheDir = tempDir('cache');+ const npm = fakeNpm();+ /** @type {typeof npm.run} */+ const run = (args, opts = {}) => {+ const result = npm.run(args, opts);+ // A release whose --version answers only when notices are off.+ const bin = path.join(+ /** @type {string} */ (opts.cwd),+ 'node_modules',+ '@astryxdesign',+ 'cli',+ 'bin.cjs',+ );+ fs.writeFileSync(+ bin,+ `if (process.env.NO_UPDATE_NOTIFIER === undefined) { console.log('notices-on'); process.exit(0); }\nconsole.log('0.6.8');\n`,+ );+ return result;+ };+ const release = ensureRelease('0.6.8', {cacheDir, run});+ expect('bin' in release && release.version).toBe('0.6.8');+ });++ it('installs, verifies, and keeps a release, then reuses it', () => {+ const cacheDir = tempDir('cache');+ const npm = fakeNpm();+ const release = ensureRelease('0.6.8', {cacheDir, run: npm.run});+ expect('bin' in release && release.version).toBe('0.6.8');+ expect(npm.calls[0]).toEqual(+ expect.arrayContaining([+ 'install',+ '--ignore-scripts',+ '--prefer-offline',+ '@astryxdesign/[email protected]',+ '@astryxdesign/[email protected]',+ ]),+ );+ expect(cachedRelease('0.6.8', cacheDir)?.coreDir).toBe(+ path.join(+ releasesDir(cacheDir),+ '0.6.8',+ 'node_modules',+ '@astryxdesign',+ 'core',+ ),+ );+ ensureRelease('0.6.8', {cacheDir, run: npm.run});+ expect(npm.calls).toHaveLength(1);+ expect(+ fs.readdirSync(releasesDir(cacheDir)).filter(n => n.startsWith('.')),+ ).toEqual([]);+ });++ it('says why a release is unavailable and keeps nothing', () => {+ const cases = /** @type {const} */ ([+ ['offline', /could not be reached/],+ ['missing', /does not have it/],+ ['wrong-version', /another version/],+ ]);+ for (const [outcome, reason] of cases) {+ const cacheDir = tempDir('cache');+ const result = ensureRelease('0.6.8', {+ cacheDir,+ run: fakeNpm({outcome}).run,+ });+ expect('reason' in result && result.reason).toMatch(reason);+ expect(cachedRelease('0.6.8', cacheDir)).toBeNull();+ }+ });++ it("refuses a release this computer's Node cannot run", () => {+ const cacheDir = tempDir('cache');+ const result = ensureRelease('0.9.0', {+ cacheDir,+ run: fakeNpm({engines: '>=99.0.0'}).run,+ });+ expect('reason' in result && result.reason).toMatch(+ /needs Node >=99\.0\.0/,+ );+ });++ it('refuses a version that is not a release version', () => {+ const result = ensureRelease('../../etc', {+ cacheDir: tempDir('cache'),+ run: fakeNpm().run,+ });+ expect('reason' in result && result.reason).toMatch(+ /not a release version/,+ );+ });++ it('waits for another run installing the same release', () => {+ const cacheDir = tempDir('cache');+ fs.mkdirSync(path.join(releasesDir(cacheDir), '.lock-0.6.8'), {+ recursive: true,+ });+ const result = ensureRelease('0.6.8', {+ cacheDir,+ run: fakeNpm().run,+ waitMs: 300,+ });+ expect('reason' in result && result.reason).toMatch(/still installing/);+ });+});++describe('cachedRelease', () => {+ it('counts a release only once it is verified', () => {+ const cacheDir = tempDir('cache');+ const dir = seedRelease(cacheDir, '0.7.1');+ expect(cachedRelease('0.7.1', cacheDir)).not.toBeNull();+ fs.rmSync(path.join(dir, 'release.json'));+ forgetVerifiedReleases();+ expect(cachedRelease('0.7.1', cacheDir)).toBeNull();+ });++ it('knows a folder inside the cache', () => {+ const cacheDir = tempDir('cache');+ const dir = seedRelease(cacheDir, '0.7.1');+ expect(isInReleaseCache(dir, cacheDir)).toBe(true);+ expect(isInReleaseCache(tempDir(), cacheDir)).toBe(false);+ });+});++describe.skipIf(process.platform === 'win32')(+ 'a stale lock ends a recorded process group only when it is surely the install',+ () => {+ /** @type {import('node:child_process').ChildProcess[]} */+ const started = [];+ afterEach(() => {+ for (const child of started.splice(0)) {+ try {+ process.kill(-(/** @type {number} */ (child.pid)), 'SIGKILL');+ } catch {+ // Already gone.+ }+ }+ });+ const SLEEP = 'setTimeout(() => {}, 60000)';+ /**+ * A process in a group of its own, started as `program args…`.+ * @param {string} program @param {string[]} args+ */+ const startGroup = (program, args) => {+ const child = spawn(program, args, {detached: true, stdio: 'ignore'});+ started.push(child);+ return /** @type {number} */ (child.pid);+ };+ /** A sleeping script at `dir/name`. @param {string} name */+ const script = name => {+ const file = path.join(tempDir('bin'), name);+ fs.writeFileSync(file, SLEEP);+ return file;+ };+ /** @param {number} pid @param {number} at */+ const lockFor = (pid, at) => {+ const lockDir = path.join(tempDir('lock'), '.lock-9.9.9');+ fs.mkdirSync(lockDir, {recursive: true});+ fs.writeFileSync(path.join(lockDir, 'npm.pid'), String(pid));+ fs.writeFileSync(+ path.join(lockDir, 'owner.json'),+ JSON.stringify({pid: 999999, host: os.hostname(), at}),+ );+ return lockDir;+ };+ const alive = (/** @type {number} */ pid) => {+ try {+ process.kill(pid, 0);+ return true;+ } catch {+ return false;+ }+ };+ const INSTALL = ['install', '--no-save', '@astryxdesign/[email protected]'];+ const until = async (/** @type {() => boolean} */ done) => {+ for (let i = 0; i < 50 && !done(); i++) {+ await new Promise(resolve => setTimeout(resolve, 100));+ }+ return done();+ };++ it('reads the install only from its exact program and arguments', () => {+ const ok = ['/usr/bin/node', '/x/npm/bin/npm-cli.js', ...INSTALL];+ expect(isReleaseInstall(ok, '9.9.9')).toBe(true);+ // npm's own process title, split on whitespace.+ expect(+ isReleaseInstall(+ 'npm install --no-save @astryxdesign/[email protected] @astryxdesign/[email protected]'.split(+ ' ',+ ),+ '9.9.9',+ ),+ ).toBe(true);+ expect(isReleaseInstall(['C:\\npm\\npm.cmd', ...INSTALL], '9.9.9')).toBe(+ true,+ );+ for (const argv of [+ ['/opt/my-npm-tool', ...INSTALL],+ ['python3', '-c', 'sleep', '/home/me/notes/npm-debug.log', ...INSTALL],+ ['/usr/bin/node', '-e', 'x', 'npm', ...INSTALL],+ [+ '/usr/bin/node',+ '/x/npm-cli.js',+ 'install',+ '@astryxdesign/[email protected]',+ ],+ ['/usr/bin/node', '/x/npm-cli.js', 'ci', '@astryxdesign/[email protected]'],+ ]) {+ expect(isReleaseInstall(argv, '9.9.9'), argv.join(' ')).toBe(false);+ }+ });++ it.skipIf(!fs.existsSync('/proc/self/stat'))(+ "reads npm's rewritten process title from /proc, one argument, and ends that install",+ async () => {+ const at = Date.now() - 1000;+ const npm = startGroup(process.execPath, ['-e', SLEEP]);+ await new Promise(resolve => setTimeout(resolve, 300));+ // A process table whose cmdline is npm's title: one NUL-terminated string.+ const procRoot = tempDir('proc');+ fs.mkdirSync(path.join(procRoot, String(npm)));+ fs.writeFileSync(+ path.join(procRoot, String(npm), 'cmdline'),+ 'npm install --no-save @astryxdesign/[email protected] @astryxdesign/[email protected]\u0000',+ );+ // procfs files report size 0, so they are read, not copied.+ for (const [from, to] of [+ [`/proc/${npm}/stat`, path.join(procRoot, String(npm), 'stat')],+ ['/proc/stat', path.join(procRoot, 'stat')],+ ]) {+ fs.writeFileSync(to, fs.readFileSync(from, 'utf8'));+ }+ expect(endRecordedInstall(lockFor(npm, at), {procRoot})).toBe('ended');+ expect(await until(() => !alive(npm))).toBe(true);+ },+ );++ it('leaves a program named my-npm-tool, and one with npm only in an argument', async () => {+ const now = Date.now();+ const tool = path.join(tempDir('bin'), 'my-npm-tool');+ fs.symlinkSync(process.execPath, tool);+ const named = startGroup(tool, [script('sleep.js'), ...INSTALL]);+ const argued = startGroup(process.execPath, [+ '-e',+ SLEEP,+ 'npm',+ '/home/me/notes/npm-debug.log',+ ...INSTALL,+ ]);+ await new Promise(resolve => setTimeout(resolve, 300));+ for (const pid of [named, argued]) {+ expect(endRecordedInstall(lockFor(pid, now - 5000), {now})).toBe(+ 'left',+ );+ expect(alive(pid)).toBe(true);+ }+ });++ it("ends the lock's own install: node running npm-cli.js install of that release, started after the lock", async () => {+ const at = Date.now() - 1000;+ const npm = startGroup(process.execPath, [+ script('npm-cli.js'),+ ...INSTALL,+ ]);+ await new Promise(resolve => setTimeout(resolve, 300));+ // An old lock, or one with no recorded start: not trusted.+ expect(+ endRecordedInstall(lockFor(npm, Date.now() - INSTALL_TIMEOUT_MS - 1)),+ ).toBe('left');+ const unknown = lockFor(npm, at);+ fs.writeFileSync(+ path.join(unknown, 'owner.json'),+ JSON.stringify({pid: 999999, host: os.hostname()}),+ );+ expect(endRecordedInstall(unknown)).toBe('left');+ // A lock taken after the process started: the id names an older process.+ expect(+ endRecordedInstall(lockFor(npm, Date.now() + 60_000), {+ now: Date.now() + 61_000,+ }),+ ).toBe('left');+ expect(alive(npm)).toBe(true);+ expect(endRecordedInstall(lockFor(npm, at))).toBe('ended');+ expect(await until(() => !alive(npm))).toBe(true);+ });++ it('decides from the process facts alone, however they were read (no /proc: ps or PowerShell)', async () => {+ const at = Date.now() - 1000;+ // A real group to end, with facts given as ps would report them, so the+ // outcome never depends on what this computer's ps prints.+ const npm = startGroup(process.execPath, ['-e', SLEEP]);+ await new Promise(resolve => setTimeout(resolve, 300));+ const factsOf =+ (/** @type {string[]} */ argv, startedAt = at + 500) =>+ () => ({argv, startedAt});+ const installArgv = [+ '/usr/bin/node',+ '/x/npm/bin/npm-cli.js',+ ...INSTALL,+ ];+ for (const [argv, startedAt] of /** @type {const} */ ([+ [['/opt/my-npm-tool', ...INSTALL], at + 500],+ [['/usr/bin/node', '-e', 'x', 'npm', ...INSTALL], at + 500],+ [+ [+ 'python3',+ '-c',+ 'sleep',+ '/home/me/notes/npm-debug.log',+ ...INSTALL,+ ],+ at + 500,+ ],+ // Started before the lock: an older process that reuses the id.+ [installArgv, at - 5000],+ ])) {+ expect(+ endRecordedInstall(lockFor(npm, at), {+ factsOf: factsOf([...argv], startedAt),+ }),+ argv.join(' '),+ ).toBe('left');+ }+ // Facts that cannot be read: left alone.+ expect(+ endRecordedInstall(lockFor(npm, at), {+ factsOf: () => ({argv: null, startedAt: null}),+ }),+ ).toBe('left');+ expect(alive(npm)).toBe(true);+ expect(+ endRecordedInstall(lockFor(npm, at), {factsOf: factsOf(installArgv)}),+ ).toBe('ended');+ expect(await until(() => !alive(npm))).toBe(true);+ });+ },+);++describe('a declared range never reaches a shell', () => {+ it('reads only version ranges as ranges', () => {+ for (const ok of [+ '^1.2.3',+ '>=1 <2',+ '1.x || 2.x',+ '*',+ '1.0.0-beta.1',+ 'latest',+ ]) {+ expect(isVersionRange(ok), ok).toBe(true);+ }+ for (const bad of [+ '^1 & echo hi',+ '1 && 2',+ '1|2',+ '1;2',+ '"1"',+ '$(id)',+ '`id`',+ 'https://x',+ '',+ ' ',+ ]) {+ expect(isVersionRange(bad), bad).toBe(false);+ }+ });++ it('asks npm nothing for a range with shell syntax in it', () => {+ /** @type {string[][]} */+ const asked = [];+ const run = (/** @type {string[]} */ args) => {+ asked.push(args);+ return {status: 0, stdout: '"1.0.0"', stderr: ''};+ };+ for (const spec of ['^1 & echo hi', '^1 | tee x', '^1; rm x']) {+ expect(+ resolvePublishedVersion('@astryxdesign/core', spec, {run}),+ ).toBeNull();+ }+ expect(+ resolvePublishedVersion('@astryxdesign/core && x', '^1', {run}),+ ).toBeNull();+ expect(asked).toEqual([]);+ });++ it.skipIf(process.platform === 'win32')(+ 'takes an npm beside the running Node, or on the PATH, that links to its entry file',+ () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-npm-link-'));+ try {+ // A distribution layout: npm's files away from Node's folder, and an+ // npm link into them on the PATH.+ const entry = path.join(+ root,+ 'lib',+ 'node_modules_22',+ 'npm',+ 'bin',+ 'npm-cli.js',+ );+ fs.mkdirSync(path.dirname(entry), {recursive: true});+ fs.writeFileSync(entry, '');+ const bin = path.join(root, 'bin');+ fs.mkdirSync(bin);+ fs.symlinkSync(entry, path.join(bin, 'npm'));+ // A Node with no npm beside it.+ const node = path.join(root, 'node', 'bin', 'node');+ fs.mkdirSync(path.dirname(node), {recursive: true});+ expect(+ npmCommand({env: {PATH: bin}, platform: 'linux', execPath: node}),+ ).toEqual({+ command: node,+ prefix: [fs.realpathSync(entry)],+ shell: false,+ });+ // The same link beside the running Node.+ fs.symlinkSync(entry, path.join(path.dirname(node), 'npm'));+ expect(+ npmCommand({env: {PATH: ''}, platform: 'linux', execPath: node}),+ ).toEqual({+ command: node,+ prefix: [fs.realpathSync(entry)],+ shell: false,+ });+ // Nothing anywhere: npm on the PATH, started directly.+ expect(+ npmCommand({+ env: {PATH: ''},+ platform: 'linux',+ execPath: path.join(root, 'none', 'node'),+ }),+ ).toEqual({command: 'npm', prefix: [], shell: false});+ } finally {+ fs.rmSync(root, {recursive: true, force: true});+ }+ },+ );++ it('names why the newest release could not be asked for', () => {+ /** @type {string[]} */+ const reasons = [];+ const onFailure = (/** @type {string} */ r) => reasons.push(r);+ const missing = Object.assign(new Error('spawn npm ENOENT'), {+ code: 'ENOENT',+ });+ expect(+ resolveLatestRelease({+ run: () => ({status: null, stdout: '', stderr: '', error: missing}),+ onFailure,+ }),+ ).toBeNull();+ expect(+ resolveLatestRelease({+ run: () => ({+ status: 1,+ stdout: '',+ stderr: 'npm error code ECONNREFUSED\nnpm error errno ECONNREFUSED\n',+ }),+ onFailure,+ }),+ ).toBeNull();+ expect(+ resolveLatestRelease({+ run: () => ({status: 0, stdout: '"latest"', stderr: ''}),+ onFailure,+ }),+ ).toBeNull();+ expect(reasons).toEqual([+ 'npm-missing',+ 'npm-failed: ECONNREFUSED',+ 'bad-reply',+ ]);+ });++ it('starts npm from its entry file with this Node, never through a shell', () => {+ const npm = npmCommand();+ expect(npm.shell).toBe(false);+ if (npm.prefix.length > 0) {+ expect(npm.command).toBe(process.execPath);+ expect(npm.prefix[0]).toMatch(/npm-cli\.js$/u);+ }+ });+});++describe('resolvePublishedVersion', () => {+ it('takes the newest version npm reports for a range', () => {+ /** @type {import('./cache.mjs').runNpm} */+ const run = args => {+ expect(args).toEqual([+ 'view',+ '@astryxdesign/core@^0.6.0',+ 'version',+ '--json',+ '--fetch-retries=1',+ '--fetch-timeout=30000',+ '--fetch-retry-mintimeout=2000',+ '--fetch-retry-maxtimeout=10000',+ ]);+ return {status: 0, stdout: '["0.6.3","0.6.8"]', stderr: ''};+ };+ expect(resolvePublishedVersion('@astryxdesign/core', '^0.6.0', {run})).toBe(+ '0.6.8',+ );+ });++ it('is null when npm fails or answers nothing usable', () => {+ expect(+ resolvePublishedVersion('@astryxdesign/cli', 'latest', {+ run: () => ({status: 1, stdout: '', stderr: ''}),+ }),+ ).toBeNull();+ expect(+ resolvePublishedVersion('@astryxdesign/cli', 'latest', {+ run: () => ({status: 0, stdout: '""', stderr: ''}),+ }),+ ).toBeNull();+ });+});++describe('tryLock', () => {+ it('takes a free lock once, keeps a live holder, and reclaims a stale one', () => {+ const dir = path.join(tempDir('lock'), '.lock-x');+ expect(tryLock(dir)).toBe(true);+ expect(tryLock(dir)).toBe(false);+ // A live holder on this computer keeps its lock, however long it takes.+ const slow = new Date(Date.now() - 25 * 60_000);+ fs.utimesSync(dir, slow, slow);+ expect(tryLock(dir)).toBe(false);+ // Past the hard bound, even a live holder's lock is reclaimed.+ const old = new Date(Date.now() - 31 * 60_000);+ fs.utimesSync(dir, old, old);+ expect(tryLock(dir)).toBe(true);+ });++ it('takes over a lock from another computer once its holder stops renewing it (b12)', () => {+ const dir = path.join(tempDir('lock'), '.lock-z');+ fs.mkdirSync(dir, {recursive: true});+ const owner = path.join(dir, 'owner.json');+ fs.writeFileSync(owner, JSON.stringify({pid: 4242, host: 'other-host'}));+ const t0 = Date.now();+ expect(tryLock(dir, {now: t0})).toBe(false);+ expect(tryLock(dir, {now: t0 + LEASE_SILENCE_MS - 1})).toBe(false);+ // The holder renews: the wait starts again from the change.+ renewLock(dir);+ expect(JSON.parse(fs.readFileSync(owner, 'utf8'))).toEqual({+ pid: 4242,+ host: 'other-host',+ beat: 1,+ });+ expect(tryLock(dir, {now: t0 + LEASE_SILENCE_MS})).toBe(false);+ expect(tryLock(dir, {now: t0 + 2 * LEASE_SILENCE_MS - 1})).toBe(false);+ // Unrenewed for the whole lease, as this run saw it: taken over.+ expect(tryLock(dir, {now: t0 + 2 * LEASE_SILENCE_MS})).toBe(true);+ expect(JSON.parse(fs.readFileSync(owner, 'utf8'))).toEqual({+ pid: process.pid,+ host: os.hostname(),+ at: expect.any(Number),+ });+ });++ it('reclaims a lock with no owner record after a few seconds', () => {+ const dir = path.join(tempDir('lock'), '.lock-y');+ fs.mkdirSync(dir, {recursive: true});+ expect(tryLock(dir)).toBe(false);+ const old = new Date(Date.now() - 11_000);+ fs.utimesSync(dir, old, old);+ expect(tryLock(dir)).toBe(true);+ });+});++describe('a slow install', () => {+ it('ends in a timeout reason, never a stopped run, when npm hits the time limit', () => {+ const cacheDir = tempDir('cache');+ /** @type {import('./cache.mjs').runNpm} */+ const run = () => ({+ status: null,+ signal: 'SIGTERM',+ stdout: '',+ stderr: '',+ error: Object.assign(new Error('spawnSync npm ETIMEDOUT'), {+ code: 'ETIMEDOUT',+ }),+ });+ const result = ensureRelease('0.6.8', {cacheDir, run});+ expect('reason' in result && result.reason).toMatch(+ /did not finish within 15 minutes/,+ );+ expect('signal' in result && result.signal).toBeFalsy();+ });++ it('tells the caller once when it installs and once when it waits', () => {+ const cacheDir = tempDir('cache');+ /** @type {string[]} */+ const events = [];+ ensureRelease('0.6.8', {+ cacheDir,+ run: fakeNpm().run,+ onProgress: (e, v) => events.push(`${e} ${v}`),+ });+ expect(events).toEqual(['install 0.6.8']);+ const other = tempDir('cache');+ const lock = path.join(releasesDir(other), '.lock-0.6.8');+ fs.mkdirSync(lock, {recursive: true});+ fs.writeFileSync(+ path.join(lock, 'owner.json'),+ JSON.stringify({pid: process.pid, host: os.hostname()}),+ );+ events.length = 0;+ ensureRelease('0.6.8', {+ cacheDir: other,+ run: fakeNpm().run,+ waitMs: 500,+ onProgress: (e, v) => events.push(`${e} ${v}`),+ });+ expect(events).toEqual(['wait 0.6.8']);+ });+});++describe('a damaged library file', () => {+ it('is caught by the size record and replaced', () => {+ const cacheDir = tempDir('cache');+ const npm = fakeNpm();+ ensureRelease('0.6.8', {cacheDir, run: npm.run});+ const cli = path.join(+ releasesDir(cacheDir),+ '0.6.8',+ 'node_modules',+ '@astryxdesign',+ 'cli',+ );+ fs.writeFileSync(path.join(cli, 'extra-module.mjs'), 'export {};\n');+ forgetVerifiedReleases();+ expect(cachedRelease('0.6.8', cacheDir)).toBeNull();+ expect('bin' in ensureRelease('0.6.8', {cacheDir, run: npm.run})).toBe(+ true,+ );+ expect(npm.calls).toHaveLength(2);+ });+});++describe('stopped and damaged installs heal', () => {+ it('takes over a lock whose holder has gone, and clears its scratch folder', () => {+ const cacheDir = tempDir('cache');+ const root = releasesDir(cacheDir);+ const lock = path.join(root, '.lock-0.6.8');+ fs.mkdirSync(lock, {recursive: true});+ // A process id no run has: the holder was killed.+ fs.writeFileSync(+ path.join(lock, 'owner.json'),+ JSON.stringify({pid: 2 ** 22 + 7, host: os.hostname()}),+ );+ fs.mkdirSync(path.join(root, '.tmp-0.6.8-999-abc'), {recursive: true});+ const started = Date.now();+ const result = ensureRelease('0.6.8', {+ cacheDir,+ run: fakeNpm().run,+ waitMs: 60_000,+ });+ expect('bin' in result).toBe(true);+ expect(Date.now() - started).toBeLessThan(10_000);+ expect(fs.readdirSync(root).filter(n => n.startsWith('.'))).toEqual([]);+ });++ it('waits for a holder that is still running', () => {+ const cacheDir = tempDir('cache');+ const lock = path.join(releasesDir(cacheDir), '.lock-0.6.8');+ fs.mkdirSync(lock, {recursive: true});+ fs.writeFileSync(+ path.join(lock, 'owner.json'),+ JSON.stringify({pid: process.pid, host: os.hostname()}),+ );+ const result = ensureRelease('0.6.8', {+ cacheDir,+ run: fakeNpm().run,+ waitMs: 300,+ });+ expect('reason' in result && result.reason).toMatch(/still installing/);+ });++ it('replaces a release whose marker, Core, or entry file is damaged', () => {+ /** @type {Array<(dir: string) => void>} */+ const damage = [+ dir =>+ fs.writeFileSync(path.join(dir, 'release.json'), '{"version": "0.6'),+ dir =>+ fs.rmSync(path.join(dir, 'node_modules', '@astryxdesign', 'core'), {+ recursive: true,+ }),+ dir =>+ fs.writeFileSync(+ path.join(dir, 'node_modules', '@astryxdesign', 'cli', 'bin.cjs'),+ '#!/usr/bin/env node\n',+ ),+ ];+ for (const harm of damage) {+ const cacheDir = tempDir('cache');+ const npm = fakeNpm();+ const first = ensureRelease('0.6.8', {cacheDir, run: npm.run});+ expect('bin' in first).toBe(true);+ harm(path.join(releasesDir(cacheDir), '0.6.8'));+ forgetVerifiedReleases();+ expect(cachedRelease('0.6.8', cacheDir)).toBeNull();+ const healed = ensureRelease('0.6.8', {cacheDir, run: npm.run});+ expect('bin' in healed && healed.version).toBe('0.6.8');+ expect(npm.calls).toHaveLength(2);+ expect(cachedRelease('0.6.8', cacheDir)).not.toBeNull();+ }+ });++ it('says the cache cannot be written instead of throwing', () => {+ const parent = tempDir('ro');+ const cacheDir = path.join(parent, 'cache');+ // A file where the cache folder should be: no folder can be made there.+ fs.writeFileSync(cacheDir, '');+ const result = ensureRelease('0.6.8', {cacheDir, run: fakeNpm().run});+ expect('reason' in result && result.reason).toMatch(/cannot be written/);+ });+});++describe('runNpm time limit', () => {+ it('ends a package manager that ignores SIGTERM, leaving no process behind', () => {+ const marker = tempDir('npm-pid');+ const pidFile = path.join(marker, 'pid');+ const result = runNpm([], {+ timeoutMs: 500,+ npm: {+ command: process.execPath,+ prefix: [+ '-e',+ `require('node:fs').writeFileSync(${JSON.stringify(pidFile)}, String(process.pid)); process.on('SIGTERM', () => {}); setTimeout(() => {}, 60000);`,+ ],+ shell: false,+ },+ });+ expect(/** @type {any} */ (result.error)?.code).toBe('ETIMEDOUT');+ const pid = Number(fs.readFileSync(pidFile, 'utf-8'));+ expect(() => process.kill(pid, 0)).toThrow();+ });+});++describe('no install outlives its run', () => {+ /** @param {number} pid */+ const alive = pid => {+ try {+ process.kill(pid, 0);+ return true;+ } catch {+ return false;+ }+ };+ /** @param {() => boolean} done @param {number} ms */+ const waitFor = async (done, ms) => {+ const end = Date.now() + ms;+ while (Date.now() < end) {+ if (done()) return true;+ await new Promise(r => setTimeout(r, 100));+ }+ return done();+ };++ it('ends npm when the run that started it is killed outright, and removes its process-id record', async () => {+ const dir = tempDir('orphan');+ const pidFile = path.join(dir, 'npm-pid');+ // The record a release lock keeps of npm's process id.+ const record = path.join(dir, 'npm.pid');+ const cacheModule = new URL('./cache.mjs', import.meta.url).href;+ const sleeper = `require('node:fs').writeFileSync(${JSON.stringify(pidFile)}, String(process.pid)); setTimeout(() => {}, 120000);`;+ const script = `import(${JSON.stringify(cacheModule)}).then(m => m.runNpm([], {timeoutMs: 120000, pidFile: ${JSON.stringify(record)}, npm: {command: process.execPath, prefix: ['-e', ${JSON.stringify(sleeper)}], shell: false}}));`;+ const cli = spawn(process.execPath, ['-e', script], {stdio: 'ignore'});+ expect(await waitFor(() => fs.existsSync(pidFile), 10_000)).toBe(true);+ expect(await waitFor(() => fs.existsSync(record), 5_000)).toBe(true);+ const npmPid = Number(fs.readFileSync(pidFile, 'utf-8'));+ expect(alive(npmPid)).toBe(true);+ cli.kill('SIGKILL');+ expect(await waitFor(() => !alive(npmPid), 5_000)).toBe(true);+ // A later takeover finds no id that could now name another process.+ expect(await waitFor(() => !fs.existsSync(record), 5_000)).toBe(true);+ }, 30_000);++ it('ends npm, which ignores Ctrl-C, when the run gets Ctrl-C', async () => {+ const dir = tempDir('ctrlc');+ const pidFile = path.join(dir, 'npm-pid');+ const cacheModule = new URL('./cache.mjs', import.meta.url).href;+ const sleeper = `require('node:fs').writeFileSync(${JSON.stringify(pidFile)}, String(process.pid)); process.on('SIGINT', () => {}); setTimeout(() => {}, 120000);`;+ const script = `import(${JSON.stringify(cacheModule)}).then(m => m.runNpm([], {timeoutMs: 120000, npm: {command: process.execPath, prefix: ['-e', ${JSON.stringify(sleeper)}], shell: false}}));`;+ // Its own group, as a terminal's foreground job: Ctrl-C reaches the group.+ const cli = spawn(process.execPath, ['-e', script], {+ stdio: 'ignore',+ detached: true,+ });+ expect(await waitFor(() => fs.existsSync(pidFile), 10_000)).toBe(true);+ const npmPid = Number(fs.readFileSync(pidFile, 'utf-8'));+ const exited = new Promise(resolve => cli.on('exit', resolve));+ process.kill(-(/** @type {number} */ (cli.pid)), 'SIGINT');+ expect(await waitFor(() => !alive(npmPid), 5_000)).toBe(true);+ await exited;+ }, 30_000);++ it("a run that takes over a dead run's lock ends the install it recorded", async () => {+ const cacheDir = tempDir('cache');+ const lock = path.join(releasesDir(cacheDir), '.lock-0.6.8');+ fs.mkdirSync(lock, {recursive: true});+ // An install left running by a run that was killed: its own group, node+ // running npm's entry file to install this release.+ const at = Date.now() - 1000;+ const npmCli = path.join(tempDir('npm'), 'npm-cli.js');+ fs.writeFileSync(npmCli, 'setTimeout(() => {}, 120000)');+ const leftover = spawn(+ process.execPath,+ [+ npmCli,+ 'install',+ '@astryxdesign/[email protected]',+ '@astryxdesign/[email protected]',+ ],+ {+ detached: true,+ stdio: 'ignore',+ },+ );+ leftover.unref();+ await new Promise(resolve => setTimeout(resolve, 300));+ fs.writeFileSync(+ path.join(lock, 'owner.json'),+ JSON.stringify({pid: 2 ** 22 + 7, host: os.hostname(), at}),+ );+ fs.writeFileSync(path.join(lock, 'npm.pid'), String(leftover.pid));+ expect(alive(/** @type {number} */ (leftover.pid))).toBe(true);+ const result = ensureRelease('0.6.8', {cacheDir, run: fakeNpm().run});+ expect('bin' in result).toBe(true);+ expect(+ await waitFor(() => !alive(/** @type {number} */ (leftover.pid)), 5_000),+ ).toBe(true);+ }, 30_000);+});diff --git a/packages/cli/foundation/release/choose.mjs b/packages/cli/foundation/release/choose.mjsnew file mode 100644index 0000000000..b97cef3cec--- /dev/null+++ b/packages/cli/foundation/release/choose.mjs@@ -0,0 +1,677 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Which release answers a run (spec AST-081 FR2, FR3, FR6, FR9).+ *+ * As released, the project decides who answers (DEC-10):+ *+ * - **In a project that installs its own CLI**, that CLI answers, whatever its+ * version: every other copy hands the run to it, `astryx upgrade` included.+ * - **In a project with no CLI of its own** (only Core, or nothing installed+ * yet), the copy that started the run answers, as it always has; a hint,+ * once a day, names the command that adds the CLI at Core's version+ * (notices.mjs).+ * - **When the project's own CLI cannot start**, the release equal to the+ * project's Core answers (the matched release): the copy that started the+ * run when it is that release, else the release in the per-user cache,+ * installed first. When it cannot be obtained, the copy that started the+ * run answers, announced (handoff.mjs).+ * - **Outside a project**, every copy answers itself, the global copy+ * included; a newer release is announced, never installed (notices.mjs).+ *+ * Core deciding over the project's own CLI, and the matched release for a+ * project with only Core, are the next minor release's change.+ *+ * A copy never hands a run to itself, so a run is handed off at most once:+ * the copy it reaches makes the same choice and finds itself.+ *+ * @input the folder, the running copy+ * @output a {@link ReleaseChoice}+ * @position foundation/release — called once per run by handoff.mjs.+ */++import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {+ readReleaseFacts,+ readJson,+ CORE_PACKAGE_NAME,+ CLI_PACKAGE_NAME,+} from './project.mjs';+import {+ cliBinOf,+ isInReleaseCache,+ isReleaseVersion,+ resolvePublishedVersion,+ userCacheDir,+} from './cache.mjs';+import {relativeWithin, samePath} from '../fs/path-compare.mjs';++/**+ * The copy that is running.+ * @typedef {object} RunningCopy+ * @property {string} version its package version+ * @property {string} root its package folder+ */++/**+ * Who answers the run.+ * @typedef {object} ReleaseChoice+ * @property {'project' | 'starting' | 'matched' | 'carried' | 'fallback'} copy+ * the kind of copy that answers (`meta.answeredBy.copy`): `project`, the+ * project's own CLI; `starting`, the copy that started the run, in a project+ * with no CLI of its own; `matched`, the release equal to the project's+ * Core, when the project's own CLI cannot start; `carried`, outside a+ * project; `fallback`, the copy that started the run when the matched+ * release could not be obtained (spec AST-081 FR2, FR5)+ * @property {'self' | 'project-cli' | 'release'} answer `self`: this copy;+ * `project-cli`: hand off to the project's CLI; `release`: hand off to the+ * cached release `version`+ * @property {string} version the release that answers+ * @property {string | null} bin the entry file to hand off to (`project-cli`+ * and a cached `release` that is already installed)+ * @property {string | null} coreVersion the Core the answering release pairs+ * with, when known now+ * @property {boolean} inProject+ * @property {string | null} unavailable why the release cannot answer, when it+ * cannot+ */++/**+ * @param {string} p+ * @returns {string}+ */+function real(p) {+ try {+ return fs.realpathSync(p);+ } catch {+ return path.resolve(p);+ }+}++/** Folder-name patterns of package-manager global installs that hold a package.json. */+const GLOBAL_OWNER_PATTERNS = [+ // pnpm: `<pnpm home>/global/5` before pnpm 10, `<pnpm home>/global/v11/<id>` since.+ /[\\/]global[\\/]v?\d+(?:[\\/][^\\/]+)?$/,+ // Yarn 1: `~/.config/yarn/global`, or `%LOCALAPPDATA%\Yarn\Data\global` on Windows.+ /[\\/]yarn[\\/](?:data[\\/])?global$/i,+ // Bun: `<BUN_INSTALL>/install/global`, `~/.bun/install/global` by default.+ /[\\/]install[\\/]global$/i,+];++/**+ * Where a global install's settings come from: the home folder, the+ * environment, and the platform. Defaults to this process's.+ * @typedef {{home?: string, env?: NodeJS.ProcessEnv, platform?: NodeJS.Platform}} GlobalWhere+ */++/**+ * The value a line `<key> <value>` or `<key>=<value>` sets in a package+ * manager's settings file (`.yarnrc`, `.npmrc`, `bunfig.toml`), unquoted, or+ * null.+ * @param {string} file+ * @param {string} key+ * @returns {string | null}+ */+function settingIn(file, key) {+ let text;+ try {+ text = fs.readFileSync(file, 'utf8');+ } catch {+ return null;+ }+ const escaped = key.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');+ const match = new RegExp(+ `^\\s*${escaped}\\s*(?:=|\\s)\\s*(.+?)\\s*$`,+ 'mu',+ ).exec(text);+ if (!match) return null;+ return match[1].replace(/^(["'])(.*)\1$/u, '$2');+}++/**+ * An absolute folder from a setting, with `~` for the home folder; null for a+ * relative or empty one.+ * @param {string | null | undefined} value+ * @param {string} home+ * @param {NodeJS.Platform} platform+ * @returns {string | null}+ */+function absoluteFolder(value, home, platform) {+ if (!value) return null;+ const paths = platform === 'win32' ? path.win32 : path.posix;+ const expanded = value.startsWith('~')+ ? paths.join(home, value.slice(1))+ : value;+ return paths.isAbsolute(expanded) ? paths.normalize(expanded) : null;+}++/**+ * The global folders the package managers' own settings name on this+ * computer, read the way each package manager reads them, never guessed from+ * a folder's layout:+ * - Bun: `$BUN_INSTALL/install/global`, else `~/.bun/install/global`, and a+ * `globalDir` in `~/.bunfig.toml` or `$XDG_CONFIG_HOME/.bunfig.toml`.+ * - Yarn 1: the `global-folder` setting (`YARN_GLOBAL_FOLDER`,+ * `npm_config_global_folder`, or `global-folder` in `~/.yarnrc`), else+ * `<data folder>/global`: `%LOCALAPPDATA%\Yarn\Data` on Windows,+ * `$XDG_DATA_HOME/yarn`, else `~/.config/yarn`.+ * - pnpm: `<PNPM_HOME>/global`, else `<data folder>/global` (`$XDG_DATA_HOME/pnpm`,+ * else `%LOCALAPPDATA%\pnpm`, `~/Library/pnpm`, or `~/.local/share/pnpm`), and a+ * `global-dir` in `~/.npmrc` or pnpm's `rc` file; a global install is a+ * numbered folder below it.+ * @param {GlobalWhere} [where]+ * @returns {Array<{manager: 'bun' | 'yarn' | 'pnpm', folder: string}>}+ */+export function configuredGlobalFolders(where = {}) {+ const {+ home = os.homedir(),+ env = process.env,+ platform = process.platform,+ } = where;+ const paths = platform === 'win32' ? path.win32 : path.posix;+ const abs = (/** @type {string | null | undefined} */ value) =>+ absoluteFolder(value, home, platform);+ const xdgConfig = abs(env.XDG_CONFIG_HOME) ?? paths.join(home, '.config');+ const xdgData = abs(env.XDG_DATA_HOME);+ const localAppData =+ abs(env.LOCALAPPDATA) ?? paths.join(home, 'AppData', 'Local');+ /** @type {Array<{manager: 'bun' | 'yarn' | 'pnpm', folder: string}>} */+ const out = [];+ // Bun+ out.push({+ manager: 'bun',+ folder: paths.join(+ abs(env.BUN_INSTALL) ?? paths.join(home, '.bun'),+ 'install',+ 'global',+ ),+ });+ for (const file of [+ paths.join(home, '.bunfig.toml'),+ paths.join(xdgConfig, '.bunfig.toml'),+ ]) {+ const dir = abs(settingIn(file, 'globalDir'));+ if (dir) out.push({manager: 'bun', folder: dir});+ }+ // Yarn 1+ const yarnSetting =+ abs(env.YARN_GLOBAL_FOLDER) ??+ abs(env.npm_config_global_folder) ??+ abs(settingIn(paths.join(home, '.yarnrc'), 'global-folder'));+ const yarnData =+ platform === 'win32'+ ? paths.join(localAppData, 'Yarn', 'Data')+ : xdgData+ ? paths.join(xdgData, 'yarn')+ : paths.join(home, '.config', 'yarn');+ out.push({+ manager: 'yarn',+ folder: yarnSetting ?? paths.join(yarnData, 'global'),+ });+ // pnpm+ // pnpm's data folder: PNPM_HOME, else $XDG_DATA_HOME/pnpm on any platform,+ // else the platform's own.+ const pnpmHome =+ abs(env.PNPM_HOME) ??+ (xdgData+ ? paths.join(xdgData, 'pnpm')+ : platform === 'win32'+ ? paths.join(localAppData, 'pnpm')+ : platform === 'darwin'+ ? paths.join(home, 'Library', 'pnpm')+ : paths.join(home, '.local', 'share', 'pnpm'));+ out.push({manager: 'pnpm', folder: paths.join(pnpmHome, 'global')});+ for (const file of [+ paths.join(home, '.npmrc'),+ paths.join(xdgConfig, 'pnpm', 'rc'),+ ]) {+ const dir = abs(settingIn(file, 'global-dir'));+ if (dir) out.push({manager: 'pnpm', folder: dir});+ }+ return out;+}++/**+ * The package manager's global folder that holds the CLI at `root`, when the+ * package manager's own settings name that folder (configuredGlobalFolders);+ * null otherwise. A folder that only looks like one, such as an app made with+ * `yarn add` alone or one under a folder named `install/global`, is not.+ * @param {string} root the CLI package's real folder+ * @param {GlobalWhere} [where]+ * @returns {{manager: 'bun' | 'pnpm' | 'yarn', folder: string} | null}+ */+export function globalFolderOf(root, where = {}) {+ const place = installPlaceOf(root);+ if (place.runner || !place.owner) return null;+ const owner = place.owner;+ const platform = where.platform ?? process.platform;+ for (const known of configuredGlobalFolders(where)) {+ // Compared as real folders, so a linked home folder reads the same.+ const folder = real(known.folder);+ if (known.manager === 'pnpm') {+ // `<global-dir>/<n>` before pnpm 11, `<global-dir>/v<n>/<id>` since.+ const rel = relativeWithin(folder, owner, platform);+ if (rel !== null && /^v?\d+(?:[\\/][^\\/]+)?$/u.test(rel)) {+ return {manager: 'pnpm', folder: owner};+ }+ } else if (samePath(folder, owner, platform)) {+ return {manager: known.manager, folder: owner};+ }+ }+ return null;+}++/** Path markers of package runners' temporary installs. */+const RUNNER_CACHE =+ /[\\/]_npx[\\/]|[\\/]dlx[-\\/]|[\\/]\.bun[\\/]install[\\/]cache[\\/]|[\\/]bunx-|[\\/]xfs-/i;++/**+ * Where an installed CLI package lives: its owner, the folder that holds the+ * `node_modules` it is in (above pnpm's `.pnpm` store), and whether that owner+ * is named like a package manager's default global folder (`knownGlobal`, a+ * hint only: isGlobalCopy decides from the package managers' settings). Pure:+ * reads no file, and+ * accepts either separator, so Windows paths read the same on every platform.+ * @param {string} root the package's real folder+ * @returns {{runner: boolean, owner: string | null, knownGlobal: boolean}}+ */+export function installPlaceOf(root) {+ if (RUNNER_CACHE.test(root)) {+ return {runner: true, owner: null, knownGlobal: false};+ }+ const sep = /^[A-Za-z]:\\|^\\\\/.test(root) ? '\\' : path.sep;+ const parts = root.split(/[\\/]/);+ const at = parts.lastIndexOf('node_modules');+ if (at < 1) return {runner: false, owner: null, knownGlobal: false};+ let owner = parts.slice(0, at).join(sep) || sep;+ // pnpm keeps the real folder in `<owner>/node_modules/.pnpm/<id>/node_modules`,+ // or, for its global folder before pnpm 11, in `<owner>/.pnpm/<id>/node_modules`.+ const pnpmAt = parts.lastIndexOf('.pnpm');+ if (pnpmAt > 0 && pnpmAt < at) {+ owner =+ parts+ .slice(0, parts[pnpmAt - 1] === 'node_modules' ? pnpmAt - 1 : pnpmAt)+ .join(sep) || sep;+ }+ return {+ runner: false,+ owner,+ knownGlobal: GLOBAL_OWNER_PATTERNS.some(re => re.test(owner)),+ };+}++/**+ * Whether `root` is inside a pnpm store's `links` folder (`<store>/v<N>/links`),+ * where the global virtual store keeps its packages.+ * @param {string} root+ * @returns {boolean}+ */+function inPnpmStoreLinks(root) {+ const parts = root.split(/[\\/]/);+ const at = parts.lastIndexOf('links');+ return at >= 2 && /^v\d+$/u.test(parts[at - 1]);+}++/**+ * Whether a global folder of pnpm's, as its settings name it, installs the+ * CLI package at `root`: `<global-dir>/v<N>/<id>/node_modules/@astryxdesign/cli`+ * (or `<global-dir>/<N>/node_modules/…` before pnpm 11) resolves to it.+ * @param {string} root the CLI package's real folder+ * @param {GlobalWhere} where+ * @returns {boolean}+ */+function linkedFromPnpmGlobal(root, where) {+ const platform = where.platform ?? process.platform;+ const cliIn = (/** @type {string} */ dir) =>+ path.join(dir, 'node_modules', '@astryxdesign', 'cli');+ for (const known of configuredGlobalFolders(where)) {+ if (known.manager !== 'pnpm') continue;+ /** @type {string[]} */+ let versions;+ try {+ versions = fs.readdirSync(known.folder);+ } catch {+ continue;+ }+ for (const version of versions.filter(v => /^v?\d+$/u.test(v))) {+ const dir = path.join(known.folder, version);+ /** @type {string[]} */+ let ids = [];+ try {+ ids = fs.readdirSync(dir);+ } catch {+ // Not a folder.+ }+ for (const candidate of [dir, ...ids.map(id => path.join(dir, id))]) {+ if (samePath(real(cliIn(candidate)), root, platform)) return true;+ }+ }+ }+ return false;+}++/**+ * Is the running copy the CLI package installed for the computer+ * (`npm i -g`, `pnpm add -g`, `yarn global add`, `bun add -g`, Volta)?+ *+ * Read from where the package lives: in a `node_modules` folder whose owner+ * holds no package.json (npm's global folder), or whose owner is a global+ * folder a package manager's own settings name (globalFolderOf). A copy in a+ * project, in a package runner's temporary install, or in the release cache+ * is not, and when unsure the answer is no: a copy that is not global runs no+ * update check and writes no agent skill.+ *+ * @param {string} cliRoot+ * @param {string} [cacheDir]+ * @param {GlobalWhere} [where]+ * @returns {boolean}+ */+export function isGlobalCopy(cliRoot, cacheDir = userCacheDir(), where = {}) {+ const root = real(cliRoot);+ const place = installPlaceOf(root);+ if (place.runner || !place.owner || isInReleaseCache(root, cacheDir)) {+ return false;+ }+ if (globalFolderOf(root, where)) return true;+ // pnpm's global virtual store keeps every package, a project's own CLI+ // included, in `<store>/v<N>/links/…`, whose folders hold no package.json:+ // global only when a pnpm global folder the settings name links to it.+ if (inPnpmStoreLinks(root)) return linkedFromPnpmGlobal(root, where);+ // npm's global folder holds no package.json; a project always has one.+ return !fs.existsSync(path.join(place.owner, 'package.json'));+}++/**+ * The Core release a project records, without asking the registry: the Core+ * the folder reads, else the version its lockfile records, else an exact+ * declared version; null for a range.+ * @param {import('./project.mjs').ReleaseFacts} facts+ * @returns {string | null}+ */+export function coreVersionOf(facts) {+ if (facts.core) return facts.core.version;+ if (isReleaseVersion(facts.lockedCoreVersion)) {+ return /** @type {string} */ (facts.lockedCoreVersion);+ }+ if (facts.declaredCoreRange) {+ return exactOrRange(CORE_PACKAGE_NAME, facts.declaredCoreRange).version;+ }+ return null;+}++/**+ * The release that matches a project's facts, before any registry question.+ * @param {import('./project.mjs').ReleaseFacts} facts+ * @returns {{version: string | null, range: {name: string, spec: string} | null}}+ */+export function matchedVersionOf(facts) {+ if (facts.core) return {version: facts.core.version, range: null};+ if (isReleaseVersion(facts.lockedCoreVersion)) {+ return {version: facts.lockedCoreVersion, range: null};+ }+ if (facts.declaredCoreRange) {+ return exactOrRange(CORE_PACKAGE_NAME, facts.declaredCoreRange);+ }+ if (facts.cli) return {version: facts.cli.version, range: null};+ if (isReleaseVersion(facts.lockedCliVersion)) {+ return {version: facts.lockedCliVersion, range: null};+ }+ if (facts.declaredCliRange) {+ return exactOrRange(CLI_PACKAGE_NAME, facts.declaredCliRange);+ }+ return {version: null, range: null};+}++/**+ * @param {string} name+ * @param {string} spec+ * @returns {{version: string | null, range: {name: string, spec: string} | null}}+ */+function exactOrRange(name, spec) {+ const trimmed = spec.trim().replace(/^=/, '').replace(/^v/, '');+ if (isReleaseVersion(trimmed)) return {version: trimmed, range: null};+ return {version: null, range: {name, spec}};+}++/**+ * Choose who answers a run started by `self` in `cwd`.+ *+ * A command that acts on the computer rather than the folder is chosen as+ * outside a project wherever it runs (`computer`), so a project's older CLI+ * never answers it.+ *+ * @param {{cwd: string, self: RunningCopy, cacheDir?: string, resolve?: typeof resolvePublishedVersion, computer?: boolean}} input+ * @returns {ReleaseChoice}+ */+export function chooseRelease({+ cwd,+ self,+ resolve = resolvePublishedVersion,+ computer = false,+}) {+ const facts = computer ? OUTSIDE : readReleaseFacts(cwd);+ const selfReal = real(self.root);++ if (!facts.inProject) {+ return {+ copy: 'carried',+ answer: 'self',+ version: self.version,+ bin: null,+ coreVersion: null,+ inProject: false,+ unavailable: null,+ };+ }++ // A project that installs its own CLI is answered by that CLI, whatever its+ // version, and a project with none by the copy that started the run, as+ // released (FR2, DEC-10; `spec:AST-017` FR12). Only a project whose own CLI+ // cannot start gets the Core-matched release.+ if (!facts.cli) {+ // A copy that lives inside the project itself, such as a workspace's own+ // CLI package beside its Core package, is the project's own CLI.+ const inside = isInside(selfReal, projectRootOf(facts));+ return {+ copy: inside ? 'project' : 'starting',+ answer: 'self',+ version: self.version,+ bin: null,+ coreVersion: coreVersionOf(facts),+ inProject: true,+ unavailable: null,+ };+ }+ {+ if (samePath(real(facts.cli.dir), selfReal)) {+ return {+ copy: 'project',+ answer: 'self',+ version: facts.cli.version,+ bin: null,+ coreVersion: facts.core?.version ?? null,+ inProject: true,+ unavailable: null,+ };+ }+ const bin = cliBinOf(facts.cli.dir);+ if (bin) {+ return {+ copy: 'project',+ answer: 'project-cli',+ version: facts.cli.version,+ bin,+ coreVersion: facts.core?.version ?? null,+ inProject: true,+ unavailable: null,+ };+ }+ }+ let {version, range} = matchedVersionOf(facts);+ if (!version && range) {+ version = resolve(range.name, range.spec);+ if (!version) {+ return {+ copy: 'matched',+ answer: 'release',+ version: `${range.name}@${range.spec}`,+ bin: null,+ coreVersion: null,+ inProject: true,+ unavailable: `no published release of ${range.name} matching "${range.spec}" could be found`,+ };+ }+ }++ const coreVersion = facts.core?.version ?? version;+ if (!version || version === self.version) {+ // A copy that lives inside the project itself, such as a workspace's own+ // CLI package beside its Core package, is the project's own CLI.+ if (isInside(selfReal, projectRootOf(facts))) {+ return {+ copy: 'project',+ answer: 'self',+ version: self.version,+ bin: null,+ coreVersion: facts.core?.version ?? null,+ inProject: true,+ unavailable: null,+ };+ }+ return {+ copy: 'matched',+ answer: 'self',+ version: self.version,+ bin: null,+ coreVersion,+ inProject: true,+ unavailable: null,+ };+ }+ return {+ copy: 'matched',+ answer: 'release',+ version,+ bin: null,+ coreVersion,+ inProject: true,+ unavailable: null,+ };+}++/**+ * The folder a project's facts point at: the declaring package.json's folder,+ * else the folder that holds the Core (the one above its node_modules, or the+ * workspace root above `packages/core`).+ * @param {import('./project.mjs').ReleaseFacts} facts+ * @returns {string | null}+ */+export function projectRootOf(facts) {+ if (facts.declaringDir) return facts.declaringDir;+ const dir = facts.core?.dir ?? facts.cli?.dir;+ if (!dir) return null;+ const parts = path.resolve(dir).split(path.sep);+ const at = parts.indexOf('node_modules');+ if (at > 0) return parts.slice(0, at).join(path.sep) || path.sep;+ return path.dirname(path.dirname(dir));+}++/**+ * Is `child` inside `parent` (both real paths), outside any node_modules+ * folder in between? A package installed into a project's node_modules is+ * found as the project's CLI already; this covers a copy that is part of the+ * project's own source, such as a workspace package.+ * @param {string} child+ * @param {string | null} parent+ * @returns {boolean}+ */+function isInside(child, parent) {+ if (!parent) return false;+ const rel = relativeWithin(real(parent), child);+ if (rel === null) return false;+ return !rel.split(/[\\/]/).includes('node_modules');+}++/** The facts of a folder outside any project. */+const OUTSIDE = Object.freeze({+ inProject: false,+ core: null,+ cli: null,+ declaringDir: null,+ declaredCoreRange: null,+ declaredCliRange: null,+ lockedCoreVersion: null,+ lockedCliVersion: null,+});++/** Options that take a value, so their value is not the command or topic. */+const VALUE_OPTIONS = new Set(['--lang', '--detail', '--depth']);++/**+ * Is this run a command that acts on the computer rather than the folder it+ * runs in? `astryx init --user`, which writes the computer-level agent text,+ * and `astryx docs global[/…]`, the docs of global mode itself, which the copy+ * that started the run answers, so they are readable inside a project whose+ * release predates them (spec AST-081 FR8, FR9).+ * @param {string[]} argv arguments after `astryx`+ * @returns {boolean}+ */+export function isComputerLevel(argv) {+ const words = [];+ for (let i = 0; i < argv.length && words.length < 2; i++) {+ const arg = argv[i];+ if (VALUE_OPTIONS.has(arg)) {+ i += 1;+ continue;+ }+ if (!arg.startsWith('-')) words.push(arg);+ }+ const [command, topic] = words;+ if (command === 'init') return argv.includes('--user');+ return (+ command === 'docs' &&+ typeof topic === 'string' &&+ (topic === 'global' || topic.startsWith('global/'))+ );+}++/**+ * The running copy, from its package folder.+ * @param {string} root+ * @returns {RunningCopy}+ */+export function runningCopy(root) {+ const pkg = readJson(path.join(root, 'package.json'));+ return {version: String(pkg?.version ?? '0.0.0'), root};+}++/**+ * Does the package at `cliDir` print its own who-answered line? Releases that+ * carry this module do; older ones answer silently, so the copy that hands a+ * run to them prints the line for them.+ * @param {string} cliDir+ * @returns {boolean}+ */+export function namesWhoAnswered(cliDir) {+ return fs.existsSync(+ path.join(cliDir, 'foundation', 'release', 'choose.mjs'),+ );+}++/**+ * The CLI package folder an entry file belongs to.+ * @param {string} bin+ * @returns {string}+ */+export function packageRootOf(bin) {+ let dir = path.dirname(real(bin));+ for (;;) {+ if (readJson(path.join(dir, 'package.json'))?.name === CLI_PACKAGE_NAME)+ return dir;+ const parent = path.dirname(dir);+ if (parent === dir) return path.dirname(real(bin));+ dir = parent;+ }+}diff --git a/packages/cli/foundation/release/choose.test.mjs b/packages/cli/foundation/release/choose.test.mjsnew file mode 100644index 0000000000..87bea4670b--- /dev/null+++ b/packages/cli/foundation/release/choose.test.mjs@@ -0,0 +1,427 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, it, expect, afterEach} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {+ chooseRelease,+ isComputerLevel,+ isGlobalCopy,+ matchedVersionOf,+ namesWhoAnswered,+} from './choose.mjs';+import {+ cleanupFixtures,+ installCore,+ installStandInCli,+ project,+ seedRelease,+ tempDir,+ writeJson,+} from '../../test-utils/release-fixtures.mjs';++afterEach(cleanupFixtures);++/**+ * A running copy installed somewhere that is not a project or a global+ * folder: a package runner's temporary install.+ * @param {string} version+ */+function runnerCopy(version) {+ const dir = path.join(tempDir('runner'), '_npx', 'abc');+ project(dir, {'@astryxdesign/cli': version});+ return {version, root: installStandInCli(dir, version)};+}++/**+ * A copy installed for the computer the way npm does it: a node_modules+ * folder whose owner holds no package.json.+ * @param {string} version+ */+function globalCopy(version) {+ const prefix = path.join(tempDir('global'), 'lib');+ fs.mkdirSync(prefix, {recursive: true});+ return {version, root: installStandInCli(prefix, version)};+}++describe('chooseRelease in a project', () => {+ it('hands off to the project CLI when it matches the project Core', () => {+ const root = project(tempDir(), {'@astryxdesign/core': '0.6.8'});+ installCore(root, '0.6.8');+ const cli = installStandInCli(root, '0.6.8');+ const choice = chooseRelease({+ cwd: root,+ self: globalCopy('0.7.2'),+ cacheDir: tempDir('cache'),+ });+ expect(choice).toMatchObject({+ copy: 'project',+ answer: 'project-cli',+ version: '0.6.8',+ });+ expect(choice.bin).toBe(path.join(cli, 'bin.cjs'));+ });++ it('answers itself when it is the project CLI', () => {+ const root = project(tempDir(), {'@astryxdesign/core': '0.6.8'});+ installCore(root, '0.6.8');+ const cli = installStandInCli(root, '0.6.8');+ const choice = chooseRelease({+ cwd: root,+ self: {version: '0.6.8', root: cli},+ cacheDir: tempDir('cache'),+ });+ expect(choice).toMatchObject({copy: 'project', answer: 'self'});+ });++ it("lets the project's own CLI answer even when it is another release than Core, both ways", () => {+ for (const [cliVersion, coreVersion] of [+ ['0.6.8', '0.7.0'],+ ['0.7.1', '0.6.8'],+ ]) {+ const root = project(tempDir(), {'@astryxdesign/core': coreVersion});+ installCore(root, coreVersion);+ const cli = installStandInCli(root, cliVersion);+ expect(+ chooseRelease({+ cwd: root,+ self: {version: cliVersion, root: cli},+ cacheDir: tempDir('cache'),+ }),+ ).toMatchObject({copy: 'project', answer: 'self', version: cliVersion});+ expect(+ chooseRelease({+ cwd: root,+ self: globalCopy('0.7.2'),+ cacheDir: tempDir('cache'),+ }),+ ).toMatchObject({+ copy: 'project',+ answer: 'project-cli',+ version: cliVersion,+ });+ }+ });++ it("hands a run to the project's own CLI even from a copy equal to the project's Core", () => {+ const root = project(tempDir(), {'@astryxdesign/core': '0.7.2'});+ installCore(root, '0.7.2');+ installStandInCli(root, '0.6.8');+ expect(+ chooseRelease({+ cwd: root,+ self: runnerCopy('0.7.2'),+ cacheDir: tempDir('cache'),+ }),+ ).toMatchObject({copy: 'project', answer: 'project-cli', version: '0.6.8'});+ });++ it('answers a Core-only project with the copy that started the run, as released, naming its Core', () => {+ const root = project(tempDir(), {'@astryxdesign/core': '0.6.8'});+ installCore(root, '0.6.8');+ for (const self of [runnerCopy('0.7.1'), globalCopy('0.6.8')]) {+ expect(+ chooseRelease({cwd: root, self, cacheDir: tempDir('cache')}),+ ).toMatchObject({+ copy: 'starting',+ answer: 'self',+ version: self.version,+ coreVersion: '0.6.8',+ inProject: true,+ });+ }+ });++ it('answers a workspace member with its own Core with the root CLI, as before global mode', () => {+ const ws = tempDir();+ writeJson(path.join(ws, 'package.json'), {+ name: 'ws',+ workspaces: ['apps/*'],+ devDependencies: {'@astryxdesign/cli': '0.7.1'},+ dependencies: {'@astryxdesign/core': '0.7.1'},+ });+ installCore(ws, '0.7.1');+ installStandInCli(ws, '0.7.1');+ const legacy = project(path.join(ws, 'apps', 'legacy'), {+ '@astryxdesign/core': '0.6.8',+ });+ installCore(legacy, '0.6.8');+ const choice = chooseRelease({+ cwd: legacy,+ self: globalCopy('0.7.2'),+ cacheDir: tempDir('cache'),+ });+ expect(choice).toMatchObject({copy: 'project', version: '0.7.1'});+ const web = project(path.join(ws, 'apps', 'web'), {+ '@astryxdesign/core': '0.7.1',+ });+ expect(+ chooseRelease({+ cwd: web,+ self: globalCopy('0.7.2'),+ cacheDir: tempDir('cache'),+ }),+ ).toMatchObject({+ copy: 'project',+ answer: 'project-cli',+ version: '0.7.1',+ });+ });++ it('answers a fresh clone with the copy that started the run, naming the Core its lockfile records', () => {+ const root = project(tempDir(), {'@astryxdesign/core': '^0.6.0'});+ writeJson(path.join(root, 'package-lock.json'), {+ lockfileVersion: 3,+ packages: {'node_modules/@astryxdesign/core': {version: '0.6.8'}},+ });+ /** @type {string[]} */+ const asked = [];+ expect(+ chooseRelease({+ cwd: root,+ self: runnerCopy('0.7.2'),+ cacheDir: tempDir('cache'),+ resolve: (name, spec) => {+ asked.push(`${name}@${spec}`);+ return null;+ },+ }),+ ).toMatchObject({copy: 'starting', version: '0.7.2', coreVersion: '0.6.8'});+ // No registry question for a project the starting copy answers.+ expect(asked).toEqual([]);+ });++ it('matches a project whose own CLI cannot start from its lockfile, else its declared range, else reports the range unavailable', () => {+ const root = project(tempDir(), {'@astryxdesign/core': '^0.6.0'});+ installStandInCli(root, '0.6.0', {bin: false});+ writeJson(path.join(root, 'package-lock.json'), {+ lockfileVersion: 3,+ packages: {'node_modules/@astryxdesign/core': {version: '0.6.8'}},+ });+ expect(+ chooseRelease({+ cwd: root,+ self: runnerCopy('0.7.2'),+ cacheDir: tempDir('cache'),+ }),+ ).toMatchObject({copy: 'matched', version: '0.6.8'});+ const bare = project(tempDir(), {'@astryxdesign/core': '^0.6.0'});+ installStandInCli(bare, '0.6.0', {bin: false});+ /** @type {string[]} */+ const asked = [];+ expect(+ chooseRelease({+ cwd: bare,+ self: runnerCopy('0.7.2'),+ cacheDir: tempDir('cache'),+ resolve: (name, spec) => {+ asked.push(`${name}@${spec}`);+ return '0.6.8';+ },+ }),+ ).toMatchObject({copy: 'matched', answer: 'release', version: '0.6.8'});+ expect(asked).toEqual(['@astryxdesign/core@^0.6.0']);+ const none = project(tempDir(), {'@astryxdesign/core': '^9.0.0'});+ installStandInCli(none, '0.6.0', {bin: false});+ expect(+ chooseRelease({+ cwd: none,+ self: runnerCopy('0.7.2'),+ cacheDir: tempDir('cache'),+ resolve: () => null,+ }).unavailable,+ ).toMatch(/\^9\.0\.0/);+ });++ it("passes a project CLI with no astryx command over for the release matching the project's Core", () => {+ const root = project(tempDir(), {'@astryxdesign/core': '0.6.8'});+ installCore(root, '0.6.8');+ installStandInCli(root, '0.6.8', {bin: false});+ expect(+ chooseRelease({+ cwd: root,+ self: globalCopy('0.7.2'),+ cacheDir: tempDir('cache'),+ }),+ ).toMatchObject({copy: 'matched', answer: 'release', version: '0.6.8'});+ });++ it('ignores a version requested on the command line: the copy still hands off', () => {+ const root = project(tempDir(), {'@astryxdesign/core': '0.6.8'});+ installCore(root, '0.6.8');+ installStandInCli(root, '0.6.8');+ expect(+ chooseRelease({+ cwd: root,+ self: runnerCopy('0.7.0'),+ cacheDir: tempDir('cache'),+ }),+ ).toMatchObject({+ answer: 'project-cli',+ version: '0.6.8',+ });+ });+});++describe("chooseRelease for a workspace's own CLI package", () => {+ it('counts a copy inside the project, outside node_modules, as the project CLI', () => {+ const ws = tempDir();+ writeJson(path.join(ws, 'package.json'), {name: 'ws', private: true});+ writeJson(path.join(ws, 'packages', 'core', 'package.json'), {+ name: '@astryxdesign/core',+ version: '0.7.2',+ });+ const cli = path.join(ws, 'packages', 'cli');+ writeJson(path.join(cli, 'package.json'), {+ name: '@astryxdesign/cli',+ version: '0.7.2',+ });+ const self = {version: '0.7.2', root: cli};+ expect(+ chooseRelease({cwd: ws, self, cacheDir: tempDir('cache')}),+ ).toMatchObject({copy: 'project', answer: 'self'});+ });+});++describe('chooseRelease outside a project', () => {+ it('answers with the running copy, the global copy included, whatever releases are cached', () => {+ const empty = tempDir('empty');+ const cacheDir = tempDir('cache');+ seedRelease(cacheDir, '0.7.3');+ for (const self of [globalCopy('0.7.2'), runnerCopy('0.7.0')]) {+ expect(chooseRelease({cwd: empty, self, cacheDir})).toMatchObject({+ copy: 'carried',+ answer: 'self',+ version: self.version,+ });+ }+ });+});++describe('isGlobalCopy', () => {+ it('knows npm, pnpm, Yarn, and Bun global folders from project and runner copies', () => {+ const base = tempDir('globals');+ const cacheDir = tempDir('cache');+ /** @param {string} rel @param {boolean} [withPkg] */+ const at = (rel, withPkg = false) => {+ const owner = path.join(base, rel);+ fs.mkdirSync(owner, {recursive: true});+ if (withPkg) writeJson(path.join(owner, 'package.json'), {name: 'owner'});+ return installStandInCli(owner, '0.7.2');+ };+ // The package managers' settings, as on a computer whose home is `base`.+ const where = {+ home: base,+ platform: /** @type {const} */ ('linux'),+ env: {PNPM_HOME: path.join(base, 'share/pnpm')},+ };+ expect(isGlobalCopy(at('usr/lib'), cacheDir, where)).toBe(true);+ expect(isGlobalCopy(at('share/pnpm/global/5', true), cacheDir, where)).toBe(+ true,+ );+ // pnpm 11+: the global packages live in a store folder under global/v11/<id>.+ const pnpmOwner = path.join(base, 'share/pnpm/global/v11/2f9c1a');+ fs.mkdirSync(pnpmOwner, {recursive: true});+ writeJson(path.join(pnpmOwner, 'package.json'), {+ dependencies: {'@astryxdesign/cli': '0.7.2'},+ });+ const pnpmStore = path.join(+ pnpmOwner,+ 'node_modules',+ '.pnpm',+ '@[email protected]',+ );+ fs.mkdirSync(pnpmStore, {recursive: true});+ expect(+ isGlobalCopy(installStandInCli(pnpmStore, '0.7.2'), cacheDir, where),+ ).toBe(true);+ expect(isGlobalCopy(at('.config/yarn/global', true), cacheDir, where)).toBe(+ true,+ );+ expect(isGlobalCopy(at('.bun/install/global', true), cacheDir, where)).toBe(+ true,+ );+ // Named like one, but no package manager's settings name it.+ expect(isGlobalCopy(at('other/pnpm/global/5', true), cacheDir, where)).toBe(+ false,+ );+ expect(isGlobalCopy(at('other/yarn/global', true), cacheDir, where)).toBe(+ false,+ );+ expect(isGlobalCopy(at('app', true), cacheDir, where)).toBe(false);+ expect(isGlobalCopy(at('npm/_npx/123', true), cacheDir, where)).toBe(false);+ const seeded = seedRelease(cacheDir, '0.7.2');+ expect(+ isGlobalCopy(+ path.join(seeded, 'node_modules', '@astryxdesign', 'cli'),+ cacheDir,+ ),+ ).toBe(false);+ });++ it("treats a project's pnpm store copy as the project's", () => {+ const app = tempDir('app');+ writeJson(path.join(app, 'package.json'), {name: 'app'});+ const store = path.join(+ app,+ 'node_modules',+ '.pnpm',+ '@[email protected]',+ );+ fs.mkdirSync(store, {recursive: true});+ expect(+ isGlobalCopy(installStandInCli(store, '0.7.2'), tempDir('cache')),+ ).toBe(false);+ });+});++describe('matchedVersionOf', () => {+ it('takes an exact declared version without asking the registry', () => {+ expect(+ matchedVersionOf({+ inProject: true,+ core: null,+ cli: null,+ declaringDir: '/x',+ declaredCoreRange: '0.6.8',+ declaredCliRange: null,+ lockedCoreVersion: null,+ lockedCliVersion: null,+ }),+ ).toEqual({version: '0.6.8', range: null});+ });+});++describe('namesWhoAnswered', () => {+ it('is true for this release and false for a stand-in from before it', () => {+ expect(+ namesWhoAnswered(path.resolve(import.meta.dirname, '..', '..')),+ ).toBe(true);+ expect(namesWhoAnswered(installStandInCli(tempDir(), '0.6.8'))).toBe(false);+ });+});++describe('isComputerLevel', () => {+ it('is init --user, with root options anywhere before it', () => {+ expect(isComputerLevel(['init', '--user'])).toBe(true);+ expect(+ isComputerLevel(['--json', 'init', '--user', '--remove-agents']),+ ).toBe(true);+ expect(isComputerLevel(['--lang', 'zh', 'init', '--user'])).toBe(true);+ expect(isComputerLevel(['init'])).toBe(false);+ expect(isComputerLevel(['docs', 'init', '--user'])).toBe(false);+ });++ it('is docs global and its pages, whatever the options', () => {+ expect(isComputerLevel(['docs', 'global'])).toBe(true);+ expect(isComputerLevel(['--json', 'docs', 'global/problems'])).toBe(true);+ expect(isComputerLevel(['docs', '--depth', '2', 'global'])).toBe(true);+ expect(isComputerLevel(['docs', '--lang', 'zh', 'global/updates'])).toBe(+ true,+ );+ expect(isComputerLevel(['docs'])).toBe(false);+ expect(isComputerLevel(['docs', 'globals'])).toBe(false);+ expect(isComputerLevel(['docs', 'cli/global'])).toBe(false);+ expect(isComputerLevel(['search', 'global'])).toBe(false);+ });+});diff --git a/packages/cli/foundation/release/core-worker.mjs b/packages/cli/foundation/release/core-worker.mjsnew file mode 100644index 0000000000..05aede0038--- /dev/null+++ b/packages/cli/foundation/release/core-worker.mjs@@ -0,0 +1,38 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file The global copy's background step that installs its own release's+ * Core into the per-user cache (spec AST-081 FR3, FR6), as its own detached+ * process, so commands that read Core outside a project work offline after+ * one online run.+ *+ * Started by `maybeFetchCore` (global-state.mjs) with one argument, the+ * per-user cache folder. It installs this release (CLI and Core, as a+ * project's matched release is installed) through the release cache, which+ * takes the install lock, records a failure for its backoff, and forgets it+ * on success. It writes nothing to any stream and never reaches a person: it+ * is not a command and takes no options.+ *+ * @input argv[2]: the per-user cache folder+ * @output this release, Core included, in the release cache+ * @position foundation/release — one of the detached processes the CLI+ * starts, beside refresh-worker.mjs and agent-text-worker.mjs.+ */++import {fileURLToPath} from 'node:url';+import {ensureRelease} from './cache.mjs';+import {readJson} from './project.mjs';++const cacheDir = process.argv[2];+if (cacheDir) {+ try {+ const pkg = readJson(+ fileURLToPath(new URL('../../package.json', import.meta.url)),+ );+ if (typeof pkg?.version === 'string') {+ ensureRelease(pkg.version, {cacheDir});+ }+ } catch {+ // A cache that cannot be written is tried again by a later run.+ }+}diff --git a/packages/cli/foundation/release/global-state.mjs b/packages/cli/foundation/release/global-state.mjsnew file mode 100644index 0000000000..cd2ead2511--- /dev/null+++ b/packages/cli/foundation/release/global-state.mjs@@ -0,0 +1,472 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file The per-user update state, and the background check that keeps it+ * current (spec AST-081 FR6).+ *+ * The CLI never installs a newer release for the computer; it tells its user+ * one exists, the way `gh` and the Vercel CLI do (notices.mjs). At most once a+ * day, never in the first day after the first run, a run starts a detached+ * check of the release the registry tags `latest`; no run waits for it. No+ * check starts when the standard `CI` variable is set, or when+ * `NO_UPDATE_NOTIFIER` is (update-notice-env.mjs).+ *+ * <user config>/astryx/state.json+ * firstRunAt when a run first kept this state (no check before a day)+ * checkedAt when the last check started+ * checkOkAt when a check last reached the registry+ * latest the version `latest` named then+ * latestNode the Node range that release declares, or null+ * agentText the computer-level agent text: {writtenBy, attemptFor,+ * attemptAt}, the release that last wrote it and the last+ * background attempt (spec AST-081 FR8)+ * notifiedAt when each update notice last printed (notices.mjs)+ *+ * @input the clock, the registry's `latest` tag (in the worker)+ * @output the newest release known, for notices and doctor+ * @position foundation/release — read by the bin and doctor; the check runs+ * in refresh-worker.mjs.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {spawn} from 'node:child_process';+import {fileURLToPath} from 'node:url';+import {+ cachedRelease,+ isReleaseVersion,+ recentFailedInstall,+ releasesDir,+ resolveLatestRelease,+ tryLock,+} from './cache.mjs';+import {readJson} from './project.mjs';+import {userConfigDir} from '../env/user-dirs.mjs';+import {computerAgentTextSettings} from '../env/user-settings.mjs';+import {isCi, updateNoticesOff} from './update-notice-env.mjs';++/** How often a check may start: once a day, as `gh` and update-notifier do. */+export const CHECK_INTERVAL_MS = 24 * 60 * 60_000;++/**+ * @typedef {object} GlobalState+ * @property {number} [firstRunAt]+ * @property {number} [checkedAt]+ * @property {number} [checkOkAt]+ * @property {string} [latest]+ * @property {string | null} [latestNode]+ * @property {{at: number, reason: string}} [checkFailed] why the last check+ * did not reach the registry, for diagnosis only (`astryx doctor`); cleared+ * by a check that does. Not part of any contract.+ * @property {{writtenBy?: string, attemptFor?: string, attemptAt?: number}} [agentText]+ * @property {Record<string, number>} [notifiedAt] when each update notice+ * last printed (notices.mjs)+ * @property {Record<string, NoticeSkip>} [noticeSkips] why each update notice+ * last did not print, for diagnosis only: `astryx doctor` shows the newest.+ * Not part of any contract; its shape may change in any release.+ */++/**+ * Why an update notice did not print: `already-shown` (it printed within the+ * day) or `no-newer` (nothing newer is known). Recorded only while the run+ * holds the state file's lock.+ * @typedef {{reason: 'already-shown' | 'no-newer', at: number}} NoticeSkip+ */++/**+ * The state file.+ * @param {string} [stateDir] the per-user configuration folder+ * @returns {string}+ */+export function stateFile(stateDir = userConfigDir()) {+ return path.join(stateDir, 'state.json');+}++/**+ * The saved state; `{}` when there is none or it cannot be read.+ * @param {string} [stateDir]+ * @returns {GlobalState}+ */+export function readGlobalState(stateDir = userConfigDir()) {+ const state = readJson(stateFile(stateDir));+ return state && typeof state === 'object' && !Array.isArray(state)+ ? state+ : {};+}++/** How long a run waits for another run's change to the state file. */+const STATE_LOCK_WAIT_MS = 2000;++/** Sleep the thread without spinning. @param {number} ms */+function sleep(ms) {+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);+}++/**+ * Run `change` while holding the state file's lock, so runs that finish at+ * the same moment change the state one at a time: each reads what the one+ * before it wrote. Returns `change`'s result, or `undefined` when the lock+ * cannot be taken in time or the folder cannot be written, in which case+ * nothing changes.+ * @template T+ * @param {string} stateDir+ * @param {() => T} change+ * @returns {T | undefined}+ */+export function withStateLock(stateDir, change) {+ const outcome = tryStateLock(stateDir, change);+ return outcome.ran ? outcome.value : undefined;+}++/**+ * Who holds the state file's lock now, read from its owner record, for+ * diagnosis: null when it is free. `since` is when the lock folder was made.+ * @param {string} [stateDir]+ * @returns {{pid: number | null, host: string | null, since: number} | null}+ */+export function stateLockHolder(stateDir = userConfigDir()) {+ const lockDir = path.join(stateDir, '.lock-state');+ try {+ const since = fs.statSync(lockDir).mtimeMs;+ const owner = readJson(path.join(lockDir, 'owner.json'));+ return {+ pid: Number.isInteger(owner?.pid) ? owner.pid : null,+ host: typeof owner?.host === 'string' ? owner.host : null,+ since,+ };+ } catch {+ return null;+ }+}++/**+ * {@link withStateLock}, saying why `change` did not run: the lock stayed+ * taken past the wait (`lock-timeout`), or the folder cannot hold it+ * (`state-unwritable`).+ * @template T+ * @param {string} stateDir+ * @param {() => T} change+ * @returns {{ran: true, value: T} | {ran: false, reason: 'lock-timeout' | 'state-unwritable'}}+ */+export function tryStateLock(stateDir, change) {+ const lockDir = path.join(stateDir, '.lock-state');+ const deadline = Date.now() + STATE_LOCK_WAIT_MS;+ try {+ while (!tryLock(lockDir)) {+ if (Date.now() > deadline) return {ran: false, reason: 'lock-timeout'};+ sleep(10);+ }+ } catch {+ return {ran: false, reason: 'state-unwritable'};+ }+ try {+ return {ran: true, value: change()};+ } finally {+ fs.rmSync(lockDir, {recursive: true, force: true});+ }+}++/**+ * Write the whole state, atomically. Call only while holding the lock.+ * @param {GlobalState} state+ * @param {string} stateDir+ * @returns {boolean} whether it was written+ */+export function writeGlobalState(state, stateDir) {+ const file = stateFile(stateDir);+ try {+ const tmp = `${file}.${process.pid}.tmp`;+ fs.writeFileSync(tmp, `${JSON.stringify(state, null, 2)}\n`);+ fs.renameSync(tmp, file);+ return true;+ } catch {+ return false;+ }+}++/**+ * Merge `patch` into the saved state under the lock. An unwritable folder+ * never fails a run; the state is simply not kept.+ * @param {Partial<GlobalState>} patch+ * @param {string} [stateDir]+ * @returns {GlobalState}+ */+export function updateGlobalState(patch, stateDir = userConfigDir()) {+ try {+ fs.mkdirSync(stateDir, {recursive: true});+ } catch {+ // Unwritable: nothing is kept.+ }+ return (+ withStateLock(stateDir, () => {+ const next = {...readGlobalState(stateDir), ...patch};+ writeGlobalState(next, stateDir);+ return next;+ }) ?? {...readGlobalState(stateDir), ...patch}+ );+}++/**+ * The newest release the last check found, and the Node range it declares;+ * null when no check has reached the registry.+ * @param {string} [stateDir]+ * @returns {{version: string, node: string | null} | null}+ */+export function knownLatest(stateDir = userConfigDir()) {+ const state = readGlobalState(stateDir);+ if (typeof state.checkOkAt !== 'number' || !isReleaseVersion(state.latest)) {+ return null;+ }+ return {+ version: state.latest,+ node: typeof state.latestNode === 'string' ? state.latestNode : null,+ };+}++/**+ * The version of the newest release known, or null.+ * @param {string} [stateDir]+ * @returns {string | null}+ */+export function knownLatestRelease(stateDir = userConfigDir()) {+ return knownLatest(stateDir)?.version ?? null;+}++/**+ * Record the release that last wrote the computer-level agent text.+ * @param {string | null} version+ * @param {string} [stateDir]+ */+export function recordAgentTextWritten(version, stateDir = userConfigDir()) {+ if (!isReleaseVersion(version)) return;+ updateGlobalState({agentText: {writtenBy: version}}, stateDir);+}++/** A background attempt to write the agent text is retried after an hour. */+export const AGENT_TEXT_RETRY_MS = 60 * 60_000;++/**+ * The global copy keeps the computer-level agent text installed (spec+ * AST-081 FR8): when the person has not turned it off and the running global+ * version has not written it yet, as after the person upgraded the global+ * copy, that release's own background step writes it, detached, so no command+ * waits. Returns whether a step was started.+ *+ * @param {{+ * release: {version: string, root: string},+ * stateDir?: string,+ * configDir?: string,+ * now?: number,+ * start?: (worker: string, stateDir: string) => void,+ * }} options+ * @returns {boolean}+ */+export function maybeKeepAgentText({+ release,+ stateDir = userConfigDir(),+ configDir,+ now = Date.now(),+ start = startWorker,+}) {+ if (!computerAgentTextSettings(configDir).install) return false;+ const {agentText} = readGlobalState(stateDir);+ if (agentText?.writtenBy === release.version) return false;+ if (+ agentText?.attemptFor === release.version &&+ typeof agentText.attemptAt === 'number' &&+ now - agentText.attemptAt < AGENT_TEXT_RETRY_MS+ ) {+ return false;+ }+ const worker = path.join(+ release.root,+ 'foundation',+ 'release',+ 'agent-text-worker.mjs',+ );+ // A release without the step predates it; it never writes the text.+ if (!fs.existsSync(worker)) return false;+ updateGlobalState(+ {agentText: {...agentText, attemptFor: release.version, attemptAt: now}},+ stateDir,+ );+ // An attempt that cannot be recorded would start again on every run.+ if (readGlobalState(stateDir).agentText?.attemptAt !== now) return false;+ start(worker, stateDir);+ return true;+}++/**+ * Start the background step that installs this release's Core into the+ * per-user cache, so commands that read Core work offline outside a project+ * after one online run (spec AST-081 FR3, FR6): when the global copy carries+ * no Core beside it and none is cached for its release, no install of it is+ * under way, no recent attempt failed (the release cache's backoff), and+ * `CI` is not set. It never blocks a command, prints nothing, and a failure+ * is retried by a later run's step. Returns whether it was started.+ *+ * Never on Windows: a detached child there inherits the caller's open handles,+ * such as the pipes a tool or agent reads this run's output from, and the+ * caller would wait for the download to end. A component read on Windows+ * fetches the Core itself when it first needs it.+ * @param {{release: {version: string, root: string}, cacheDir: string, env?: NodeJS.ProcessEnv, start?: typeof startWorker, platform?: NodeJS.Platform}} options+ * @returns {boolean}+ */+export function maybeFetchCore({+ release,+ cacheDir,+ env = process.env,+ start = startWorker,+ platform = process.platform,+}) {+ if (isCi(env) || platform === 'win32') return false;+ if (!isReleaseVersion(release.version)) return false;+ const beside = readJson(+ path.join(release.root, '..', 'core', 'package.json'),+ );+ if (+ beside?.name === '@astryxdesign/core' &&+ beside.version === release.version+ ) {+ return false;+ }+ if (cachedRelease(release.version, cacheDir)) return false;+ if (recentFailedInstall(release.version, cacheDir)) return false;+ if (+ fs.existsSync(path.join(releasesDir(cacheDir), `.lock-${release.version}`))+ ) {+ return false;+ }+ const worker = path.join(+ release.root,+ 'foundation',+ 'release',+ 'core-worker.mjs',+ );+ // A release without the step predates it.+ if (!fs.existsSync(worker)) return false;+ start(worker, cacheDir);+ return true;+}++/**+ * Start the background check when one is due: never when the environment+ * turns update notices off (`CI`, `NO_UPDATE_NOTIFIER`), never in the first+ * day after the first run, and at most once a day. Returns whether a check+ * was started.+ *+ * @param {{+ * stateDir?: string,+ * now?: number,+ * env?: Record<string, string | undefined>,+ * start?: (worker: string, stateDir: string) => void,+ * }} [options]+ * @returns {boolean}+ */+export function maybeStartCheck(options = {}) {+ const {+ stateDir = userConfigDir(),+ now = Date.now(),+ env = process.env,+ start = startWorker,+ } = options;+ if (updateNoticesOff(env)) return false;+ const state = readGlobalState(stateDir);+ if (typeof state.firstRunAt !== 'number') {+ updateGlobalState({firstRunAt: now}, stateDir);+ return false;+ }+ const last = Math.max(state.firstRunAt, state.checkedAt ?? 0);+ if (now - last < CHECK_INTERVAL_MS) return false;+ updateGlobalState({checkedAt: now}, stateDir);+ // A start time that cannot be recorded would start a check on every run.+ if (readGlobalState(stateDir).checkedAt !== now) return false;+ start(+ fileURLToPath(new URL('./refresh-worker.mjs', import.meta.url)),+ stateDir,+ );+ return true;+}++/**+ * Why the last update check did not reach the registry, when it failed after+ * the last one that did; null otherwise. For diagnosis only.+ * @param {string} [stateDir]+ * @returns {{at: number, reason: string} | null}+ */+export function lastCheckFailure(stateDir = userConfigDir()) {+ const state = readGlobalState(stateDir);+ const failed = state.checkFailed;+ if (+ !failed ||+ typeof failed.at !== 'number' ||+ typeof failed.reason !== 'string'+ ) {+ return null;+ }+ return typeof state.checkOkAt === 'number' && state.checkOkAt > failed.at+ ? null+ : {at: failed.at, reason: failed.reason};+}++/**+ * Start a detached worker that outlives this run and reaches no stream.+ * @param {string} worker+ * @param {string} stateDir+ */+function startWorker(worker, stateDir) {+ try {+ const child = spawn(process.execPath, [worker, stateDir], {+ detached: true,+ stdio: 'ignore',+ windowsHide: true,+ });+ child.on('error', () => {});+ child.unref();+ } catch {+ // A check that cannot start is the same as a failed check.+ }+}++/**+ * The check itself: ask the registry for `latest` and save what it says. It+ * installs nothing. At most one check runs at a time.+ * @param {{stateDir?: string, resolve?: typeof resolveLatestRelease}} [options]+ * @returns {GlobalState}+ */+export function runCheck(options = {}) {+ const {stateDir = userConfigDir(), resolve = resolveLatestRelease} = options;+ const lockDir = path.join(stateDir, '.lock-check');+ try {+ if (!tryLock(lockDir)) return readGlobalState(stateDir);+ } catch {+ return readGlobalState(stateDir);+ }+ try {+ /** @type {string} */+ let reason = 'unknown';+ const latest = resolve({+ onFailure: why => {+ reason = why;+ },+ });+ if (!latest) {+ // Recorded so doctor can say why notices stopped (diagnosis only).+ return updateGlobalState(+ {checkFailed: {at: Date.now(), reason}},+ stateDir,+ );+ }+ return updateGlobalState(+ {+ latest: latest.version,+ latestNode: latest.node,+ checkOkAt: Date.now(),+ checkFailed: undefined,+ },+ stateDir,+ );+ } finally {+ fs.rmSync(lockDir, {recursive: true, force: true});+ }+}diff --git a/packages/cli/foundation/release/global-state.test.mjs b/packages/cli/foundation/release/global-state.test.mjsnew file mode 100644index 0000000000..bd4343beef--- /dev/null+++ b/packages/cli/foundation/release/global-state.test.mjs@@ -0,0 +1,381 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, it, expect, afterEach} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {spawnSync} from 'node:child_process';+import {fileURLToPath} from 'node:url';+import {+ AGENT_TEXT_RETRY_MS,+ CHECK_INTERVAL_MS,+ knownLatest,+ knownLatestRelease,+ lastCheckFailure,+ maybeFetchCore,+ maybeKeepAgentText,+ maybeStartCheck,+ readGlobalState,+ recordAgentTextWritten,+ runCheck,+ stateFile,+ updateGlobalState,+} from './global-state.mjs';+import {+ CLI_VERSION,+ cleanupFixtures,+ tempDir,+} from '../../test-utils/release-fixtures.mjs';+import {+ computerAgentTextSettings,+ recordComputerAgentTextSettings,+} from '../env/user-settings.mjs';+import {userConfigDir} from '../env/user-dirs.mjs';+import {renderComputerAgentText} from '../agent-docs/computer-agent-text.mjs';+import {isCi, updateNoticesOff} from './update-notice-env.mjs';++afterEach(cleanupFixtures);++describe('maybeStartCheck', () => {+ it('never checks in the first day, then at most once a day', () => {+ const stateDir = tempDir('state');+ /** @type {number[]} */+ const started = [];+ const start = () => started.push(1);+ const env = {};+ const t0 = 1_000_000;+ expect(CHECK_INTERVAL_MS).toBe(24 * 60 * 60_000);+ expect(maybeStartCheck({stateDir, env, now: t0, start})).toBe(false);+ expect(+ maybeStartCheck({stateDir, env, now: t0 + CHECK_INTERVAL_MS - 1, start}),+ ).toBe(false);+ expect(+ maybeStartCheck({stateDir, env, now: t0 + CHECK_INTERVAL_MS, start}),+ ).toBe(true);+ expect(+ maybeStartCheck({stateDir, env, now: t0 + CHECK_INTERVAL_MS + 10, start}),+ ).toBe(false);+ expect(+ maybeStartCheck({stateDir, env, now: t0 + 2 * CHECK_INTERVAL_MS, start}),+ ).toBe(true);+ expect(started).toHaveLength(2);+ expect(stateFile(stateDir)).toBe(path.join(stateDir, 'state.json'));+ });++ it.each([+ [{CI: 'true'}],+ [{CI: '1'}],+ [{NO_UPDATE_NOTIFIER: ''}],+ [{NO_UPDATE_NOTIFIER: '1'}],+ ])('never checks, nor writes state, with %o', env => {+ const stateDir = tempDir('state');+ updateGlobalState({firstRunAt: 0}, stateDir);+ const start = () => {+ throw new Error('started');+ };+ expect(+ maybeStartCheck({stateDir, env, now: 10 * CHECK_INTERVAL_MS, start}),+ ).toBe(false);+ expect(readGlobalState(stateDir)).toEqual({firstRunAt: 0});+ });++ it('starts nothing when its start time cannot be recorded', () => {+ const stateDir = path.join(tempDir('state'), 'file');+ fs.writeFileSync(stateDir, '');+ const start = () => {+ throw new Error('started');+ };+ expect(maybeStartCheck({stateDir, env: {}, now: 1, start})).toBe(false);+ expect(maybeStartCheck({stateDir, env: {}, now: 1e12, start})).toBe(false);+ });+});++describe('update-notice-env', () => {+ it('reads CI the usual way, and NO_UPDATE_NOTIFIER as set or not', () => {+ for (const value of ['true', '1', 'yes', 'github']) {+ expect(isCi({CI: value})).toBe(true);+ }+ for (const value of [undefined, '', '0', 'false', 'FALSE']) {+ expect(isCi({CI: value})).toBe(false);+ }+ expect(updateNoticesOff({})).toBe(false);+ expect(updateNoticesOff({NO_UPDATE_NOTIFIER: ''})).toBe(true);+ });+});++describe('runCheck', () => {+ it('records the newest release and its Node range, and installs nothing', () => {+ const stateDir = tempDir('state');+ const state = runCheck({+ stateDir,+ resolve: () => ({version: '0.7.3', node: '>=24'}),+ });+ expect(state).toMatchObject({latest: '0.7.3', latestNode: '>=24'});+ expect(typeof state.checkOkAt).toBe('number');+ expect(knownLatest(stateDir)).toEqual({version: '0.7.3', node: '>=24'});+ expect(knownLatestRelease(stateDir)).toBe('0.7.3');+ expect(fs.readdirSync(stateDir).sort()).toEqual(['state.json']);+ });++ it('records why when the registry cannot be reached, and a later check that reaches it clears that', () => {+ const stateDir = tempDir('state');+ updateGlobalState({firstRunAt: 1}, stateDir);+ const failed = runCheck({+ stateDir,+ resolve: ({onFailure} = {}) => {+ onFailure?.('npm-failed: ECONNREFUSED');+ return null;+ },+ });+ expect(failed).toEqual({+ firstRunAt: 1,+ checkFailed: {at: expect.any(Number), reason: 'npm-failed: ECONNREFUSED'},+ });+ expect(knownLatest(stateDir)).toBeNull();+ expect(lastCheckFailure(stateDir)).toEqual({+ at: failed.checkFailed?.at,+ reason: 'npm-failed: ECONNREFUSED',+ });+ runCheck({stateDir, resolve: () => ({version: '0.7.3', node: null})});+ expect(readGlobalState(stateDir).checkFailed).toBeUndefined();+ expect(lastCheckFailure(stateDir)).toBeNull();+ });++ it('keeps the state in the per-user configuration folder', () => {+ expect(path.dirname(stateFile())).toBe(userConfigDir());+ });+});++describe('maybeFetchCore', () => {+ /** A release folder with the step, and no Core beside it. */+ const release = () => {+ const parent = tempDir('scope');+ const root = path.join(parent, 'cli');+ fs.mkdirSync(path.join(root, 'foundation', 'release'), {recursive: true});+ fs.writeFileSync(+ path.join(root, 'foundation', 'release', 'core-worker.mjs'),+ '',+ );+ return {version: '0.8.0', root};+ };++ it("starts the step that installs this release's Core when none is beside it or cached, never in CI", () => {+ /** @type {string[]} */+ const started = [];+ const start = (/** @type {string} */ worker) => started.push(worker);+ const r = release();+ const cacheDir = tempDir('cache');+ expect(+ maybeFetchCore({release: r, cacheDir, env: {CI: 'true'}, start}),+ ).toBe(false);+ expect(+ maybeFetchCore({release: r, cacheDir, env: {}, start, platform: 'linux'}),+ ).toBe(true);+ expect(started).toEqual([+ path.join(r.root, 'foundation', 'release', 'core-worker.mjs'),+ ]);+ // A Core beside the CLI, as a door's package set carries: nothing to do.+ const beside = path.join(path.dirname(r.root), 'core', 'package.json');+ fs.mkdirSync(path.dirname(beside), {recursive: true});+ fs.writeFileSync(+ beside,+ JSON.stringify({name: '@astryxdesign/core', version: '0.8.0'}),+ );+ expect(+ maybeFetchCore({release: r, cacheDir, env: {}, start, platform: 'linux'}),+ ).toBe(false);+ });++ it('never starts on Windows, where the caller would wait on inherited pipes', () => {+ const start = () => {};+ const r = release();+ const cacheDir = tempDir('cache');+ const base = {+ release: r,+ cacheDir,+ env: {},+ start,+ platform: /** @type {const} */ ('win32'),+ };+ expect(maybeFetchCore(base)).toBe(false);+ expect(maybeFetchCore({...base, platform: 'linux'})).toBe(true);+ expect(maybeFetchCore({...base, platform: 'darwin'})).toBe(true);+ });++ it('waits out a recent failure and an install under way', () => {+ const start = () => {};+ const r = release();+ const cacheDir = tempDir('cache');+ const releases = path.join(cacheDir, 'releases');+ fs.mkdirSync(path.join(releases, '.lock-0.8.0'), {recursive: true});+ expect(+ maybeFetchCore({release: r, cacheDir, env: {}, start, platform: 'linux'}),+ ).toBe(false);+ fs.rmSync(path.join(releases, '.lock-0.8.0'), {recursive: true});+ fs.writeFileSync(+ path.join(releases, '.failed-0.8.0.json'),+ JSON.stringify({at: Date.now(), reason: 'offline', failures: 1}),+ );+ expect(+ maybeFetchCore({release: r, cacheDir, env: {}, start, platform: 'linux'}),+ ).toBe(false);+ fs.writeFileSync(+ path.join(releases, '.failed-0.8.0.json'),+ JSON.stringify({+ at: Date.now() - 3 * 60_000,+ reason: 'offline',+ failures: 1,+ }),+ );+ expect(+ maybeFetchCore({release: r, cacheDir, env: {}, start, platform: 'linux'}),+ ).toBe(true);+ });+});++describe('maybeKeepAgentText', () => {+ /** @param {string} stateDir */+ const setup = stateDir => {+ const root = tempDir('cli');+ fs.mkdirSync(path.join(root, 'foundation', 'release'), {recursive: true});+ fs.writeFileSync(+ path.join(root, 'foundation', 'release', 'agent-text-worker.mjs'),+ '',+ );+ return {release: {version: '0.8.0', root}, stateDir};+ };++ it("starts the answering release's step once per release, retrying after an hour", () => {+ const stateDir = tempDir('state');+ const configDir = tempDir('config');+ /** @type {string[]} */+ const started = [];+ const start = (/** @type {string} */ worker) => started.push(worker);+ const base = {...setup(stateDir), configDir, start};+ expect(maybeKeepAgentText({...base, now: 1000})).toBe(true);+ expect(started[0]).toBe(+ path.join(+ base.release.root,+ 'foundation',+ 'release',+ 'agent-text-worker.mjs',+ ),+ );+ expect(maybeKeepAgentText({...base, now: 2000})).toBe(false);+ expect(maybeKeepAgentText({...base, now: 1000 + AGENT_TEXT_RETRY_MS})).toBe(+ true,+ );+ recordAgentTextWritten('0.8.0', stateDir);+ expect(+ maybeKeepAgentText({...base, now: 1000 + 3 * AGENT_TEXT_RETRY_MS}),+ ).toBe(false);+ // A switch to another release writes its text again.+ expect(+ maybeKeepAgentText({+ ...base,+ release: {...base.release, version: '0.8.1'},+ now: 1000 + 3 * AGENT_TEXT_RETRY_MS,+ }),+ ).toBe(true);+ expect(started).toHaveLength(3);+ });++ it('starts nothing after the person turned the text off, or for a release without the step', () => {+ const stateDir = tempDir('state');+ const configDir = tempDir('config');+ const start = () => {+ throw new Error('started');+ };+ recordComputerAgentTextSettings({install: false, links: []}, configDir);+ expect(maybeKeepAgentText({...setup(stateDir), configDir, start})).toBe(+ false,+ );+ const other = tempDir('config');+ expect(+ maybeKeepAgentText({+ release: {version: '0.7.0', root: tempDir('old')},+ stateDir,+ configDir: other,+ start,+ }),+ ).toBe(false);+ });++ it('starts nothing when the attempt cannot be recorded', () => {+ const stateDir = path.join(tempDir('state'), 'file');+ fs.writeFileSync(stateDir, '');+ const start = () => {+ throw new Error('started');+ };+ expect(+ maybeKeepAgentText({+ ...setup(stateDir),+ configDir: tempDir('config'),+ start,+ }),+ ).toBe(false);+ });+});++describe('agent-text-worker.mjs', () => {+ it('writes the file with this release, links it, records both, and keeps an edited file', () => {+ const home = tempDir('home');+ const stateDir = path.join(home, '.config', 'astryx');+ const env = {+ ...process.env,+ HOME: home,+ USERPROFILE: home,+ XDG_CONFIG_HOME: path.join(home, '.config'),+ APPDATA: path.join(home, 'AppData', 'Roaming'),+ };+ const configDir = userConfigDir({home, env});+ const worker = fileURLToPath(+ new URL('./agent-text-worker.mjs', import.meta.url),+ );+ const run = () =>+ spawnSync(process.execPath, [worker, stateDir], {env, encoding: 'utf8'});+ const first = run();+ expect(first.status).toBe(0);+ expect(first.stdout + first.stderr).toBe('');+ const file = path.join(home, '.agents', 'skills', 'astryx', 'SKILL.md');+ const claude = path.join(home, '.claude', 'skills', 'astryx');+ expect(fs.readFileSync(file, 'utf8')).toBe(+ renderComputerAgentText({command: 'astryx'}),+ );+ expect(fs.lstatSync(claude).isSymbolicLink()).toBe(true);+ expect(computerAgentTextSettings(configDir)).toEqual({+ install: true,+ links: [claude],+ });+ expect(readGlobalState(stateDir).agentText).toEqual({+ writtenBy: CLI_VERSION,+ });+ fs.appendFileSync(file, 'mine\n');+ expect(run().status).toBe(0);+ expect(fs.readFileSync(file, 'utf8')).toMatch(/mine\n$/u);+ });++ it('writes nothing when the text is turned off', () => {+ const home = tempDir('home');+ const env = {+ ...process.env,+ HOME: home,+ USERPROFILE: home,+ XDG_CONFIG_HOME: path.join(home, '.config'),+ };+ recordComputerAgentTextSettings(+ {install: false, links: []},+ userConfigDir({home, env}),+ );+ const worker = fileURLToPath(+ new URL('./agent-text-worker.mjs', import.meta.url),+ );+ expect(+ spawnSync(+ process.execPath,+ [worker, path.join(home, '.config', 'astryx')],+ {env},+ ).status,+ ).toBe(0);+ expect(fs.existsSync(path.join(home, '.agents'))).toBe(false);+ });+});diff --git a/packages/cli/foundation/release/handoff.e2e.test.mjs b/packages/cli/foundation/release/handoff.e2e.test.mjsnew file mode 100644index 0000000000..c479e87435--- /dev/null+++ b/packages/cli/foundation/release/handoff.e2e.test.mjs@@ -0,0 +1,278 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file The hand-off through the real bin: a run started in this copy, in a+ * project whose release is another one, is answered by that release with the+ * same arguments, folder, standard streams, and exit status, and one line on+ * standard error in text mode (spec AST-081 FR2, FR9).+ */++import {describe, it, expect, afterEach} from 'vitest';+import {spawnSync} from 'node:child_process';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {fileURLToPath} from 'node:url';+import {+ CLI_VERSION,+ cleanupFixtures,+ installCore,+ linkThisCliAsProjectCli,+ installStandInCli,+ project,+ seedRelease,+ tempDir,+ writeJson,+} from '../../test-utils/release-fixtures.mjs';++const BIN = fileURLToPath(+ new URL('../../clients/cli/bin/astryx.mjs', import.meta.url),+);+const SELF_VERSION = JSON.parse(+ fs.readFileSync(+ fileURLToPath(new URL('../../package.json', import.meta.url)),+ 'utf-8',+ ),+).version;++afterEach(cleanupFixtures);++/**+ * Run this copy's bin in `cwd` with a private home and cache.+ * @param {string} cwd+ * @param {string[]} args+ * @param {{input?: string, cache?: string, home?: string, env?: Record<string, string>}} [options]+ */+function run(cwd, args, options = {}) {+ const home = options.home ?? tempDir('home');+ const cache = options.cache ?? tempDir('cache');+ const result = spawnSync(process.execPath, [BIN, ...args], {+ cwd,+ encoding: 'utf-8',+ input: options.input ?? '',+ env: {+ // Not the package manager running the tests: its npm_* settings would+ // name it as the project's package manager. Nor the test runner's CI+ // or NO_UPDATE_NOTIFIER, which turn update notices off.+ ...Object.fromEntries(+ Object.entries(process.env).filter(+ ([key]) => !/^(?:npm_|CI$|NO_UPDATE_NOTIFIER$)/iu.test(key),+ ),+ ),+ HOME: home,+ USERPROFILE: home,+ XDG_CACHE_HOME: cache,+ LOCALAPPDATA: cache,+ XDG_CONFIG_HOME: path.join(home, '.config'),+ APPDATA: path.join(home, 'AppData', 'Roaming'),+ NO_COLOR: '1',+ ...options.env,+ },+ timeout: 60_000,+ });+ return {+ status: result.status,+ stdout: result.stdout,+ stderr: result.stderr,+ /** The stand-in's report, when a stand-in answered. */+ report: () => JSON.parse(result.stdout.trim().split('\n').pop() ?? 'null'),+ };+}++describe('hand-off to the project CLI', () => {+ it('passes argv, folder, stdin and the exit status, with one stderr line', () => {+ const root = project(tempDir(), {'@astryxdesign/core': '0.6.8'});+ installCore(root, '0.6.8');+ installStandInCli(root, '0.6.8');+ const src = path.join(root, 'src');+ fs.mkdirSync(src);+ const result = run(src, ['component', 'Button', '--exit', '7'], {+ input: 'piped',+ });+ expect(result.status).toBe(7);+ expect(result.report()).toEqual({+ version: '0.6.8',+ args: ['component', 'Button', '--exit', '7'],+ cwd: src,+ stdin: 'piped',+ });+ const lines = result.stderr.trim().split('\n');+ expect(lines).toEqual([+ `astryx: answered by this project's CLI 0.6.8, handed over from CLI ${SELF_VERSION}`,+ 'stand-in 0.6.8',+ ]);+ });++ it('prints no line with --json', () => {+ const root = project(tempDir(), {'@astryxdesign/core': '0.6.8'});+ installCore(root, '0.6.8');+ installStandInCli(root, '0.6.8');+ const result = run(root, ['docs', '--json']);+ expect(result.status).toBe(0);+ expect(result.stderr.trim()).toBe('stand-in 0.6.8');+ });++ it("a project CLI that cannot start: the release matching the project's Core answers; offline, this copy, with the warning", () => {+ const root = project(tempDir(), {'@astryxdesign/core': '0.6.8'});+ installCore(root, '0.6.8');+ installStandInCli(root, '0.6.8', {bin: false});+ const offline = {npm_config_registry: 'http://127.0.0.1:9'};+ const json = run(root, ['docs', '--json'], {env: offline});+ expect(json.status).toBe(0);+ expect(JSON.parse(json.stdout).meta.answeredBy.copy).toBe('fallback');+ const text = run(root, ['--version'], {env: offline});+ expect(text.status).toBe(0);+ expect(text.stdout.trim()).toBe(SELF_VERSION);+ expect(text.stderr).toMatch(+ /astryx: could not get Astryx 0\.6\.8 to match this project's Core/u,+ );+ });+});++describe('hand-off to the matched release', () => {+ it("runs the project's own CLI even when its version differs from the project's Core", () => {+ const cache = tempDir('cache');+ seedRelease(path.join(cache, 'astryx'), '0.7.0');+ const root = project(tempDir(), {'@astryxdesign/core': '0.7.0'});+ installCore(root, '0.7.0');+ installStandInCli(root, '0.6.8');+ const result = run(root, ['upgrade', '--from', '0.6.8'], {cache});+ expect(result.status).toBe(0);+ expect(result.report()).toMatchObject({+ version: '0.6.8',+ args: ['upgrade', '--from', '0.6.8'],+ });+ });++ it("runs the cached release equal to the project's Core when the project's own CLI cannot start", () => {+ const cache = tempDir('cache');+ seedRelease(path.join(cache, 'astryx'), '0.7.0');+ const root = project(tempDir(), {'@astryxdesign/core': '0.7.0'});+ installCore(root, '0.7.0');+ installStandInCli(root, '0.6.8', {bin: false});+ const result = run(root, ['upgrade', '--from', '0.6.8'], {cache});+ expect(result.status).toBe(0);+ expect(result.report()).toMatchObject({+ version: '0.7.0',+ args: ['upgrade', '--from', '0.6.8'],+ });+ expect(result.stderr.trim().split('\n')).toEqual([+ "astryx: answered by CLI 0.7.0 with Core 0.7.0, the release that matches this project's Core",+ 'stand-in 0.7.0',+ ]);+ });++ it('answers a Core-only project itself, as released, with no line and no install', () => {+ const cache = tempDir('cache');+ const root = project(tempDir(), {'@astryxdesign/core': '0.7.0'});+ installCore(root, '0.7.0');+ const result = run(root, ['docs', '--json'], {cache});+ expect(result.status).toBe(0);+ expect(JSON.parse(result.stdout).meta.answeredBy).toEqual({+ cli: SELF_VERSION,+ core: '0.7.0',+ copy: 'starting',+ });+ expect(fs.existsSync(path.join(cache, 'astryx', 'releases', '0.7.0'))).toBe(+ false,+ );+ });+});++describe('answering itself', () => {+ it('outside a project: one line in text mode, answeredBy in JSON', () => {+ const empty = tempDir('empty');+ const text = run(empty, ['--version']);+ expect(text.stdout.trim()).toBe(SELF_VERSION);+ expect(text.stderr.trim()).toBe(+ `astryx: answered by CLI ${SELF_VERSION} with Core ${SELF_VERSION}, outside a project`,+ );+ const json = run(empty, ['docs', '--json']);+ expect(json.stderr).toBe('');+ expect(JSON.parse(json.stdout).meta.answeredBy).toEqual({+ cli: SELF_VERSION,+ core: SELF_VERSION,+ copy: 'carried',+ });+ });+});++describe('answeredBy on every successful JSON result', () => {+ it('covers the manifest, the version, and help', () => {+ const empty = tempDir('empty');+ for (const args of [+ ['manifest', '--json'],+ ['--json'],+ ['--version', '--json'],+ ['component', '--help', '--json'],+ ]) {+ const result = run(empty, args);+ expect(result.status, args.join(' ')).toBe(0);+ expect(+ JSON.parse(result.stdout).meta?.answeredBy,+ args.join(' '),+ ).toEqual({+ cli: SELF_VERSION,+ core: SELF_VERSION,+ copy: 'carried',+ });+ }+ });+});++describe('computer-level commands are never handed to a project', () => {+ it('answers init --user itself inside a project whose CLI is another release', () => {+ const root = project(tempDir(), {'@astryxdesign/core': '0.6.8'});+ installCore(root, '0.6.8');+ installStandInCli(root, '0.6.8');+ for (const args of [+ ['init', '--user'],+ ['--json', 'init', '--user', '--remove-agents'],+ ]) {+ const result = run(root, args);+ expect(result.status, result.stderr).toBe(0);+ expect(result.stdout).not.toContain('"version":"0.6.8"');+ expect(result.stderr).not.toContain('stand-in');+ }+ const text = run(root, ['init', '--user']);+ expect(text.stderr.split('\n')[0]).toBe(+ `astryx: answered by CLI ${SELF_VERSION} with Core ${SELF_VERSION}, for this computer`,+ );+ });+});++describe('update notices through the real bin (FR10)', () => {+ it('prints the project notice after the command, once a day, never with --json, in CI, or with NO_UPDATE_NOTIFIER', () => {+ const [major, minor, patch] = CLI_VERSION.split(/[.-]/u).map(Number);+ const newest = `${major}.${minor}.${patch + 1}`;+ const root = project(tempDir(), {+ '@astryxdesign/core': CLI_VERSION,+ '@astryxdesign/cli': CLI_VERSION,+ });+ installCore(root, CLI_VERSION);+ linkThisCliAsProjectCli(root);+ writeJson(path.join(root, 'package-lock.json'), {lockfileVersion: 3});+ const cache = tempDir('cache');+ const home = tempDir('home');+ writeJson(path.join(home, '.config', 'astryx', 'state.json'), {+ latest: newest,+ checkOkAt: 1,+ });+ const notice = [+ `A new release of Astryx is available: ${CLI_VERSION} → ${newest}`,+ `To upgrade, run: npm install @astryxdesign/core@${newest} @astryxdesign/cli@${newest}, then npx astryx upgrade --from ${CLI_VERSION} --apply`,+ ];+ for (const env of [{CI: 'true'}, {NO_UPDATE_NOTIFIER: '1'}]) {+ const off = run(root, ['--version'], {cache, home, env});+ expect(off.stderr).not.toContain('A new release');+ }+ const json = run(root, ['--version', '--json'], {cache, home});+ expect(json.status).toBe(0);+ expect(json.stderr).not.toContain('A new release');+ const first = run(root, ['--version'], {cache, home});+ expect(first.status).toBe(0);+ expect(first.stdout.trim()).toBe(CLI_VERSION);+ expect(first.stderr.trim().split('\n').slice(-2)).toEqual(notice);+ const second = run(root, ['--version'], {cache, home});+ expect(second.stderr).not.toContain('A new release');+ });+});diff --git a/packages/cli/foundation/release/handoff.mjs b/packages/cli/foundation/release/handoff.mjsnew file mode 100644index 0000000000..d4c975a45e--- /dev/null+++ b/packages/cli/foundation/release/handoff.mjs@@ -0,0 +1,357 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file The first thing every run does: choose the release that answers and,+ * when it is not this copy, hand the run to it (spec AST-081 FR2, FR6, FR9).+ *+ * Runs in the bin right after the Node version gate, before the CLI loads+ * the folder's `astryx.config`, its integrations, or its Core. A hand-off+ * starts the chosen CLI with exactly this run's arguments, working folder, and+ * standard streams, adds nothing to its environment, options, or+ * configuration, and ends this process with that CLI's exit status. The+ * chosen copy makes the same choice and finds itself, so a run is handed off+ * at most once.+ *+ * In text mode a run that a copy other than the project's own CLI answers+ * prints one line on standard error naming the CLI and Core that answered; a+ * run with `--json` prints none and carries `meta.answeredBy` instead. After a+ * successful command, the copy that started the run prints any update notice+ * (notices.mjs); a global copy also starts the daily update check, which+ * installs nothing (global-state.mjs).+ *+ * @input the running copy, argv, the working folder+ * @output returns when this copy answers; otherwise never returns+ * @position foundation/release — called once by clients/cli/bin/astryx.mjs.+ */++import {spawn} from 'node:child_process';+import {writeSync} from 'node:fs';+import {+ chooseRelease,+ isComputerLevel,+ isGlobalCopy,+ namesWhoAnswered,+ packageRootOf,+ runningCopy,+} from './choose.mjs';+import {ensureRelease, userCacheDir} from './cache.mjs';+import {+ maybeFetchCore,+ maybeKeepAgentText,+ maybeStartCheck,+} from './global-state.mjs';+import {recordRunChoice} from './run-context.mjs';+import {noticeLines} from './notices.mjs';+import {cliDoor, runWithCliDoor} from '../env/cli-command.mjs';++/** Where each release's notes are published. */++/**+ * The who-answered line for a run a copy other than the project's own CLI+ * answers.+ * @param {import('./choose.mjs').ReleaseChoice} choice+ * @param {boolean} [computer] the command acts on the computer, not the folder+ * @returns {string}+ */+export function whoAnsweredLine(choice, computer = false) {+ const core = choice.coreVersion ?? choice.version;+ if (computer) {+ return `astryx: answered by CLI ${choice.version} with Core ${core}, for this computer`;+ }+ return choice.copy === 'matched'+ ? `astryx: answered by CLI ${choice.version} with Core ${core}, the release that matches this project's Core`+ : `astryx: answered by CLI ${choice.version} with Core ${core}, outside a project`;+}++/**+ * The line for a run handed to the project's own CLI.+ * @param {string} projectVersion+ * @param {string} startedIn the version of the copy the run started in+ * @returns {string}+ */+export function handedToProjectLine(projectVersion, startedIn) {+ return `astryx: answered by this project's CLI ${projectVersion}, handed over from CLI ${startedIn}`;+}++/**+ * One line on standard error while a release installs, so a slow download+ * never looks like a hang. Text mode only.+ * @param {'install' | 'wait'} event+ * @param {string} version+ */+export function progressLine(event, version) {+ console.error(progressText(event, version));+}++/**+ * The text of {@link progressLine}.+ * @param {'install' | 'wait'} event+ * @param {string} version+ * @returns {string}+ */+export function progressText(event, version) {+ return event === 'install'+ ? `astryx: installing CLI release ${version} into the per-user cache (once)...`+ : `astryx: waiting for another run to finish installing CLI release ${version}...`;+}++/**+ * The warning a run prints, in text mode, when the release that matches the+ * project's Core cannot be obtained and the copy that answered before global+ * mode answers instead (spec AST-081 FR2).+ * @param {string} wanted the matched release, or the range it was read from+ * @param {string} reason why it cannot be obtained+ * @param {string} answering the version that answers instead+ * @returns {string}+ */+export function fallbackLine(wanted, reason, answering) {+ return `astryx: could not get Astryx ${wanted} to match this project's Core (${reason}); answering with CLI ${answering} instead`;+}++/**+ * Fail the run before any command starts, in the shape every command fails+ * in: the JSON error envelope on stdout with `--json`, else `Error: …` on+ * standard error. Exit status 1.+ * @param {string} message+ * @param {boolean} json+ * @returns {never}+ */+function failUnavailable(message, json) {+ if (json) {+ process.stdout.write(+ `${JSON.stringify(+ {apiVersion: 1, error: message, code: 'ERR_VERSIONS_UNAVAILABLE'},+ null,+ 2,+ )}\n`,+ );+ } else {+ console.error(`Error: ${message}`);+ }+ process.exit(1);+}++/**+ * Choose who answers and hand off when it is not this copy.+ * @param {{cliRoot: string, argv: string[]}} input argv after `node astryx`+ * @returns {Promise<void>} resolves when this copy answers+ */+export async function startRun({cliRoot, argv}) {+ const json = argv.includes('--json');+ const self = runningCopy(cliRoot);+ const cacheDir = userCacheDir();+ const global = isGlobalCopy(cliRoot, cacheDir);+ if (global) {+ try {+ maybeStartCheck();+ } catch {+ // A check that cannot start never fails a run.+ }+ try {+ // The global copy keeps the computer-level agent text on its own+ // release's text, so it follows each upgrade of the copy (FR8).+ maybeKeepAgentText({release: self});+ } catch {+ // Nor does the agent text.+ }+ // And its own Core, so component reads work offline outside a project+ // after one online run (FR3). Started as the run ends, so it never takes+ // the install lock from this run's own Core read, nor holds anything the+ // command's caller waits on while the command runs.+ process.once('exit', () => {+ try {+ maybeFetchCore({release: self, cacheDir});+ } catch {+ // Nor does the Core download.+ }+ });+ }++ const computer = isComputerLevel(argv);+ /** @type {import('./choose.mjs').ReleaseChoice} */+ let choice;+ try {+ choice = chooseRelease({+ cwd: process.cwd(),+ self,+ cacheDir,+ computer,+ });+ } catch {+ choice = {+ copy: 'carried',+ answer: 'self',+ version: self.version,+ bin: null,+ coreVersion: null,+ inProject: false,+ unavailable: null,+ };+ }++ if (choice.unavailable && choice.copy === 'project') {+ failUnavailable(+ `This project's CLI ${choice.version} could not be started: ${choice.unavailable}. Reinstall the project's dependencies.`,+ json,+ );+ }++ // A host's door holds only inside the call that set it; notices print as+ // the process exits, outside it, so the door this run started under is+ // kept and set again for them (FR5).+ const door = cliDoor();+ /** FR10: after a successful command, at most once a day per notice. */+ const notify = () => {+ const print = () => {+ for (const line of noticeLines({+ cwd: process.cwd(),+ self,+ choice: computer ? {...choice, inProject: false} : choice,+ json,+ cacheDir,+ })) {+ // Synchronous: the process is exiting.+ writeSync(2, `${line}\n`);+ }+ };+ try {+ if (door) runWithCliDoor(door, print);+ else print();+ } catch {+ // A notice never fails a run.+ }+ };+ /**+ * The matched release cannot be obtained: the copy that started the run+ * answers instead, as before global mode, announced (FR2).+ * @param {string} reason+ * @returns {Promise<void>}+ */+ const fallBack = async reason => {+ recordRunChoice({+ ...choice,+ copy: 'fallback',+ answer: 'self',+ version: self.version,+ bin: null,+ coreVersion: null,+ unavailable: null,+ });+ if (!json) {+ console.error(fallbackLine(choice.version, reason, self.version));+ }+ process.once('exit', code => {+ if (code === 0) notify();+ });+ };++ if (choice.unavailable) {+ await fallBack(choice.unavailable);+ return;+ }++ if (choice.answer === 'self') {+ recordRunChoice(choice);+ // A project with no CLI of its own is answered as released, with no+ // line; a hint after the command, once a day, says how to match it.+ if (!json && (choice.copy === 'matched' || choice.copy === 'carried'))+ console.error(whoAnsweredLine(choice, computer));+ process.once('exit', code => {+ if (code === 0) notify();+ });+ return;+ }++ let bin = choice.bin;+ if (!bin) {+ const release = ensureRelease(choice.version, {+ cacheDir,+ onProgress: json ? undefined : progressLine,+ });+ if (!('bin' in release)) {+ await fallBack(release.reason);+ return;+ }+ bin = release.bin;+ }++ if (!json) {+ if (choice.copy === 'project') {+ console.error(handedToProjectLine(choice.version, self.version));+ } else if (!namesWhoAnswered(packageRootOf(bin))) {+ console.error(whoAnsweredLine(choice, computer));+ }+ }++ await handOff(bin, argv, choice, json, notify);+}++/**+ * How long a hand-off waits after an interrupt before passing it on to a CLI+ * that is still running. An interrupt sent to the whole process group (a+ * terminal's Ctrl-C, a process manager) already reached that CLI, and one that+ * stops within this time is never interrupted twice; one sent to this process+ * alone (an agent's `kill('SIGINT')`) stops the run once it is passed on.+ */+export const INTERRUPT_GRACE_MS = 5000;++/**+ * Run `bin` as this run and end with its exit status.+ * @param {string} bin+ * @param {string[]} argv+ * @param {import('./choose.mjs').ReleaseChoice} choice+ * @param {boolean} json+ * @param {() => void} [notify] prints update notices after a successful run+ * @returns {Promise<never>}+ */+function handOff(bin, argv, choice, json, notify = () => {}) {+ return new Promise(() => {+ const child = spawn(process.execPath, [bin, ...argv], {+ stdio: 'inherit',+ windowsHide: false,+ });+ /** @param {NodeJS.Signals} signal */+ const forward = signal => {+ try {+ child.kill(signal);+ } catch {+ // The child is already gone.+ }+ };+ const running = () => child.exitCode === null && child.signalCode === null;+ // An interrupt is passed on only to a CLI still running after the grace+ // (see INTERRUPT_GRACE_MS): one sent to this process alone then stops the+ // run, and one the whole process group got is not delivered twice to a CLI+ // that stops in time. On Windows, Ctrl-C reaches every process in the+ // console and a forwarded SIGINT would end the child abruptly, so this+ // process only outlives it.+ const onInterrupt = () => {+ if (process.platform === 'win32' || !running()) return;+ setTimeout(() => {+ if (running()) forward('SIGINT');+ }, INTERRUPT_GRACE_MS).unref();+ };+ process.on('SIGINT', onInterrupt);+ process.on('SIGTERM', forward);+ process.on('SIGHUP', forward);+ child.on('error', error => {+ failUnavailable(+ choice.copy === 'project'+ ? `This project's CLI ${choice.version} could not be started: ${error.message}. Reinstall the project's dependencies.`+ : `CLI release ${choice.version} could not be started: ${error.message}.`,+ json,+ );+ });+ child.on('exit', (code, signal) => {+ process.off('SIGINT', onInterrupt);+ process.off('SIGTERM', forward);+ process.off('SIGHUP', forward);+ if (signal) {+ process.kill(process.pid, signal);+ return;+ }+ if (code === 0) notify();+ process.exit(code ?? 1);+ });+ });+}diff --git a/packages/cli/foundation/release/lock-lease.mjs b/packages/cli/foundation/release/lock-lease.mjsnew file mode 100644index 0000000000..df7352d170--- /dev/null+++ b/packages/cli/foundation/release/lock-lease.mjs@@ -0,0 +1,80 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file The lease on a release install's lock in the per-user cache (spec+ * AST-081 FR11).+ *+ * A lock folder records its holder in `owner.json`: the process id and the+ * computer's name. On the same computer a waiting run checks whether that+ * process still runs. A cache shared between computers cannot check another+ * computer's processes, so the holder renews its record every+ * `LEASE_RENEW_MS` while the package manager works, and a waiting run takes+ * a lock from another computer over once it has seen the record go unrenewed+ * for `LEASE_SILENCE_MS`. The waiting run judges by change it observes, never+ * by comparing clocks, so computers whose clocks differ agree.+ *+ * @input the lock folder+ * @output the renewed record, and whether a foreign record has gone silent+ * @position foundation/release — renewed by npm-guard.mjs, read by cache.mjs.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';++/** How often the holder renews its record while the package manager works. */+export const LEASE_RENEW_MS = 10_000;++/** How long a record from another computer may go unrenewed, as observed. */+export const LEASE_SILENCE_MS = 60_000;++/**+ * Renew the holder's record: the same process and computer, with a counter+ * that changes on every renewal. Never throws.+ * @param {string} lockDir+ */+export function renewLock(lockDir) {+ const file = path.join(lockDir, 'owner.json');+ try {+ const owner = JSON.parse(fs.readFileSync(file, 'utf-8'));+ const next = {...owner, beat: (Number(owner.beat) || 0) + 1};+ const tmp = `${file}.${process.pid}.tmp`;+ fs.writeFileSync(tmp, JSON.stringify(next));+ fs.renameSync(tmp, file);+ } catch {+ // A lock that was taken over or removed has no record to renew.+ }+}++/**+ * What this process last saw of each foreign lock: the record's text and+ * when that text was first seen.+ * @type {Map<string, {text: string, since: number}>}+ */+const observed = new Map();++/**+ * Whether a lock held from another computer has gone silent: its record has+ * not changed for `LEASE_SILENCE_MS` of this process's own observation.+ * @param {string} lockDir+ * @param {number} [now]+ * @returns {boolean}+ */+export function foreignLockIsSilent(lockDir, now = Date.now()) {+ let text;+ try {+ text = fs.readFileSync(path.join(lockDir, 'owner.json'), 'utf-8');+ } catch {+ text = '';+ }+ const seen = observed.get(lockDir);+ if (!seen || seen.text !== text) {+ observed.set(lockDir, {text, since: now});+ return false;+ }+ return now - seen.since >= LEASE_SILENCE_MS;+}++/** Forget what this process observed (tests). */+export function forgetObservedLocks() {+ observed.clear();+}diff --git a/packages/cli/foundation/release/notices.mjs b/packages/cli/foundation/release/notices.mjsnew file mode 100644index 0000000000..262a4d20d9--- /dev/null+++ b/packages/cli/foundation/release/notices.mjs@@ -0,0 +1,596 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Update notices (spec AST-081 FR10), the way `gh` and the Vercel CLI+ * tell their users about a newer release: after the command finishes, on+ * standard error, at most once a day per notice, never in machine-readable+ * output, and never when the environment turns them off (`CI`,+ * `NO_UPDATE_NOTIFIER`; update-notice-env.mjs). Unlike `gh`, a notice prints+ * when standard error is not a terminal too, because agents run the CLI+ * without one.+ *+ * Each notice is two lines:+ *+ * A new release of Astryx is available: 0.7.2 → 0.7.3+ * To upgrade, run: npm i -g @astryxdesign/cli@latest+ *+ * - Outside a project, about the global copy that answered, with the command+ * of the package manager that installed it (npm, pnpm, Yarn, Bun, Volta),+ * read from where it lives, as the Vercel CLI does.+ * - Inside a project, about the project's release, with the project's install+ * and `upgrade` commands.+ * - In any folder, about an `astryx` command first on the search path that+ * predates the hand-off and so answers every folder itself.+ *+ * A newer release needs a check that has reached the registry+ * (global-state.mjs); the last kind needs none. When the newest release needs+ * a newer Node than the computer runs, the second line says so. Prerelease and+ * canary versions are never reported as behind. The times of the notices are+ * kept in the per-user state file; a time that cannot be recorded keeps the+ * notice from printing, so it never prints on every run.+ *+ * @input the per-user state, the release choice, the project's files, the+ * search path, the clock, and the environment+ * @output notice lines, and the facts doctor reports+ * @position foundation/release — printed by handoff.mjs's startRun after the+ * command, read by doctor.+ */++import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {userConfigDir} from '../env/user-dirs.mjs';+import {astryxCommandsOnSearchPath} from '../env/search-path.mjs';+import {+ CLI_PACKAGE,+ detectPackageManager,+ getCliInvocation,+} from '../env/package-manager.mjs';+import {satisfiesRange, semverCompare} from '../env/semver.mjs';+import {isInReleaseCache, isReleaseVersion} from './cache.mjs';+import {+ knownLatest,+ readGlobalState,+ stateFile,+ tryStateLock,+ writeGlobalState,+} from './global-state.mjs';+import {globalFolderOf, isGlobalCopy, projectRootOf} from './choose.mjs';+import {readReleaseFacts} from './project.mjs';+import {samePath} from '../fs/path-compare.mjs';+import {updateNoticesOff} from './update-notice-env.mjs';++/** A notice prints at most once in this long. */+export const NOTICE_INTERVAL_MS = 24 * 60 * 60_000;++/** Notice times older than this are dropped from the state file. */+const FORGET_AFTER_MS = 30 * 24 * 60 * 60_000;++/**+ * The CLI package at its newest release, for every upgrade command. Spelled+ * out, not built from package-manager.mjs's constant: that module reaches+ * this one through the run context, so its bindings are not ready when this+ * module loads.+ */+const LATEST = '@astryxdesign/cli@latest';++/**+ * Whether notice `key` may print now; when it may, its time is recorded+ * first, and a time that cannot be recorded keeps it from printing.+ * @param {string} key+ * @param {{stateDir?: string, now?: number}} [options]+ * @returns {boolean}+ */+export function takeNotice(+ key,+ {stateDir = userConfigDir(), now = Date.now()} = {},+) {+ try {+ fs.mkdirSync(stateDir, {recursive: true});+ } catch {+ return false;+ }+ // Read, decide, and record under one lock: of the runs that finish at the+ // same moment, exactly one takes the notice.+ const outcome = tryStateLock(stateDir, () => {+ const state = readGlobalState(stateDir);+ const shown = state.notifiedAt ?? {};+ const last = shown[key];+ if (typeof last === 'number' && now - last < NOTICE_INTERVAL_MS) {+ const skips = withSkip(state.noticeSkips, key, 'already-shown', now);+ if (skips) writeGlobalState({...state, noticeSkips: skips}, stateDir);+ return /** @type {const} */ ('already-shown');+ }+ /** @type {Record<string, number>} */+ const next = {};+ for (const [k, t] of Object.entries(shown)) {+ if (typeof t === 'number' && now - t < FORGET_AFTER_MS) next[k] = t;+ }+ next[key] = now;+ return writeGlobalState({...state, notifiedAt: next}, stateDir)+ ? /** @type {const} */ ('taken')+ : /** @type {const} */ ('state-unwritable');+ });+ // A skip is recorded only inside the lock that made the decision. A lock+ // held past the wait, or a state file that cannot be written, records+ // nothing: doctor names a lock's holder from the lock itself.+ return outcome.ran && outcome.value === 'taken';+}++/** A skip with the same reason is recorded again only after this long. */+const SKIP_RECORD_INTERVAL_MS = 60 * 60_000;++/**+ * `skips` with `key`'s skip set to `reason` at `now`, dropping skips older+ * than {@link FORGET_AFTER_MS}; null when the same reason was recorded within+ * {@link SKIP_RECORD_INTERVAL_MS}, so a notice skipped on every run does not+ * rewrite the state file on every run.+ * @param {Record<string, import('./global-state.mjs').NoticeSkip> | undefined} skips+ * @param {string} key+ * @param {import('./global-state.mjs').NoticeSkip['reason']} reason+ * @param {number} now+ * @returns {Record<string, import('./global-state.mjs').NoticeSkip> | null}+ */+function withSkip(skips, key, reason, now) {+ const last = skips?.[key];+ if (last?.reason === reason && now - last.at < SKIP_RECORD_INTERVAL_MS) {+ return null;+ }+ /** @type {Record<string, import('./global-state.mjs').NoticeSkip>} */+ const next = {};+ for (const [k, skip] of Object.entries(skips ?? {})) {+ if (+ skip &&+ typeof skip.at === 'number' &&+ now - skip.at < FORGET_AFTER_MS+ ) {+ next[k] = skip;+ }+ }+ next[key] = {reason, at: now};+ return next;+}++/**+ * Record why notice `key` did not print (state `noticeSkips`), for diagnosis+ * only. It adds to a state file that already exists and never creates one, so+ * a run that keeps no state (a project's own CLI before any check) writes+ * nothing. It is written only while this run holds the state file's lock:+ * when the lock stays taken or the file cannot be written, nothing is+ * recorded, and a run never fails because of it.+ * @param {string} key+ * @param {import('./global-state.mjs').NoticeSkip['reason']} reason+ * @param {{stateDir?: string, now?: number}} [options]+ */+export function recordNoticeSkip(+ key,+ reason,+ {stateDir = userConfigDir(), now = Date.now()} = {},+) {+ try {+ if (!fs.existsSync(stateFile(stateDir))) return;+ tryStateLock(stateDir, () => {+ const state = readGlobalState(stateDir);+ const skips = withSkip(state.noticeSkips, key, reason, now);+ if (skips) writeGlobalState({...state, noticeSkips: skips}, stateDir);+ });+ } catch {+ // Diagnosis only.+ }+}++/**+ * The newest notice skip the state file records, with the notice it was for.+ * @param {{stateDir?: string}} [options]+ * @returns {({key: string} & import('./global-state.mjs').NoticeSkip) | null}+ */+export function lastNoticeSkip({stateDir = userConfigDir()} = {}) {+ /** @type {({key: string} & import('./global-state.mjs').NoticeSkip) | null} */+ let newest = null;+ for (const [key, skip] of Object.entries(+ readGlobalState(stateDir).noticeSkips ?? {},+ )) {+ if (+ skip &&+ typeof skip.at === 'number' &&+ (!newest || skip.at > newest.at)+ ) {+ newest = {key, ...skip};+ }+ }+ return newest;+}++/**+ * Is `version` a plain release older than `newest`?+ * @param {string | null | undefined} version+ * @param {string | null | undefined} newest+ * @returns {boolean}+ */+function isBehind(version, newest) {+ return (+ isReleaseVersion(version) &&+ isReleaseVersion(newest) &&+ !version.includes('-') &&+ !newest.includes('-') &&+ semverCompare(newest, version) > 0+ );+}++/**+ * The command that upgrades a CLI installed for the computer, by the package+ * manager whose global folder holds it (the Vercel CLI reads it the same+ * way); npm when none is recognized. A CLI that npm installed under a prefix+ * of its own (`npm i -g --prefix ~/.local`, `NPM_CONFIG_PREFIX`, or `prefix=`+ * in an `.npmrc`) is upgraded into that same prefix, named with `--prefix`,+ * so the upgrade lands where the running copy is whatever npm's settings are+ * when it runs. pnpm, Yarn, and Bun read their global folder from their own+ * settings, so their plain command reinstalls in place.+ * @param {string} cliRoot the CLI package's folder+ * @param {{execPath?: string, home?: string, platform?: NodeJS.Platform, env?: NodeJS.ProcessEnv}} [where]+ * @returns {string}+ */+export function globalUpgradeCommand(cliRoot, where = {}) {+ let at = cliRoot;+ try {+ at = fs.realpathSync(cliRoot);+ } catch {+ // Read the path as given.+ }+ if (/[\\/]\.volta[\\/]/iu.test(at)) return `volta install ${LATEST}`;+ const {+ home = os.homedir(),+ platform = process.platform,+ env = process.env,+ } = where;+ const global = globalFolderOf(at, {home, platform, env});+ // Each reads the same settings that named its global folder, so its plain+ // command reinstalls into that folder.+ if (global?.manager === 'bun') return `bun add -g ${LATEST}`;+ if (global?.manager === 'yarn') return `yarn global add ${LATEST}`;+ if (+ global?.manager === 'pnpm' ||+ /[\\/]pnpm[\\/]|[\\/]global[\\/]v?\d+[\\/]/iu.test(at)+ ) {+ return `pnpm add -g ${LATEST}`;+ }+ const prefix = npmOwnPrefix(at, where);+ return prefix+ ? `npm i -g --prefix ${prefix} ${LATEST}`+ : `npm i -g ${LATEST}`;+}++/**+ * The npm prefix that holds the CLI at `at`, as a person types it (`~` for+ * the home folder outside Windows), when it is not one npm uses by default:+ * Node's own prefix, `/usr/local` or `/usr`, or `%APPDATA%\\npm` on Windows.+ * Null for any other layout.+ * @param {string} at the CLI package's real path+ * @param {{execPath?: string, home?: string, platform?: NodeJS.Platform, env?: NodeJS.ProcessEnv}} where+ * @returns {string | null}+ */+function npmOwnPrefix(at, where) {+ const {+ execPath = process.execPath,+ home = os.homedir(),+ platform = process.platform,+ env = process.env,+ } = where;+ const win = platform === 'win32';+ const paths = win ? path.win32 : path.posix;+ const parts = at.split(/[\\/]/);+ const n = parts.length;+ if (parts[n - 1] !== 'cli' || parts[n - 2] !== '@astryxdesign') return null;+ if (parts[n - 3] !== 'node_modules') return null;+ // npm's global folder: `<prefix>/lib/node_modules` on macOS and Linux,+ // `<prefix>\\node_modules` on Windows.+ const depth = win ? n - 3 : n - 4;+ if (!win && parts[n - 4] !== 'lib') return null;+ const prefix = parts.slice(0, depth).join(win ? '\\' : '/') || paths.sep;+ const defaults = win+ ? [+ paths.dirname(execPath),+ ...(env.APPDATA ? [paths.join(env.APPDATA, 'npm')] : []),+ ]+ : [paths.dirname(paths.dirname(execPath)), '/usr/local', '/usr'];+ if (defaults.some(d => samePath(d, prefix, platform))) return null;+ if (!win) {+ const rel = paths.relative(home, prefix);+ if (rel === '') return '~';+ if (!rel.startsWith('..') && !paths.isAbsolute(rel)) return `~/${rel}`;+ }+ return /\s/.test(prefix) ? JSON.stringify(prefix) : prefix;+}++/**+ * The second line of a notice: the command, after the Node it needs when the+ * computer runs an older one.+ * @param {string} command+ * @param {string | null} node the Node range the newest release declares+ * @param {string} [nodeVersion]+ * @returns {string}+ */+export function upgradeLine(+ command,+ node,+ nodeVersion = process.versions.node,+) {+ return node && !satisfiesRange(nodeVersion, node)+ ? `To upgrade, install Node ${node} (this computer runs Node ${nodeVersion}), then run: ${command}`+ : `To upgrade, run: ${command}`;+}++/**+ * The first line of a newer-release notice.+ * @param {string} current+ * @param {string} newest+ * @returns {string}+ */+export function availableLine(current, newest) {+ return `A new release of Astryx is available: ${current} → ${newest}`;+}++/**+ * @typedef {object} GlobalBehind+ * @property {string} current the global copy's version+ * @property {string} newest the newest release known+ * @property {string | null} node the Node range it declares+ * @property {string} command the command that upgrades the global copy+ */++/**+ * Whether the global copy is older than the newest release known.+ * @param {{self: {version: string, root: string}, stateDir?: string}} options+ * @returns {GlobalBehind | null}+ */+export function globalBehind({self, stateDir = userConfigDir()}) {+ const latest = knownLatest(stateDir);+ if (!latest || !isBehind(self.version, latest.version)) return null;+ return {+ current: self.version,+ newest: latest.version,+ node: latest.node,+ command: globalUpgradeCommand(self.root),+ };+}++/**+ * @typedef {object} ProjectLag+ * @property {string} root the project's folder+ * @property {string} current the release that answers it+ * @property {string} newest the newest release known+ * @property {string | null} node the Node range the newest release declares+ * @property {string} install the command that installs the newest release+ * @property {string} upgrade the command that migrates the project+ */++/**+ * The install verb of each package manager.+ * @type {Record<string, string>}+ */+const ADD = {+ npm: 'npm install',+ pnpm: 'pnpm add',+ yarn: 'yarn add',+ bun: 'bun add',+};++/**+ * The commands that bring a project's own CLI and Core to one release, with+ * the project's package manager: when the CLI is newer, Core up to it and then+ * the codemods from Core's release; otherwise the CLI to Core's release.+ * @param {{cwd: string, cli: string, core: string}} options+ * @returns {string}+ */+export function alignCliAndCore({cwd, cli, core}) {+ const facts = readReleaseFacts(cwd);+ const root = projectRootOf(facts) ?? cwd;+ const add = ADD[detectPackageManager(root)] ?? ADD.npm;+ if (semverCompare(cli, core) > 0) {+ return `${add} @astryxdesign/core@${cli}, then ${getCliInvocation(root, {installed: true})} upgrade --from ${core} --apply`;+ }+ return `${add} ${CLI_PACKAGE}@${core}`;+}++/**+ * The hint for a project with no CLI of its own, answered by `answered` while+ * its Core is `core`: the command that adds the CLI at Core's version, with+ * the project's package manager.+ * @param {{cwd: string, answered: string, core: string}} options+ * @returns {{root: string, line: string}}+ */+export function noCliHint({cwd, answered, core}) {+ const root = projectRootOf(readReleaseFacts(cwd)) ?? cwd;+ return {root, line: noCliHintLine(answered, core, addCliCommand(root, core))};+}++/**+ * The hint's text.+ * @param {string} answered+ * @param {string} core+ * @param {string} command the command that adds the CLI at Core's version+ * @returns {string}+ */+export function noCliHintLine(answered, core, command) {+ return `astryx: this project has no Astryx CLI installed; answered by CLI ${answered} while its Core is ${core}. To match, run: ${command}`;+}++/**+ * The command that installs the CLI at `version` in the project at `root`,+ * with its package manager.+ * @param {string} root+ * @param {string} version+ * @returns {string}+ */+export function addCliCommand(root, version) {+ return `${ADD[detectPackageManager(root)] ?? ADD.npm} ${CLI_PACKAGE}@${version}`;+}++/**+ * Whether the project's release is older than the newest release known, and+ * the commands that upgrade it.+ * @param {{cwd: string, current: string, stateDir?: string}} options+ * @returns {ProjectLag | null}+ */+export function projectLag({cwd, current, stateDir = userConfigDir()}) {+ const latest = knownLatest(stateDir);+ if (!latest || !isBehind(current, latest.version)) return null;+ const newest = latest.version;+ const facts = readReleaseFacts(cwd);+ if (!facts.inProject) return null;+ const root = projectRootOf(facts) ?? cwd;+ const pm = detectPackageManager(root);+ // The CLI is always installed beside Core: a project that installed only+ // Core gets it too, as recommended, so its version is pinned with Core's.+ const install = `${ADD[pm] ?? ADD.npm} @astryxdesign/core@${newest} ${CLI_PACKAGE}@${newest}`;+ // The command runs after the install above, so the picker's guess is the+ // project's own CLI (spec AST-081 FR5).+ const stem = getCliInvocation(root, {installed: true});+ return {+ root,+ current,+ newest,+ node: latest.node,+ install,+ upgrade: `${stem} upgrade --from ${current} --apply`,+ };+}++/**+ * The first `astryx` on the search path, when it is an Astryx CLI release+ * that predates the hand-off and is not the running copy.+ * @param {{selfRoot?: string, searchPath?: string, platform?: NodeJS.Platform}} [options]+ * @returns {{file: string, version: string | null, command: string} | null}+ */+export function oldGlobalCommand({selfRoot, ...options} = {}) {+ const first = astryxCommandsOnSearchPath(options)[0];+ if (!first?.astryx || !first.cliRoot || first.handsOff !== false) return null;+ if (selfRoot && samePath(real(selfRoot), real(first.cliRoot))) return null;+ return {+ file: first.file,+ version: first.version,+ command: globalUpgradeCommand(first.cliRoot),+ };+}++/**+ * @param {string} p+ * @returns {string}+ */+function real(p) {+ try {+ return fs.realpathSync(p);+ } catch {+ return path.resolve(p);+ }+}++/**+ * The two lines about a global copy that predates the hand-off.+ * @param {{version: string | null, command: string}} old+ * @returns {string[]}+ */+export function oldGlobalLines(old) {+ return [+ `The astryx command on this computer runs CLI ${old.version ?? 'of an unknown version'}, which answers every folder itself.`,+ `To upgrade, run: ${old.command}`,+ ];+}++/**+ * The notice lines to print after a command, each notice recorded as shown.+ * Empty in machine-readable runs and when the environment turns notices off.+ * Never throws.+ * @param {{+ * cwd: string,+ * self: {version: string, root: string},+ * choice: {inProject: boolean, version: string, copy?: string, coreVersion?: string | null},+ * json?: boolean,+ * stateDir?: string,+ * cacheDir?: string,+ * now?: number,+ * env?: Record<string, string | undefined>,+ * searchPath?: string,+ * }} options+ * @returns {string[]}+ */+export function noticeLines({+ cwd,+ self,+ choice,+ json = false,+ stateDir = userConfigDir(),+ cacheDir,+ now = Date.now(),+ env = process.env,+ searchPath,+}) {+ // A run inside the release cache is the CLI checking a release it+ // installed, never a person's run.+ if (json || updateNoticesOff(env) || isInReleaseCache(cwd, cacheDir)) {+ return [];+ }+ /** @type {string[]} */+ const lines = [];+ const take = (/** @type {string} */ key) => takeNotice(key, {stateDir, now});+ try {+ // A project with no CLI of its own, answered by a release other than its+ // Core's: once a day per project, how to match them (FR2).+ if (+ choice.inProject &&+ choice.copy === 'starting' &&+ choice.coreVersion &&+ choice.coreVersion !== choice.version+ ) {+ const hint = noCliHint({+ cwd,+ answered: choice.version,+ core: choice.coreVersion,+ });+ if (take(`no-cli:${hint.root}`)) lines.push(hint.line);+ }+ } catch {+ // A hint never fails a run.+ }+ try {+ if (choice.inProject) {+ // The project's version is its own CLI's, or, with none, its Core's.+ const current =+ choice.copy === 'starting' && choice.coreVersion+ ? choice.coreVersion+ : choice.version;+ const lag = projectLag({cwd, current, stateDir});+ if (!lag) recordNoticeSkip('project', 'no-newer', {stateDir, now});+ if (lag && take(`project:${lag.root}`)) {+ lines.push(+ availableLine(lag.current, lag.newest),+ upgradeLine(`${lag.install}, then ${lag.upgrade}`, lag.node),+ );+ }+ } else if (isGlobalCopy(self.root, cacheDir)) {+ const behind = globalBehind({self, stateDir});+ if (!behind) recordNoticeSkip('global', 'no-newer', {stateDir, now});+ if (behind && take('global')) {+ lines.push(+ availableLine(behind.current, behind.newest),+ upgradeLine(behind.command, behind.node),+ );+ }+ }+ } catch {+ // A notice never fails a run.+ }+ try {+ const shown = readGlobalState(stateDir).notifiedAt?.['old-global'];+ if (typeof shown !== 'number' || now - shown >= NOTICE_INTERVAL_MS) {+ const old = oldGlobalCommand({+ selfRoot: self.root,+ ...(searchPath === undefined ? {} : {searchPath}),+ });+ if (old && take('old-global')) lines.push(...oldGlobalLines(old));+ }+ } catch {+ // Nor does this one.+ }+ return lines;+}diff --git a/packages/cli/foundation/release/notices.test.mjs b/packages/cli/foundation/release/notices.test.mjsnew file mode 100644index 0000000000..44a0c49fb2--- /dev/null+++ b/packages/cli/foundation/release/notices.test.mjs@@ -0,0 +1,565 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Update notices (spec AST-081 FR10): when each one applies, its exact+ * two lines, the upgrade command for each package manager, and that it prints+ * at most once a day and never when the environment turns notices off.+ */++import {afterEach, describe, expect, it} from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {spawn} from 'node:child_process';+import {+ recordDeclaredCliCommands,+ runWithCliDoor,+} from '../env/cli-command.mjs';+import {+ NOTICE_INTERVAL_MS,+ availableLine,+ globalBehind,+ globalUpgradeCommand,+ noticeLines,+ oldGlobalCommand,+ oldGlobalLines,+ projectLag,+ alignCliAndCore,+ lastNoticeSkip,+ recordNoticeSkip,+ takeNotice,+ upgradeLine,+} from './notices.mjs';+import {+ readGlobalState,+ stateLockHolder,+ tryStateLock,+ updateGlobalState,+} from './global-state.mjs';+import {+ cleanupFixtures,+ installCore,+ installStandInCli,+ project,+ tempDir,+ writeJson,+} from '../../test-utils/release-fixtures.mjs';++afterEach(cleanupFixtures);++const DAY = 24 * 60 * 60_000;++/**+ * An Astryx CLI package on a search path folder, with or without the hand-off.+ * @param {string} version+ * @param {{handsOff?: boolean, prefix?: string[]}} [options]+ */+function cliOnPath(version, {handsOff = false, prefix = ['lib']} = {}) {+ const root = tempDir('prefix');+ const pkg = path.join(+ root,+ ...prefix,+ 'node_modules',+ '@astryxdesign',+ 'cli',+ );+ fs.mkdirSync(pkg, {recursive: true});+ writeJson(path.join(pkg, 'package.json'), {+ name: '@astryxdesign/cli',+ version,+ });+ fs.writeFileSync(path.join(pkg, 'bin.mjs'), '#!/usr/bin/env node\n');+ fs.chmodSync(path.join(pkg, 'bin.mjs'), 0o755);+ if (handsOff) {+ fs.mkdirSync(path.join(pkg, 'foundation', 'release'), {recursive: true});+ fs.writeFileSync(path.join(pkg, 'foundation', 'release', 'choose.mjs'), '');+ }+ fs.mkdirSync(path.join(root, 'bin'));+ fs.symlinkSync(path.join(pkg, 'bin.mjs'), path.join(root, 'bin', 'astryx'));+ return {bin: path.join(root, 'bin'), pkg, root};+}++/** A state folder whose last check found `version`, needing Node `node`. */+function checked(version = '0.7.3', node = null) {+ const stateDir = tempDir('state');+ updateGlobalState(+ {latest: version, latestNode: node, checkOkAt: 1},+ stateDir,+ );+ return stateDir;+}++describe('takeNotice', () => {+ it('lets a notice print once in any 24 hours, per key', () => {+ const stateDir = tempDir('state');+ expect(takeNotice('a', {stateDir, now: 1000})).toBe(true);+ expect(takeNotice('a', {stateDir, now: 1000 + DAY - 1})).toBe(false);+ expect(takeNotice('b', {stateDir, now: 2000})).toBe(true);+ expect(takeNotice('a', {stateDir, now: 1000 + NOTICE_INTERVAL_MS})).toBe(+ true,+ );+ expect(readGlobalState(stateDir).notifiedAt).toEqual({+ a: 1000 + NOTICE_INTERVAL_MS,+ b: 2000,+ });+ });++ it('lets exactly one of many runs finishing at once take a notice (b18)', async () => {+ const stateDir = tempDir('state');+ const notices = new URL('./notices.mjs', import.meta.url).href;+ const source = `+ const {takeNotice} = await import(${JSON.stringify(notices)});+ const at = Number(process.argv[1]);+ while (Date.now() < at) {}+ process.stdout.write(takeNotice('global', {stateDir: ${JSON.stringify(stateDir)}}) ? 'took' : 'skip');+ `;+ const at = String(Date.now() + 1500);+ const runs = await Promise.all(+ Array.from(+ {length: 10},+ () =>+ new Promise(resolve => {+ const child = spawn(+ process.execPath,+ ['--input-type=module', '-e', source, at],+ {stdio: ['ignore', 'pipe', 'inherit']},+ );+ let out = '';+ child.stdout.on('data', d => (out += d));+ child.on('close', () => resolve(out));+ }),+ ),+ );+ expect(runs.filter(r => r === 'took')).toHaveLength(1);+ expect(runs.filter(r => r === 'skip')).toHaveLength(9);+ expect(fs.existsSync(path.join(stateDir, '.lock-state'))).toBe(false);+ });++ it('prints nothing when the time cannot be recorded', () => {+ const file = path.join(tempDir('state'), 'file');+ fs.writeFileSync(file, '');+ expect(takeNotice('a', {stateDir: file, now: 1})).toBe(false);+ });+});++describe('why a notice did not print (diagnostic state)', () => {+ it('records an already-shown skip, at most once an hour for the same reason', () => {+ const stateDir = tempDir('state');+ expect(takeNotice('global', {stateDir, now: 1000})).toBe(true);+ expect(takeNotice('global', {stateDir, now: 2000})).toBe(false);+ expect(readGlobalState(stateDir).noticeSkips).toEqual({+ global: {reason: 'already-shown', at: 2000},+ });+ // Within the hour: not rewritten.+ expect(takeNotice('global', {stateDir, now: 3000})).toBe(false);+ expect(readGlobalState(stateDir).noticeSkips?.global.at).toBe(2000);+ // After it: recorded again.+ expect(takeNotice('global', {stateDir, now: 2000 + 60 * 60_000})).toBe(+ false,+ );+ expect(readGlobalState(stateDir).noticeSkips?.global.at).toBe(+ 2000 + 60 * 60_000,+ );+ expect(lastNoticeSkip({stateDir})).toEqual({+ key: 'global',+ reason: 'already-shown',+ at: 2000 + 60 * 60_000,+ });+ });++ it('says a held lock timed out, and who holds it', () => {+ const stateDir = tempDir('state');+ const lockDir = path.join(stateDir, '.lock-state');+ fs.mkdirSync(lockDir, {recursive: true});+ fs.writeFileSync(+ path.join(lockDir, 'owner.json'),+ JSON.stringify({pid: process.pid, host: os.hostname(), at: Date.now()}),+ );+ expect(tryStateLock(stateDir, () => 'ran')).toEqual({+ ran: false,+ reason: 'lock-timeout',+ });+ expect(stateLockHolder(stateDir)).toMatchObject({pid: process.pid});+ fs.rmSync(lockDir, {recursive: true});+ expect(stateLockHolder(stateDir)).toBeNull();+ // Nothing is recorded where no state file exists yet.+ recordNoticeSkip('global', 'no-newer', {stateDir, now: 4});+ expect(fs.existsSync(path.join(stateDir, 'state.json'))).toBe(false);+ }, 10_000);++ it('records nothing for a notice the lock kept from printing, and writes no other file', () => {+ const stateDir = tempDir('state');+ updateGlobalState({latest: '0.7.1'}, stateDir);+ const lockDir = path.join(stateDir, '.lock-state');+ fs.mkdirSync(lockDir, {recursive: true});+ expect(takeNotice('global', {stateDir, now: 6})).toBe(false);+ fs.rmSync(lockDir, {recursive: true});+ expect(lastNoticeSkip({stateDir})).toBeNull();+ expect(fs.readdirSync(stateDir).sort()).toEqual(['state.json']);+ }, 10_000);+});++describe('the lines', () => {+ it('match the gh form, naming the Node a release needs', () => {+ expect(availableLine('0.7.2', '0.7.3')).toBe(+ 'A new release of Astryx is available: 0.7.2 → 0.7.3',+ );+ expect(+ upgradeLine('npm i -g @astryxdesign/cli@latest', '>=20', '22.0.0'),+ ).toBe('To upgrade, run: npm i -g @astryxdesign/cli@latest');+ expect(+ upgradeLine('npm i -g @astryxdesign/cli@latest', '>=24', '22.13.0'),+ ).toBe(+ 'To upgrade, install Node >=24 (this computer runs Node 22.13.0), then run: npm i -g @astryxdesign/cli@latest',+ );+ });++ it('upgrade a CLI that npm installed under its own prefix into that prefix', () => {+ const linux = {+ execPath: '/usr/bin/node',+ home: '/home/a',+ platform: /** @type {const} */ ('linux'),+ env: {},+ };+ expect(+ globalUpgradeCommand(+ '/home/a/.local/lib/node_modules/@astryxdesign/cli',+ linux,+ ),+ ).toBe('npm i -g --prefix ~/.local @astryxdesign/cli@latest');+ expect(+ globalUpgradeCommand(+ '/home/a/.npm-global/lib/node_modules/@astryxdesign/cli',+ linux,+ ),+ ).toBe('npm i -g --prefix ~/.npm-global @astryxdesign/cli@latest');+ expect(+ globalUpgradeCommand(+ '/opt/tools/lib/node_modules/@astryxdesign/cli',+ linux,+ ),+ ).toBe('npm i -g --prefix /opt/tools @astryxdesign/cli@latest');+ // npm's default prefixes: Node's own, /usr/local, /usr.+ for (const cli of [+ '/usr/local/lib/node_modules/@astryxdesign/cli',+ '/usr/lib/node_modules/@astryxdesign/cli',+ ]) {+ expect(globalUpgradeCommand(cli, linux)).toBe(+ 'npm i -g @astryxdesign/cli@latest',+ );+ }+ expect(+ globalUpgradeCommand(+ '/home/a/.nvm/versions/node/v22.1.0/lib/node_modules/@astryxdesign/cli',+ {+ ...linux,+ execPath: '/home/a/.nvm/versions/node/v22.1.0/bin/node',+ },+ ),+ ).toBe('npm i -g @astryxdesign/cli@latest');+ const win = {+ execPath: 'C:\\Program Files\\nodejs\\node.exe',+ home: 'C:\\Users\\a',+ platform: /** @type {const} */ ('win32'),+ env: {APPDATA: 'C:\\Users\\a\\AppData\\Roaming'},+ };+ expect(+ globalUpgradeCommand(+ 'C:\\Users\\a\\AppData\\Roaming\\npm\\node_modules\\@astryxdesign\\cli',+ win,+ ),+ ).toBe('npm i -g @astryxdesign/cli@latest');+ expect(+ globalUpgradeCommand(+ 'D:\\tools\\npm\\node_modules\\@astryxdesign\\cli',+ win,+ ),+ ).toBe('npm i -g --prefix D:\\tools\\npm @astryxdesign/cli@latest');+ });++ it('name the package manager that installed the global copy', () => {+ const at = (/** @type {string} */ p) =>+ globalUpgradeCommand(path.join(path.sep, ...p.split('/')), {+ home: '/home/a',+ platform: 'linux',+ env: {PNPM_HOME: '/home/a/pn'},+ });+ expect(at('usr/local/lib/node_modules/@astryxdesign/cli')).toBe(+ 'npm i -g @astryxdesign/cli@latest',+ );+ expect(at('home/a/pn/global/5/node_modules/@astryxdesign/cli')).toBe(+ 'pnpm add -g @astryxdesign/cli@latest',+ );+ expect(at('home/a/pn/global/v11/3f2a/node_modules/@astryxdesign/cli')).toBe(+ 'pnpm add -g @astryxdesign/cli@latest',+ );+ expect(+ at('home/a/.config/yarn/global/node_modules/@astryxdesign/cli'),+ ).toBe('yarn global add @astryxdesign/cli@latest');+ expect(+ at('home/a/.bun/install/global/node_modules/@astryxdesign/cli'),+ ).toBe('bun add -g @astryxdesign/cli@latest');+ expect(+ at(+ 'home/a/.volta/tools/image/packages/@astryxdesign/cli/lib/node_modules/@astryxdesign/cli',+ ),+ ).toBe('volta install @astryxdesign/cli@latest');+ });+});++describe('globalBehind and projectLag', () => {+ it('need a completed check, and never report a current, newer, or prerelease version', () => {+ const self = {+ version: '0.7.2',+ root: '/usr/lib/node_modules/@astryxdesign/cli',+ };+ expect(globalBehind({self, stateDir: tempDir('state')})).toBeNull();+ const stateDir = checked('0.7.3', '>=24');+ expect(globalBehind({self, stateDir})).toEqual({+ current: '0.7.2',+ newest: '0.7.3',+ node: '>=24',+ command: 'npm i -g @astryxdesign/cli@latest',+ });+ for (const version of ['0.7.3', '0.8.0', '0.7.2-canary.1']) {+ expect(globalBehind({self: {...self, version}, stateDir})).toBeNull();+ }+ });++ it("name a project's install and upgrade commands for its package manager", () => {+ const stateDir = checked('0.7.3');+ const coreOnly = project(tempDir(), {'@astryxdesign/core': '0.7.1'});+ writeJson(path.join(coreOnly, 'package-lock.json'), {lockfileVersion: 3});+ installCore(coreOnly, '0.7.1');+ expect(+ projectLag({cwd: coreOnly, current: '0.7.1', stateDir}),+ ).toMatchObject({+ root: coreOnly,+ install: 'npm install @astryxdesign/[email protected] @astryxdesign/[email protected]',+ upgrade: 'npx astryx upgrade --from 0.7.1 --apply',+ });+ const pnpm = project(tempDir(), {+ '@astryxdesign/core': '0.7.1',+ '@astryxdesign/cli': '0.7.1',+ });+ fs.writeFileSync(+ path.join(pnpm, 'pnpm-lock.yaml'),+ "lockfileVersion: '9.0'\n",+ );+ installCore(pnpm, '0.7.1');+ installStandInCli(pnpm, '0.7.1');+ expect(projectLag({cwd: pnpm, current: '0.7.1', stateDir})).toMatchObject({+ install: 'pnpm add @astryxdesign/[email protected] @astryxdesign/[email protected]',+ upgrade: 'pnpm exec astryx upgrade --from 0.7.1 --apply',+ });+ });+});++describe('the commands notices print go through the command-name picker (spec AST-081 FR5)', () => {+ /** A Core-only npm project behind the newest release. */+ const coreOnlyProject = () => {+ const dir = project(tempDir(), {'@astryxdesign/core': '0.7.1'});+ writeJson(path.join(dir, 'package-lock.json'), {lockfileVersion: 3});+ installCore(dir, '0.7.1');+ return dir;+ };++ it("use an integration's declared cliCommand for the upgrade step", () => {+ const stateDir = checked('0.7.3');+ const dir = coreOnlyProject();+ recordDeclaredCliCommands(dir, [+ {name: '@acme/a', cliCommand: 'acme astryx'},+ ]);+ try {+ expect(projectLag({cwd: dir, current: '0.7.1', stateDir})?.upgrade).toBe(+ 'acme astryx upgrade --from 0.7.1 --apply',+ );+ expect(alignCliAndCore({cwd: dir, cli: '0.7.3', core: '0.7.1'})).toBe(+ 'npm install @astryxdesign/[email protected], then acme astryx upgrade --from 0.7.1 --apply',+ );+ } finally {+ recordDeclaredCliCommands(dir, []);+ }+ });++ it("use a host's door when nothing is declared", () => {+ const stateDir = checked('0.7.3');+ const dir = coreOnlyProject();+ runWithCliDoor('host astryx', () => {+ expect(projectLag({cwd: dir, current: '0.7.1', stateDir})?.upgrade).toBe(+ 'host astryx upgrade --from 0.7.1 --apply',+ );+ expect(alignCliAndCore({cwd: dir, cli: '0.7.3', core: '0.7.1'})).toBe(+ 'npm install @astryxdesign/[email protected], then host astryx upgrade --from 0.7.1 --apply',+ );+ });+ });++ it("fall back to the project's own installed CLI", () => {+ const dir = coreOnlyProject();+ expect(alignCliAndCore({cwd: dir, cli: '0.7.3', core: '0.7.1'})).toBe(+ 'npm install @astryxdesign/[email protected], then npx astryx upgrade --from 0.7.1 --apply',+ );+ });+});++describe.skipIf(process.platform === 'win32')('oldGlobalCommand', () => {+ it('names a first astryx that predates the hand-off with its own package manager, and not one that hands off', () => {+ const old = cliOnPath('0.7.1', {prefix: ['global', '5']});+ expect(oldGlobalCommand({searchPath: old.bin, platform: 'linux'})).toEqual({+ file: path.join(old.bin, 'astryx'),+ version: '0.7.1',+ command: 'pnpm add -g @astryxdesign/cli@latest',+ });+ expect(+ oldGlobalLines({+ version: '0.7.1',+ command: 'npm i -g @astryxdesign/cli@latest',+ }),+ ).toEqual([+ 'The astryx command on this computer runs CLI 0.7.1, which answers every folder itself.',+ 'To upgrade, run: npm i -g @astryxdesign/cli@latest',+ ]);+ const current = cliOnPath('0.8.0', {handsOff: true});+ expect(+ oldGlobalCommand({+ searchPath: [current.bin, old.bin].join(path.delimiter),+ platform: 'linux',+ }),+ ).toBeNull();+ expect(+ oldGlobalCommand({+ selfRoot: old.pkg,+ searchPath: old.bin,+ platform: 'linux',+ }),+ ).toBeNull();+ });+});++describe.skipIf(process.platform === 'win32')('noticeLines', () => {+ /** A global copy, outside a project. */+ const outside = () => {+ const global = cliOnPath('0.7.2', {handsOff: true});+ return {+ global,+ cwd: tempDir('empty'),+ self: {version: '0.7.2', root: global.pkg},+ choice: {inProject: false, version: '0.7.2'},+ cacheDir: tempDir('cache'),+ searchPath: global.bin,+ env: {},+ };+ };++ it('tells the global copy about a newer release, once a day', () => {+ const {global, ...input} = {...outside(), stateDir: checked('0.7.3')};+ // The fixture's global folder is a prefix of its own, so the upgrade+ // names it.+ const prefix = fs.realpathSync(global.root);+ expect(noticeLines({...input, now: 10})).toEqual([+ 'A new release of Astryx is available: 0.7.2 → 0.7.3',+ `To upgrade, run: npm i -g --prefix ${prefix} @astryxdesign/cli@latest`,+ ]);+ expect(noticeLines({...input, now: 20})).toEqual([]);+ expect(lastNoticeSkip({stateDir: input.stateDir})).toEqual({+ key: 'global',+ reason: 'already-shown',+ at: 20,+ });+ expect(noticeLines({...input, now: 10 + DAY})).toHaveLength(2);+ });++ it('records that nothing newer was known when the global copy is current', () => {+ const {global: _global, ...input} = {+ ...outside(),+ stateDir: checked('0.7.2'),+ };+ expect(noticeLines({...input, now: 30})).toEqual([]);+ expect(lastNoticeSkip({stateDir: input.stateDir})).toEqual({+ key: 'global',+ reason: 'no-newer',+ at: 30,+ });+ });++ it('prints nothing with --json, in CI, or with NO_UPDATE_NOTIFIER, and keeps the notice for later', () => {+ const {global: _global, ...input} = {+ ...outside(),+ stateDir: checked('0.7.3'),+ };+ expect(noticeLines({...input, json: true, now: 10})).toEqual([]);+ expect(noticeLines({...input, env: {CI: 'true'}, now: 10})).toEqual([]);+ expect(+ noticeLines({...input, env: {NO_UPDATE_NOTIFIER: '1'}, now: 10}),+ ).toEqual([]);+ expect(noticeLines({...input, now: 10})).toHaveLength(2);+ });++ it('tells a project about its release, and an old astryx first on the search path, even with no check', () => {+ const stateDir = checked('0.7.3');+ const dir = project(tempDir(), {'@astryxdesign/core': '0.7.1'});+ writeJson(path.join(dir, 'package-lock.json'), {lockfileVersion: 3});+ installCore(dir, '0.7.1');+ const old = cliOnPath('0.7.1');+ const oldUpgrade = `To upgrade, run: npm i -g --prefix ${fs.realpathSync(old.root)} @astryxdesign/cli@latest`;+ const input = {+ cwd: dir,+ self: {version: '0.7.1', root: tempDir('self')},+ choice: {inProject: true, version: '0.7.1'},+ searchPath: old.bin,+ env: {},+ };+ expect(noticeLines({...input, stateDir, now: 10})).toEqual([+ 'A new release of Astryx is available: 0.7.1 → 0.7.3',+ 'To upgrade, run: npm install @astryxdesign/[email protected] @astryxdesign/[email protected], then npx astryx upgrade --from 0.7.1 --apply',+ 'The astryx command on this computer runs CLI 0.7.1, which answers every folder itself.',+ oldUpgrade,+ ]);+ expect(+ noticeLines({...input, stateDir: tempDir('fresh'), now: 10}),+ ).toEqual([+ 'The astryx command on this computer runs CLI 0.7.1, which answers every folder itself.',+ oldUpgrade,+ ]);+ });++ it('says nothing in a run inside the release cache, the CLI checking a release it installed', () => {+ const cacheDir = tempDir('cache');+ const tmp = path.join(cacheDir, 'releases', '.tmp-0.7.2-1-abc');+ fs.mkdirSync(tmp, {recursive: true});+ const stateDir = checked('0.7.3');+ const old = cliOnPath('0.7.1');+ const input = {+ cwd: tmp,+ self: {version: '0.7.2', root: tempDir('self')},+ choice: {inProject: true, version: '0.7.2'},+ cacheDir,+ stateDir,+ searchPath: old.bin,+ env: {},+ now: 10,+ };+ expect(noticeLines(input)).toEqual([]);+ expect(readGlobalState(stateDir).notifiedAt).toBeUndefined();+ });++ it('says nothing about a copy that is not the global copy outside a project', () => {+ const runner = {+ ...outside(),+ self: {+ version: '0.7.2',+ root: path.join(+ tempDir('npx'),+ '_npx',+ 'x',+ 'node_modules',+ '@astryxdesign',+ 'cli',+ ),+ },+ stateDir: checked('0.7.3'),+ };+ expect(noticeLines({...runner, now: 10})).toEqual([]);+ });+});diff --git a/packages/cli/foundation/release/npm-guard.mjs b/packages/cli/foundation/release/npm-guard.mjsnew file mode 100644index 0000000000..ab1dd1d765--- /dev/null+++ b/packages/cli/foundation/release/npm-guard.mjs@@ -0,0 +1,126 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Runs one package-manager command so that it can never outlive the+ * run that started it.+ *+ * `runNpm` (cache.mjs) starts this file instead of npm itself. It starts npm+ * in a process group of its own, records npm's process id where the release+ * lock can find it, and ends npm's whole group when any of these happens:+ *+ * - the time limit passes (exit status 124);+ * - the run that started it goes away, even when it was killed outright and+ * had no chance to clean up (its parent process changes);+ * - it receives Ctrl-C, a closed terminal, or a termination request: it ends+ * npm's group outright (npm defers these signals and would keep this run's+ * output pipes open), then ends the same way.+ *+ * While npm works it renews the lock's owner record every 10 seconds+ * (lock-lease.mjs), so a run on another computer that shares the cache knows+ * the install is alive.+ *+ * Not a command and takes no options of its own; its arguments come only+ * from `runNpm`.+ *+ * @input argv: time limit (ms), process-id file ('' for none), command, args+ * @output npm's exit status; npm's output on the inherited streams+ * @position foundation/release — started only by cache.mjs.+ */++import {spawn} from 'node:child_process';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {LEASE_RENEW_MS, renewLock} from './lock-lease.mjs';++const [timeoutArg, pidFile, command, ...args] = process.argv.slice(2);+const timeoutMs = Number(timeoutArg);+const parent = process.ppid;+const posix = process.platform !== 'win32';++const child = spawn(command, args, {+ stdio: 'inherit',+ detached: posix,+ windowsHide: true,+});++/** End npm and everything it started. @param {NodeJS.Signals} signal */+function endGroup(signal) {+ try {+ if (posix && child.pid) process.kill(-child.pid, signal);+ else child.kill(signal);+ } catch {+ // Already gone.+ }+}++if (pidFile && child.pid) {+ try {+ fs.writeFileSync(pidFile, String(child.pid));+ } catch {+ // Without the record a takeover cannot end npm; the watch below still does.+ }+}++/**+ * Remove the process-id record: once npm is ended, its id may be reused by+ * an unrelated process, which a later takeover must never end.+ */+function forgetPid() {+ if (pidFile) fs.rmSync(pidFile, {force: true});+}++const limit = setTimeout(() => {+ endGroup('SIGKILL');+ forgetPid();+ process.exit(124);+}, timeoutMs);++const watch = setInterval(() => {+ if (process.ppid !== parent) {+ endGroup('SIGKILL');+ forgetPid();+ process.exit(1);+ }+}, 500);++// The lock beside the pid file is renewed while npm works, so a run on+// another computer sharing the cache knows its holder is alive.+const lease = pidFile+ ? setInterval(() => renewLock(path.dirname(pidFile)), LEASE_RENEW_MS)+ : null;+lease?.unref();++for (const signal of /** @type {NodeJS.Signals[]} */ ([+ 'SIGINT',+ 'SIGTERM',+ 'SIGHUP',+])) {+ process.on(signal, () => {+ // npm defers these signals until its work finishes, and it holds this+ // run's output pipes open, so it is ended outright.+ endGroup('SIGKILL');+ forgetPid();+ clearTimeout(limit);+ clearInterval(watch);+ process.removeAllListeners(signal);+ process.kill(process.pid, signal);+ });+}++child.on('error', () => {+ clearTimeout(limit);+ clearInterval(watch);+ forgetPid();+ process.exit(127);+});++child.on('exit', (code, signal) => {+ clearTimeout(limit);+ clearInterval(watch);+ forgetPid();+ if (signal) {+ process.kill(process.pid, signal);+ return;+ }+ process.exit(code ?? 1);+});diff --git a/packages/cli/foundation/release/project.mjs b/packages/cli/foundation/release/project.mjsnew file mode 100644index 0000000000..6760f47ae7--- /dev/null+++ b/packages/cli/foundation/release/project.mjs@@ -0,0 +1,466 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file What a folder's project says about which CLI release answers there.+ *+ * Global mode picks one release per folder (spec AST-081 FR2): the project's+ * own CLI when it matches the project's Core, otherwise the CLI release that+ * matches the Core. This module reads the facts that choice needs, and nothing+ * else: the Core the folder reads, the CLI the folder installs, and the Astryx+ * versions its package.json and lockfile record.+ *+ * It finds Core and the CLI with the CLI's released reach, the same lookups+ * every read uses (`findCoreDir`, `findInstalledPackage`), so the release that+ * answers always pairs with the Core its reads load. A folder inside another+ * project therefore belongs to that project, as it does for reads.+ *+ * Plain files only: no imports beyond Node built-ins and the path helpers, so+ * the bin can read these facts before it loads anything else.+ *+ * @input a folder+ * @output {@link ReleaseFacts}+ * @position foundation/release — read by the bin's hand-off and by the run+ * context that names who answered.+ */++import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {findInstalledPackage} from '../fs/paths.mjs';++/** The CLI package. */+export const CLI_PACKAGE_NAME = '@astryxdesign/cli';+/** The Core package. */+export const CORE_PACKAGE_NAME = '@astryxdesign/core';++/**+ * An installed package and its version.+ * @typedef {object} InstalledAstryxPackage+ * @property {string} dir the package folder+ * @property {string} version its package.json version+ */++/**+ * What one folder's project says about releases.+ * @typedef {object} ReleaseFacts+ * @property {boolean} inProject the folder belongs to a project: it reads an+ * installed Core or CLI, or a package.json above it declares one+ * @property {InstalledAstryxPackage | null} core the Core the folder reads+ * @property {InstalledAstryxPackage | null} cli the CLI the folder installs+ * @property {string | null} declaringDir the nearest folder whose package.json+ * declares the Core or the CLI+ * @property {string | null} declaredCoreRange the Core range it declares+ * @property {string | null} declaredCliRange the CLI range it declares+ * @property {string | null} lockedCoreVersion the Core version its lockfile records+ * @property {string | null} lockedCliVersion the CLI version its lockfile records+ */++/**+ * Read and parse a JSON file, or null.+ * @param {string} file+ * @returns {any}+ */+export function readJson(file) {+ try {+ return JSON.parse(fs.readFileSync(file, 'utf-8'));+ } catch {+ // Missing or unreadable: the caller treats it as absent.+ return null;+ }+}++/**+ * The version of an installed package folder, when it is the package named.+ * @param {string} dir+ * @param {string} name+ * @returns {InstalledAstryxPackage | null}+ */+function installedAs(dir, name) {+ const pkg = readJson(path.join(dir, 'package.json'));+ if (!pkg || pkg.name !== name || typeof pkg.version !== 'string') {+ return null;+ }+ return {dir, version: pkg.version};+}++/**+ * The Core the folder reads, found the way `findCoreDir` finds it: the+ * folder and up to four folders above it, a workspace's `packages/core` or+ * an installed `node_modules/@astryxdesign/core`, else the same from the+ * folder of the package.json that makes the folder part of a project. A `packages/core` that is+ * another package is skipped, because no release pairs with it.+ * @param {string} startDir+ * @returns {InstalledAstryxPackage | null}+ */+export function findReadCore(startDir) {+ const near = nearbyReadCore(startDir);+ if (near) return near;+ // A folder deeper than that reach still belongs to the project the walk to+ // its package.json finds, so its Core is read from there (spec AST-081, a+ // folder's project).+ const declaring = findDeclaringPackage(startDir);+ return declaring && declaring.dir !== path.resolve(startDir)+ ? nearbyReadCore(declaring.dir)+ : null;+}++/**+ * The Core installed in the folder or one of the four folders above it, or a+ * workspace's own Core package there.+ * @param {string} startDir+ * @returns {InstalledAstryxPackage | null}+ */+function nearbyReadCore(startDir) {+ let dir = path.resolve(startDir);+ for (let i = 0; i < 5; i++) {+ const workspace = installedAs(+ path.join(dir, 'packages', 'core'),+ CORE_PACKAGE_NAME,+ );+ if (workspace) return workspace;+ const installed = installedAs(+ path.join(dir, 'node_modules', '@astryxdesign', 'core'),+ CORE_PACKAGE_NAME,+ );+ if (installed) return installed;+ const parent = path.dirname(dir);+ if (parent === dir) break;+ dir = parent;+ }+ return null;+}++/**+ * The CLI the folder installs, found the way reads find installed packages;+ * else a workspace's own CLI package: the folder itself when it is the CLI+ * package, or a `packages/cli` that is, in the folder or one of the five+ * folders above it (spec AST-081, a folder's project). A repository that+ * builds the CLI and Core side by side answers with its own CLI.+ * @param {string} startDir+ * @returns {InstalledAstryxPackage | null}+ */+export function findProjectCli(startDir) {+ const start = path.resolve(startDir);+ const dir = findInstalledPackage(start, CLI_PACKAGE_NAME);+ if (dir) return installedAs(dir, CLI_PACKAGE_NAME);+ let at = start;+ for (let i = 0; i < 6; i++) {+ const own =+ installedAs(at, CLI_PACKAGE_NAME) ??+ installedAs(path.join(at, 'packages', 'cli'), CLI_PACKAGE_NAME);+ if (own) return own;+ const parent = path.dirname(at);+ if (parent === at) break;+ at = parent;+ }+ return null;+}++/** Version-control metadata that marks a repository's root. */+const REPOSITORY_MARKERS = ['.git', '.hg', '.sl'];++/**+ * The Astryx ranges a package.json declares, from any dependency field.+ * @param {any} pkg+ * @returns {{core: string | null, cli: string | null}}+ */+function declaredRanges(pkg) {+ /** @type {{core: string | null, cli: string | null}} */+ const out = {core: null, cli: null};+ if (!pkg || typeof pkg !== 'object') return out;+ for (const field of [+ 'dependencies',+ 'devDependencies',+ 'optionalDependencies',+ 'peerDependencies',+ ]) {+ const deps = pkg[field];+ if (!deps || typeof deps !== 'object') continue;+ if (out.core === null && typeof deps[CORE_PACKAGE_NAME] === 'string') {+ out.core = deps[CORE_PACKAGE_NAME];+ }+ if (out.cli === null && typeof deps[CLI_PACKAGE_NAME] === 'string') {+ out.cli = deps[CLI_PACKAGE_NAME];+ }+ }+ return out;+}++/**+ * The nearest package.json at or above `startDir` that declares the Core or+ * the CLI. The search stops after the first folder that holds+ * version-control metadata, and passes the home folder by unless the run+ * starts there, so a stray package.json in the home folder never claims every+ * folder beneath it.+ * @param {string} startDir+ * @returns {{dir: string, core: string | null, cli: string | null} | null}+ */+export function findDeclaringPackage(startDir) {+ const home = path.resolve(os.homedir());+ const start = path.resolve(startDir);+ let dir = start;+ for (;;) {+ if (dir !== home || dir === start) {+ const ranges = declaredRanges(readJson(path.join(dir, 'package.json')));+ if (ranges.core !== null || ranges.cli !== null) return {dir, ...ranges};+ }+ if (REPOSITORY_MARKERS.some(m => fs.existsSync(path.join(dir, m)))) {+ return null;+ }+ const parent = path.dirname(dir);+ if (parent === dir) return null;+ dir = parent;+ }+}++/**+ * Every lockfile name the version reader understands.+ */+const LOCKFILES = [+ 'package-lock.json',+ 'npm-shrinkwrap.json',+ 'pnpm-lock.yaml',+ 'yarn.lock',+ 'bun.lock',+];++/**+ * The version a lockfile records for `name`, for the package at `memberDir`.+ * @param {string} lockfile+ * @param {string} memberDir the folder whose package.json declares it+ * @param {string} name+ * @param {string | null} range the range that folder declares+ * @returns {string | null}+ */+export function lockedVersion(lockfile, memberDir, name, range) {+ let text;+ try {+ text = fs.readFileSync(lockfile, 'utf-8');+ } catch {+ // An unreadable lockfile records nothing.+ return null;+ }+ const base = path.basename(lockfile);+ const rel = path+ .relative(path.dirname(lockfile), memberDir)+ .split(path.sep)+ .join('/');+ if (base === 'package-lock.json' || base === 'npm-shrinkwrap.json') {+ const lock = safeJson(text);+ const packages = lock?.packages;+ if (packages && typeof packages === 'object') {+ for (const key of [+ rel ? `${rel}/node_modules/${name}` : null,+ `node_modules/${name}`,+ ]) {+ const version = key ? packages[key]?.version : undefined;+ if (typeof version === 'string') return version;+ }+ }+ const legacy = lock?.dependencies?.[name]?.version;+ return typeof legacy === 'string' ? legacy : null;+ }+ if (base === 'pnpm-lock.yaml') return pnpmLockedVersion(text, rel, name);+ if (base === 'yarn.lock') return yarnLockedVersion(text, name, range);+ if (base === 'bun.lock') return bunLockedVersion(text, name);+ return null;+}++/**+ * @param {string} text+ * @returns {any}+ */+function safeJson(text) {+ try {+ return JSON.parse(text);+ } catch {+ return null;+ }+}++/** @param {string} s */+const escapeRe = s => s.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&');++/**+ * A pnpm lockfile's version for `name` in the importer at `rel` (`.` at the+ * root): the `version:` under that importer's dependency entry, with any+ * peer suffix (`0.7.1([email protected])`) dropped.+ * @param {string} text+ * @param {string} rel+ * @param {string} name+ * @returns {string | null}+ */+function pnpmLockedVersion(text, rel, name) {+ const lines = text.split(/\r?\n/);+ const importer = rel || '.';+ let inImporters = false;+ let inThisImporter = false;+ for (let i = 0; i < lines.length; i++) {+ const line = lines[i];+ if (/^importers:\s*$/.test(line)) {+ inImporters = true;+ continue;+ }+ if (inImporters && /^\S/.test(line)) break;+ if (!inImporters) continue;+ const importerMatch = /^ {2}(?! )(['"]?)(.+?)\1:\s*$/.exec(line);+ if (importerMatch) {+ inThisImporter = importerMatch[2] === importer;+ continue;+ }+ if (!inThisImporter) continue;+ const depMatch = new RegExp(`^ {6}(['"]?)${escapeRe(name)}\\1:\\s*$`).exec(+ line,+ );+ if (!depMatch) continue;+ for (let j = i + 1; j < lines.length && /^ {8}/.test(lines[j]); j++) {+ const v = /^ {8}version:\s*['"]?([^'"\s(]+)/.exec(lines[j]);+ if (v) return cleanVersion(v[1]);+ }+ }+ // An older lockfile without importers lists `/name@version` keys.+ const key = new RegExp(+ `^ {2}['"]?/?${escapeRe(name)}[@/](\\d[^:'"\\s(]*)`,+ 'm',+ );+ const m = key.exec(text);+ return m ? cleanVersion(m[1]) : null;+}++/**+ * A yarn.lock's version for `name`: the entry whose descriptors include the+ * declared range (classic `name@^1`, Berry `name@npm:^1`), else the only+ * entry for the name.+ * @param {string} text+ * @param {string} name+ * @param {string | null} range+ * @returns {string | null}+ */+function yarnLockedVersion(text, name, range) {+ const blocks = text.split(/\r?\n(?=\S)/);+ /** @type {string[]} */+ const versions = [];+ for (const block of blocks) {+ const [head, ...rest] = block.split(/\r?\n/);+ const descriptors = head+ .replace(/:\s*$/, '')+ .split(',')+ .map(d => d.trim().replace(/^"|"$/g, ''));+ const ours = descriptors.filter(+ d => d.startsWith(`${name}@`) && !d.startsWith(`${name}@patch:`),+ );+ if (ours.length === 0) continue;+ const versionLine = rest.find(l => /^\s+version:?\s/.test(l));+ const v = versionLine && /version:?\s+"?([^"\s]+)"?/.exec(versionLine);+ const version = v ? cleanVersion(v[1]) : null;+ if (!version) continue;+ if (+ range &&+ ours.some(d => d === `${name}@${range}` || d === `${name}@npm:${range}`)+ ) {+ return version;+ }+ versions.push(version);+ }+ return versions.length === 1 ? versions[0] : null;+}++/**+ * A bun.lock's version for `name`: its `packages` entry,+ * `"name": ["name@version", …]`.+ * @param {string} text+ * @param {string} name+ * @returns {string | null}+ */+function bunLockedVersion(text, name) {+ const m = new RegExp(+ `"${escapeRe(name)}"\\s*:\\s*\\[\\s*"${escapeRe(name)}@([^"]+)"`,+ ).exec(text);+ return m ? cleanVersion(m[1]) : null;+}++/**+ * A plain version from a lockfile value: strips an `npm:` protocol and any+ * peer suffix.+ * @param {string} value+ * @returns {string | null}+ */+function cleanVersion(value) {+ const v = value.replace(/^npm:/, '').replace(/\(.*$/, '');+ return /^\d+\.\d+\.\d+/.test(v) ? v : null;+}++/**+ * The lockfile that records the package at `memberDir`: the nearest one at or+ * above it, up to the repository root.+ * @param {string} memberDir+ * @returns {string | null}+ */+export function findLockfile(memberDir) {+ let dir = path.resolve(memberDir);+ for (;;) {+ for (const name of LOCKFILES) {+ const file = path.join(dir, name);+ if (fs.existsSync(file)) return file;+ }+ if (REPOSITORY_MARKERS.some(m => fs.existsSync(path.join(dir, m)))) {+ return null;+ }+ const parent = path.dirname(dir);+ if (parent === dir) return null;+ dir = parent;+ }+}++/**+ * Read every release fact for `startDir`.+ * @param {string} startDir+ * @returns {ReleaseFacts}+ */+export function readReleaseFacts(startDir) {+ const declaring = findDeclaringPackage(startDir);+ // A folder deeper than the nearby look reaches still belongs to the project+ // the walk found, so its own CLI is looked up from there too, as a package+ // runner resolves the project's command from any depth (spec AST-081, a+ // folder's project); findReadCore does the same for Core.+ const fromRoot =+ declaring && declaring.dir !== path.resolve(startDir)+ ? declaring.dir+ : null;+ const core = findReadCore(startDir);+ const cli =+ findProjectCli(startDir) ?? (fromRoot ? findProjectCli(fromRoot) : null);+ let lockedCoreVersion = null;+ let lockedCliVersion = null;+ if (declaring && (!core || !cli)) {+ const lockfile = findLockfile(declaring.dir);+ if (lockfile) {+ lockedCoreVersion = declaring.core+ ? lockedVersion(+ lockfile,+ declaring.dir,+ CORE_PACKAGE_NAME,+ declaring.core,+ )+ : null;+ lockedCliVersion = declaring.cli+ ? lockedVersion(+ lockfile,+ declaring.dir,+ CLI_PACKAGE_NAME,+ declaring.cli,+ )+ : null;+ }+ }+ return {+ inProject: Boolean(core || cli || declaring),+ core,+ cli,+ declaringDir: declaring?.dir ?? null,+ declaredCoreRange: declaring?.core ?? null,+ declaredCliRange: declaring?.cli ?? null,+ lockedCoreVersion,+ lockedCliVersion,+ };+}diff --git a/packages/cli/foundation/release/project.test.mjs b/packages/cli/foundation/release/project.test.mjsnew file mode 100644index 0000000000..53af51c697--- /dev/null+++ b/packages/cli/foundation/release/project.test.mjs@@ -0,0 +1,288 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, it, expect, afterEach} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {+ findDeclaringPackage,+ findLockfile,+ findProjectCli,+ findReadCore,+ lockedVersion,+ readReleaseFacts,+} from './project.mjs';+import {+ cleanupFixtures,+ installCore,+ installStandInCli,+ project,+ tempDir,+ writeJson,+} from '../../test-utils/release-fixtures.mjs';++afterEach(cleanupFixtures);++describe('findReadCore', () => {+ it('finds the installed Core in the folder or up to four above it, and from the declaring package.json at any depth (b30)', () => {+ const root = project(tempDir(), {'@astryxdesign/core': '0.6.8'});+ installCore(root, '0.6.8');+ const deep = path.join(root, 'a', 'b', 'c', 'd');+ fs.mkdirSync(deep, {recursive: true});+ expect(findReadCore(deep)?.version).toBe('0.6.8');+ const tooDeep = path.join(deep, 'e', 'f', 'g');+ fs.mkdirSync(tooDeep, {recursive: true});+ expect(findReadCore(tooDeep)?.version).toBe('0.6.8');+ // With no package.json that declares Astryx, the reach stays four folders.+ const plain = tempDir();+ writeJson(path.join(plain, 'package.json'), {name: 'plain'});+ installCore(plain, '0.6.8');+ const plainDeep = path.join(plain, 'a', 'b', 'c', 'd', 'e');+ fs.mkdirSync(plainDeep, {recursive: true});+ expect(findReadCore(plainDeep)).toBeNull();+ });++ it("skips a workspace's packages/core that is another package", () => {+ const root = tempDir();+ writeJson(path.join(root, 'packages', 'core', 'package.json'), {+ name: '@acme/core',+ version: '1.0.0',+ });+ installCore(root, '0.7.1');+ expect(findReadCore(root)?.version).toBe('0.7.1');+ });++ it("takes a workspace's own CLI package, at the root and inside it (b13)", () => {+ const root = tempDir();+ writeJson(path.join(root, 'package.json'), {name: 'repo', private: true});+ writeJson(path.join(root, 'packages', 'core', 'package.json'), {+ name: '@astryxdesign/core',+ version: '0.7.4',+ });+ writeJson(path.join(root, 'packages', 'cli', 'package.json'), {+ name: '@astryxdesign/cli',+ version: '0.7.4',+ });+ const cliDir = path.join(root, 'packages', 'cli');+ for (const dir of [root, cliDir, path.join(root, 'apps', 'site')]) {+ fs.mkdirSync(dir, {recursive: true});+ expect(findProjectCli(dir)).toEqual({dir: cliDir, version: '0.7.4'});+ }+ writeJson(path.join(root, 'packages', 'cli', 'package.json'), {+ name: 'some-other-cli',+ version: '1.0.0',+ });+ expect(findProjectCli(root)).toBeNull();+ });++ it("takes a workspace's own Core package", () => {+ const root = tempDir();+ writeJson(path.join(root, 'packages', 'core', 'package.json'), {+ name: '@astryxdesign/core',+ version: '0.7.2',+ });+ expect(findReadCore(root)?.dir).toBe(path.join(root, 'packages', 'core'));+ });+});++describe('findDeclaringPackage', () => {+ it('finds the nearest package.json that declares Core or the CLI', () => {+ const root = project(tempDir(), {'@astryxdesign/core': '^0.6.8'});+ const nested = path.join(root, 'tools', 'pkg');+ writeJson(path.join(nested, 'package.json'), {+ name: 'pkg',+ dependencies: {'left-pad': '1'},+ });+ expect(findDeclaringPackage(nested)).toEqual({+ dir: root,+ core: '^0.6.8',+ cli: null,+ });+ });++ it('stops at the first folder with version-control metadata', () => {+ const root = project(tempDir(), {'@astryxdesign/core': '0.6.8'});+ const clone = path.join(root, 'vendor', 'repo');+ fs.mkdirSync(path.join(clone, '.git'), {recursive: true});+ expect(findDeclaringPackage(path.join(clone))).toBeNull();+ });++ it('reads peer and dev dependencies too', () => {+ const root = tempDir();+ writeJson(path.join(root, 'package.json'), {+ name: 'lib',+ peerDependencies: {'@astryxdesign/core': '>=0.7.0'},+ devDependencies: {'@astryxdesign/cli': '0.7.1'},+ });+ expect(findDeclaringPackage(root)).toEqual({+ dir: root,+ core: '>=0.7.0',+ cli: '0.7.1',+ });+ });+});++describe('lockedVersion', () => {+ it('reads an npm lockfile, member entry first', () => {+ const root = tempDir();+ writeJson(path.join(root, 'package-lock.json'), {+ lockfileVersion: 3,+ packages: {+ 'node_modules/@astryxdesign/core': {version: '0.7.1'},+ 'apps/legacy/node_modules/@astryxdesign/core': {version: '0.6.8'},+ },+ });+ const lock = path.join(root, 'package-lock.json');+ expect(lockedVersion(lock, root, '@astryxdesign/core', '0.7.1')).toBe(+ '0.7.1',+ );+ expect(+ lockedVersion(+ lock,+ path.join(root, 'apps', 'legacy'),+ '@astryxdesign/core',+ '0.6.8',+ ),+ ).toBe('0.6.8');+ });++ it('reads a pnpm lockfile importer, dropping the peer suffix', () => {+ const root = tempDir();+ const lock = path.join(root, 'pnpm-lock.yaml');+ fs.writeFileSync(+ lock,+ [+ "lockfileVersion: '9.0'",+ '',+ 'importers:',+ '',+ ' .:',+ ' dependencies:',+ " '@astryxdesign/core':",+ ' specifier: ^0.6.8',+ ' version: 0.6.8([email protected])',+ '',+ ' apps/web:',+ ' dependencies:',+ " '@astryxdesign/core':",+ ' specifier: 0.7.1',+ ' version: 0.7.1',+ '',+ 'packages:',+ '',+ ].join('\n'),+ );+ expect(lockedVersion(lock, root, '@astryxdesign/core', '^0.6.8')).toBe(+ '0.6.8',+ );+ expect(+ lockedVersion(+ lock,+ path.join(root, 'apps', 'web'),+ '@astryxdesign/core',+ '0.7.1',+ ),+ ).toBe('0.7.1');+ });++ it('reads classic and Berry yarn lockfiles by the declared range', () => {+ const root = tempDir();+ const classic = path.join(root, 'yarn.lock');+ fs.writeFileSync(+ classic,+ [+ '# yarn lockfile v1',+ '',+ '"@astryxdesign/core@^0.6.0":',+ ' version "0.6.8"',+ '',+ '"@astryxdesign/[email protected]":',+ ' version "0.7.1"',+ '',+ ].join('\n'),+ );+ expect(lockedVersion(classic, root, '@astryxdesign/core', '^0.6.0')).toBe(+ '0.6.8',+ );+ const berryDir = tempDir();+ const berry = path.join(berryDir, 'yarn.lock');+ fs.writeFileSync(+ berry,+ [+ '__metadata:',+ ' version: 8',+ '',+ '"@astryxdesign/core@npm:^0.6.8":',+ ' version: 0.6.8',+ ' resolution: "@astryxdesign/core@npm:0.6.8"',+ '',+ ].join('\n'),+ );+ expect(lockedVersion(berry, berryDir, '@astryxdesign/core', '^0.6.8')).toBe(+ '0.6.8',+ );+ });++ it('reads a bun lockfile', () => {+ const root = tempDir();+ const lock = path.join(root, 'bun.lock');+ fs.writeFileSync(+ lock,+ '{\n "lockfileVersion": 1,\n "packages": {\n "@astryxdesign/core": ["@astryxdesign/[email protected]", "", {}, "sha512-x"],\n },\n}\n',+ );+ expect(lockedVersion(lock, root, '@astryxdesign/core', '^0.6.0')).toBe(+ '0.6.8',+ );+ });++ it('finds the lockfile above a workspace member', () => {+ const root = tempDir();+ fs.writeFileSync(+ path.join(root, 'pnpm-lock.yaml'),+ "lockfileVersion: '9.0'\n",+ );+ const member = path.join(root, 'apps', 'web');+ fs.mkdirSync(member, {recursive: true});+ expect(findLockfile(member)).toBe(path.join(root, 'pnpm-lock.yaml'));+ });+});++describe('readReleaseFacts', () => {+ it('reports a fresh clone from its package.json and lockfile', () => {+ const root = project(tempDir(), {+ '@astryxdesign/core': '^0.6.0',+ '@astryxdesign/cli': '^0.6.0',+ });+ writeJson(path.join(root, 'package-lock.json'), {+ lockfileVersion: 3,+ packages: {+ 'node_modules/@astryxdesign/core': {version: '0.6.8'},+ 'node_modules/@astryxdesign/cli': {version: '0.6.8'},+ },+ });+ expect(readReleaseFacts(root)).toMatchObject({+ inProject: true,+ core: null,+ cli: null,+ lockedCoreVersion: '0.6.8',+ lockedCliVersion: '0.6.8',+ });+ });++ it('reports the installed Core and CLI', () => {+ const root = project(tempDir(), {'@astryxdesign/core': '0.7.1'});+ installCore(root, '0.7.1');+ installStandInCli(root, '0.6.8');+ const facts = readReleaseFacts(root);+ expect(facts.core?.version).toBe('0.7.1');+ expect(facts.cli?.version).toBe('0.6.8');+ });++ it('reports a folder with no Astryx as outside a project', () => {+ const root = tempDir();+ writeJson(path.join(root, 'package.json'), {+ name: 'x',+ dependencies: {react: '19'},+ });+ expect(readReleaseFacts(root).inProject).toBe(false);+ });+});diff --git a/packages/cli/foundation/release/refresh-worker.mjs b/packages/cli/foundation/release/refresh-worker.mjsnew file mode 100644index 0000000000..f624e3676e--- /dev/null+++ b/packages/cli/foundation/release/refresh-worker.mjs@@ -0,0 +1,27 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file The background update check, as its own detached process.+ *+ * Started by `maybeStartCheck` (global-state.mjs) with one argument, the+ * per-user configuration folder. It writes nothing to any stream and never+ * reaches a person: it is not a command and takes no options. Its whole job+ * is `runCheck`, which asks the registry for the newest release and installs+ * nothing.+ *+ * @input argv[2]: the per-user configuration folder+ * @output the updated state on disk+ * @position foundation/release — one of the two detached processes the CLI+ * starts; the other is agent-text-worker.mjs.+ */++import {runCheck} from './global-state.mjs';++const stateDir = process.argv[2];+if (stateDir) {+ try {+ runCheck({stateDir});+ } catch {+ // A failed check changes nothing.+ }+}diff --git a/packages/cli/foundation/release/run-context.mjs b/packages/cli/foundation/release/run-context.mjsnew file mode 100644index 0000000000..ee2ea25918--- /dev/null+++ b/packages/cli/foundation/release/run-context.mjs@@ -0,0 +1,149 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Who answered this run: the record behind `meta.answeredBy` and the+ * Core a copy carries for use outside a project (spec AST-081 FR3, FR5).+ *+ * The bin records the choice it made (handoff.mjs) before any command runs.+ * A caller that drives the CLI in-process, such as the test harness or the+ * programmatic API, never went through the bin, so the choice is made here on+ * first use from the working folder, without asking the registry.+ *+ * @input the bin's choice, or the working folder+ * @output `{cli, core, copy}`; the carried Core's folder+ * @position foundation/release — read by jsonOut and by the Core lookups of+ * commands that answer from Core outside a project.+ */++import * as path from 'node:path';+import {fileURLToPath} from 'node:url';+import {chooseRelease, isComputerLevel, runningCopy} from './choose.mjs';+import {progressLine} from './handoff.mjs';+import {isJsonMode} from '../response/json.mjs';+import {cachedRelease, ensureRelease, userCacheDir} from './cache.mjs';+import {readJson, findReadCore, CORE_PACKAGE_NAME} from './project.mjs';++/** The running CLI package's folder. */+const CLI_ROOT = path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ '..',+ '..',+);++/** @type {import('./choose.mjs').ReleaseChoice | null} */+let recorded = null;+/** @type {string | null} */+let recordedFor = null;++/**+ * Record the bin's choice for this process.+ * @param {import('./choose.mjs').ReleaseChoice} choice+ */+export function recordRunChoice(choice) {+ recorded = choice;+ recordedFor = process.cwd();+}++/**+ * The choice that applies to `cwd`: the bin's, else one made now.+ * @param {string} [cwd]+ * @returns {import('./choose.mjs').ReleaseChoice}+ */+export function runChoice(cwd = process.cwd()) {+ if (recorded && recordedFor === path.resolve(cwd)) return recorded;+ try {+ const self = runningCopy(CLI_ROOT);+ const choice = chooseRelease({+ cwd,+ self,+ resolve: () => null,+ computer: isComputerLevel(process.argv.slice(2)),+ });+ if (choice.answer === 'self') return choice;+ // Driven in-process (the programmatic API, a test harness), nothing hands+ // the run off: this copy answers, as the copy that started the run.+ return {+ ...choice,+ copy: choice.inProject ? 'starting' : 'carried',+ answer: 'self',+ version: self.version,+ bin: null,+ unavailable: null,+ };+ } catch {+ return {+ copy: 'carried',+ answer: 'self',+ version: runningCopy(CLI_ROOT).version,+ bin: null,+ coreVersion: null,+ inProject: false,+ unavailable: null,+ };+ }+}++/** The running CLI's version. */+export function cliVersion() {+ return runningCopy(CLI_ROOT).version;+}++/**+ * The Core a copy carries: the `@astryxdesign/core` of its own release, beside+ * the CLI package (a release in the cache, or a package runner that fetched+ * both), else the cached release of the same version. With `fetch`, a copy+ * that carries none installs its release into the cache first.+ *+ * @param {{fetch?: boolean, cacheDir?: string}} [options]+ * @returns {{dir: string | null, unavailable: string | null, version?: string, reason?: string}}+ */+export function carriedCore(options = {}) {+ const {fetch = false, cacheDir = userCacheDir()} = options;+ const version = cliVersion();+ const beside = path.resolve(CLI_ROOT, '..', 'core');+ const besidePkg = readJson(path.join(beside, 'package.json'));+ if (besidePkg?.name === CORE_PACKAGE_NAME && besidePkg.version === version) {+ return {dir: beside, unavailable: null};+ }+ const cached = cachedRelease(version, cacheDir);+ if (cached) return {dir: cached.coreDir, unavailable: null};+ if (!fetch) return {dir: null, unavailable: null};+ const json = isJsonMode() || process.argv.includes('--json');+ const release = ensureRelease(version, {+ cacheDir,+ onProgress: json ? undefined : progressLine,+ });+ return 'coreDir' in release+ ? {dir: release.coreDir, unavailable: null}+ : {+ dir: null,+ unavailable: `Core ${version} could not be installed: ${release.reason}`,+ version,+ reason: release.reason,+ };+}++/**+ * `meta.answeredBy` for this run: the answering CLI's version, the Core the+ * run pairs with (`null` when there is none), and which copy answered.+ * @param {string} [cwd]+ * @returns {{cli: string, core: string | null, copy: 'project' | 'starting' | 'matched' | 'carried' | 'fallback'}}+ */+export function answeredBy(cwd = process.cwd()) {+ const choice = runChoice(cwd);+ const read = findReadCore(cwd);+ let core = read ? read.version : null;+ if (!core && choice.copy !== 'project') {+ const carried = carriedCore();+ core = carried.dir+ ? (readJson(path.join(carried.dir, 'package.json'))?.version ?? null)+ : null;+ }+ return {cli: cliVersion(), core, copy: choice.copy};+}++/** Exported for tests: forget the recorded choice. */+export function _resetRunChoice() {+ recorded = null;+ recordedFor = null;+}diff --git a/packages/cli/foundation/release/update-notice-env.mjs b/packages/cli/foundation/release/update-notice-env.mjsnew file mode 100644index 0000000000..d615eaf0ba--- /dev/null+++ b/packages/cli/foundation/release/update-notice-env.mjs@@ -0,0 +1,39 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file When the environment turns update notices off (spec AST-081 FR6,+ * FR10): the standard `CI` variable, which continuous integration services+ * set, and `NO_UPDATE_NOTIFIER`, the variable command-line tools share to+ * silence update notices (update-notifier, the Vercel CLI). Astryx defines+ * neither; it reads each for its shared meaning only (`spec:AST-017` FR14).+ *+ * @input the environment+ * @output whether to skip the update check and every update notice+ * @position foundation/release — read by global-state.mjs and notices.mjs.+ */++/**+ * Whether `CI` is set to a value that means yes: present, and not empty,+ * `0`, or `false`, as continuous integration detection usually reads it.+ * @param {Record<string, string | undefined>} env+ * @returns {boolean}+ */+export function isCi(env) {+ const value = env.CI;+ return (+ value !== undefined &&+ value !== '' &&+ value !== '0' &&+ value.toLowerCase() !== 'false'+ );+}++/**+ * Whether update checks and notices are off in this environment: in+ * continuous integration, or with `NO_UPDATE_NOTIFIER` set to any value.+ * @param {Record<string, string | undefined>} [env]+ * @returns {boolean}+ */+export function updateNoticesOff(env = process.env) {+ return isCi(env) || env.NO_UPDATE_NOTIFIER !== undefined;+}diff --git a/packages/cli/foundation/response/base.d.ts b/packages/cli/foundation/response/base.d.tsindex eafaf16282..0f816420eb 100644--- a/packages/cli/foundation/response/base.d.ts+++ b/packages/cli/foundation/response/base.d.ts@@ -45,8 +45,9 @@ export interface CLIUnsupportedError {/*** A success response: a `type` discriminator, the `package` that owns what the- * response is about, its `data` payload, and an optional `meta` sidecar- * (emitted as a sibling of `data`, never merged in). `--json` prints it with+ * response is about, its `data` payload, and an optional `meta` object+ * (emitted as a sibling of `data`, never merged in) that carries+ * `answeredBy` and fields such as `deprecations`. `--json` prints it with* `apiVersion` added (see `parseResponse`).** `package` is present when the response is about one thing: one component,@@ -56,11 +57,33 @@ export interface CLIUnsupportedError {* Structural by design — there is no central union of every response `type`.* A specific command narrows `data` via its own return type.*/+/**+ * Which copy of the CLI answered a run (spec AST-081 FR5): carried in `meta`+ * on every successful machine-readable result of a release that has it.+ * - `project`: the project's own CLI.+ * - `starting`: the copy that started the run, in a project with no CLI of+ * its own.+ * - `matched`: the release equal to the project's Core, when the project's+ * own CLI cannot start, from the per-user cache or the copy that started+ * the run.+ * - `carried`: outside a project, the copy that started the run, with the Core+ * it carries.+ * - `fallback`: the matched release could not be obtained, so the copy that+ * started the run answered instead.+ */+export interface AnsweredBy {+ /** The answering CLI's version. */+ cli: string;+ /** The Core the run pairs with, or `null` when there is none. */+ core: string | null;+ copy: 'project' | 'starting' | 'matched' | 'carried' | 'fallback';+}+export interface CLIResponse {type: string;package?: string;data: unknown;- meta?: Record<string, unknown>;+ meta?: {answeredBy?: AnsweredBy} & Record<string, unknown>;}/** Wrap any response type to include possible error shapes. */diff --git a/packages/cli/foundation/response/error-codes.doc.mjs b/packages/cli/foundation/response/error-codes.doc.mjsindex da31640431..10e242fa31 100644--- a/packages/cli/foundation/response/error-codes.doc.mjs+++ b/packages/cli/foundation/response/error-codes.doc.mjs@@ -277,5 +277,17 @@ export const doc = {description:'Recorded in the debug log, never printed: the process was ended by a signal (Ctrl-C, SIGTERM) before the command reached a terminal path.',},++ // Global mode+ {+ value: 'ERR_VERSIONS_UNAVAILABLE',+ description:+ 'Nothing could answer this run, and nothing was written: the project\'s own CLI could not start and nothing else could answer, or the Core a command needs outside a project could not be installed.',+ },+ {+ value: 'ERR_PROJECT_REQUIRED',+ description:+ 'The command needs a project (an app with Astryx installed, or an integration package) and was run outside one. Nothing was written.',+ },],};diff --git a/packages/cli/foundation/response/error-codes.mjs b/packages/cli/foundation/response/error-codes.mjsindex 7ed88e3850..9acfe98350 100644--- a/packages/cli/foundation/response/error-codes.mjs+++ b/packages/cli/foundation/response/error-codes.mjs@@ -88,6 +88,8 @@* | 'ERR_LAYOUT_INVALID'* | 'ERR_UNCLASSIFIED_EXIT'* | 'ERR_SIGNAL_TERMINATED'+ * | 'ERR_VERSIONS_UNAVAILABLE'+ * | 'ERR_PROJECT_REQUIRED'* )} ErrorCode*/@@ -236,6 +238,21 @@ export const ERROR_CODES = Object.freeze({* command never reached a terminal path of its own.*/ERR_SIGNAL_TERMINATED: 'ERR_SIGNAL_TERMINATED',++ // ── Global mode (which release answers) ──────────────────────────+ /**+ * The CLI release a run needs could not run: the release that matches the+ * project's Core is not installed and could not be fetched (offline, or the+ * registry lacks it), the project's own CLI could not be started, or a copy+ * that carries no Core could not install its release's Core outside a+ * project. Nothing was written.+ */+ ERR_VERSIONS_UNAVAILABLE: 'ERR_VERSIONS_UNAVAILABLE',+ /**+ * The command needs a project (an app with Astryx installed, or an+ * integration package) and was run outside one. Nothing was written.+ */+ ERR_PROJECT_REQUIRED: 'ERR_PROJECT_REQUIRED',});/**diff --git a/packages/cli/foundation/response/error-codes.test.mjs b/packages/cli/foundation/response/error-codes.test.mjsindex 2081cac252..2b574dc70e 100644--- a/packages/cli/foundation/response/error-codes.test.mjs+++ b/packages/cli/foundation/response/error-codes.test.mjs@@ -113,6 +113,7 @@ describe('error codes: shipped set', () => {'ERR_NO_SOURCE','ERR_PALETTE_GENERATION','ERR_PATH_TRAVERSAL',+ 'ERR_PROJECT_REQUIRED','ERR_SIGNAL_TERMINATED','ERR_THEME_INVALID','ERR_THEME_LOAD',@@ -133,6 +134,7 @@ describe('error codes: shipped set', () => {'ERR_UNKNOWN_THEME','ERR_UNKNOWN_TOPIC','ERR_VERSION_DETECT',+ 'ERR_VERSIONS_UNAVAILABLE','ERR_WRITE_FAILED',];diff --git a/packages/cli/foundation/response/json-contract.test.mjs b/packages/cli/foundation/response/json-contract.test.mjsindex a1dff0338e..0de7afb71f 100644--- a/packages/cli/foundation/response/json-contract.test.mjs+++ b/packages/cli/foundation/response/json-contract.test.mjs@@ -70,13 +70,18 @@ describe('json envelope shape', () => {expect(env.apiVersion).toBe(API_VERSION);expect(env.type).toBe('docs.list');expect(env.data).toEqual([{name: 'Button'}]);- expect('meta' in env).toBe(false);+ // The only meta every result carries names who answered (AST-081 FR5).+ expect(Object.keys(env.meta)).toEqual(['answeredBy']);+ const {cli, core, copy} = env.meta.answeredBy;+ expect(typeof cli).toBe('string');+ expect(core === null || typeof core === 'string').toBe(true);+ expect(['project', 'matched', 'carried']).toContain(copy);});it('jsonOut attaches optional meta as a sibling of data', () => {jsonOut({type: 'discover.list', data: [], meta: {configured: false}});const env = JSON.parse(logs[0]);- expect(env.meta).toEqual({configured: false});+ expect(env.meta).toEqual({configured: false, answeredBy: expect.any(Object)});expect(env.data).toEqual([]);});diff --git a/packages/cli/foundation/response/json.mjs b/packages/cli/foundation/response/json.mjsindex 47f74f20b0..55b1f2920e 100644--- a/packages/cli/foundation/response/json.mjs+++ b/packages/cli/foundation/response/json.mjs@@ -30,6 +30,7 @@*/import {ERROR_CODES, isErrorCode} from './error-codes.mjs';import {recordEnvelope, setOutcome} from '../debug/index.mjs';+import {answeredBy} from '../release/run-context.mjs';export const API_VERSION = 1;@@ -101,7 +102,9 @@ export function jsonOut(response) {const envelope = {apiVersion: API_VERSION, type: response.type};if (response.package !== undefined) envelope.package = response.package;envelope.data = response.data;- if (response.meta !== undefined) envelope.meta = response.meta;+ // Every successful result names the release that answered (spec AST-081+ // FR5): the CLI, the Core it paired with, and which copy it was.+ envelope.meta = {...(response.meta ?? {}), answeredBy: answeredBy()};// Serialize BEFORE marking handled. If JSON.stringify throws (a circular// reference or a BigInt in `data` — an author bug in a command's return// value), the `__xdsJsonHandled` flag must stay unset so the bin errordiff --git a/packages/cli/foundation/response/response-types.doc.mjs b/packages/cli/foundation/response/response-types.doc.mjsindex 75e8a6bd2e..7de1a7110a 100644--- a/packages/cli/foundation/response/response-types.doc.mjs+++ b/packages/cli/foundation/response/response-types.doc.mjs@@ -32,6 +32,11 @@ export const doc = {description:'The removal receipt — returned when --remove-agents is set: `data.removed` is true when a managed agent-docs block was found and removed, and false when there was none to remove.',},+ {+ value: 'init.user',+ description:+ 'The computer-level agent text receipt — returned when --user is set: `data.files`, one `{path, action, reason?}` per path acted on, the skill file first and then each link to its folder (action `written` | `linked` | `unchanged` | `removed` | `absent` | `kept`; `reason` only on `kept`: `edited` when a person changed the text, `not-astryx` when Astryx did not write it), `data.command` (the command the text names), and `data.warnings`.',+ },// component{value: 'component.list',@@ -139,7 +144,7 @@ export const doc = {{value: 'search',description:- 'The echoed query, `matchCount` (total matches, before `limit`), and results, a ranked SearchResultEntry[] bounded by `limit`: each {domain, name, package, score, reason, description, command} (package is the npm package that owns the result), plus import (components, hooks), title, parent (the command that opens the level above), and, for a hit on one section, section (docs), or displayName and kind (templates).',+ 'The echoed query, `matchCount` (total matches, before `limit`), and results, a ranked SearchResultEntry[] bounded by `limit`: each {domain, name, package, score, reason, description, command} (package is the npm package that owns the result), plus import (components, hooks), title, parent (the command that opens the level above), and, for a hit on one section, section (docs), or displayName and kind (templates). When a search with no `type` could not obtain @astryxdesign/core, `meta.partial` is {skipped, reason}: the domains it skipped (component, hook, template) and why.',},// build@@ -296,7 +301,7 @@ export const doc = {{value: 'manifest',description:- 'The CLI capability manifest: name, version, apiVersion, description, globalOptions, commands (each name, description, arguments, options, json, aliases?, responseTypes?, examples?, exitCodes? as [{code, when}], subcommands?), jsonSupported, and the flat responseTypes index.',+ "The CLI capability manifest: name, version, apiVersion, description, globalOptions, commands (each name, description, arguments, options, json, aliases?, responseTypes?, examples?, exitCodes? as [{code, when}], outsideProject? (same, refuse, or own; absent on a group), subcommands?), jsonSupported, globalMode ({docs, summary}: what a run may do beyond its command, such as the hand-off to the project's own CLI, the daily update check, and the agent skill file, and the docs topic that explains it), and the flat responseTypes index.",},// help and version, which no single command owns@@ -333,7 +338,7 @@ export const doc = {{value: 'integration.validate',description:- 'The validation result: validated (false when nothing was validated: with no package.json the issues list carries one no_package error so the command exits 1, and with a package.json but no integration manifest the issues list is empty and proves nothing), the package name and version (both null when validated is false) plus issues, an AstryxIntegrationIssue[] of {code, severity: warning | error, message, fix?, file?, line?} (fix: the change that resolves it; file and line: where, relative to the package). When the manifest loads, docTypes checks each doc against its published authoring type: status (checked | skipped), reason, typescript, docs, findings (all warnings, each naming the field and a fix), unchecked, and fixtures (test fixture docs not checked).',+ 'The validation result: validated (false when nothing was validated: with no package.json the issues list carries one no_package error so the command exits 1, and with a package.json but no integration manifest the issues list is empty and proves nothing), the package name and version (both null when validated is false) plus issues, an AstryxIntegrationIssue[] of {code, severity: warning | error, message, fix?, file?, line?} (fix: the change that resolves it; file and line: where, relative to the package), and notes when there are any: {code, message} information that fails nothing, such as invalid_cli_command for a malformed cliCommand. When the manifest loads, docTypes checks each doc against its published authoring type: status (checked | skipped), reason, typescript, docs, findings (all warnings, each naming the field and a fix), unchecked, and fixtures (test fixture docs not checked).',},{value: 'integration.template-conflicts',diff --git a/packages/cli/foundation/response/response-types.doc.test.mjs b/packages/cli/foundation/response/response-types.doc.test.mjsindex 33e98b0df0..48333595cc 100644--- a/packages/cli/foundation/response/response-types.doc.test.mjs+++ b/packages/cli/foundation/response/response-types.doc.test.mjs@@ -12,6 +12,7 @@ import * as path from 'node:path';import {describe, it, expect} from 'vitest';import {doc} from './response-types.doc.mjs';import {runCli} from '../../test-utils/run-cli.mjs';+import {linkThisCliAsProjectCli} from '../../test-utils/release-fixtures.mjs';/** @param {string} type */const describedAs = type =>@@ -112,6 +113,51 @@ describe('response-types EnumDoc names every field', () => {);});+ it('search, including meta.partial when Core cannot be obtained', async () => {+ const empty = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-rt-partial-'));+ // The project's own CLI answers and no Core is installed: an open search+ // answers from docs and themes and says what it skipped.+ linkThisCliAsProjectCli(empty);+ try {+ const res = await data(['search', 'button'], empty);+ expect(res.meta.partial).toBeDefined();+ expectNamed('search', ['meta', 'partial', ...fieldsOf(res.meta.partial)]);+ for (const domain of res.meta.partial.skipped) {+ expectNamed('search', [domain]);+ }+ } finally {+ fs.rmSync(empty, {recursive: true, force: true});+ }+ });++ it('init.user: every row field, action, and kept reason the receipt type declares', () => {+ const types = fs.readFileSync(+ new URL('../../api/init/init.type.mjs', import.meta.url),+ 'utf8',+ );+ /** The quoted members of the union a typedef or property declares. */+ const union = (/** @type {RegExp} */ re) =>+ [...(types.match(re)?.[1] ?? '').matchAll(/'([^']+)'/gu)].map(m => m[1]);+ const actions = union(/@typedef \{([^}]*)\} InitUserAction/u);+ const reasons = union(/@property \{([^}]*)\} \[reason\]/u);+ expect(actions).toContain('linked');+ expect(reasons.length).toBeGreaterThan(0);+ const rowFields = [+ ...types+ .split('@typedef {object} InitUserFile')[1]+ .split('*/')[0]+ .matchAll(/@property \{[^}]*\} \[?(\w+)/gu),+ ].map(m => m[1]);+ expectNamed('init.user', [+ 'files',+ 'command',+ 'warnings',+ ...rowFields,+ ...actions,+ ...reasons,+ ]);+ });+it('build.kit, including the hint a thin kit carries', async () => {const res = await data(['build', 'zzqx-nothing-matches']);expect(res.type).toBe('build.kit');diff --git a/packages/cli/foundation/response/response.doc.mjs b/packages/cli/foundation/response/response.doc.mjsindex aa1a61600f..173f3976a5 100644--- a/packages/cli/foundation/response/response.doc.mjs+++ b/packages/cli/foundation/response/response.doc.mjs@@ -21,11 +21,11 @@ export const doc = {fields: [{name: 'Success envelope',- type: '{ apiVersion: number; type: string; package?: string; data: unknown; meta?: Record<string, unknown> }',+ type: '{ apiVersion: number; type: string; package?: string; data: unknown; meta?: { answeredBy?: { cli: string; core: string | null; copy: "project" | "starting" | "matched" | "carried" | "fallback" } } & Record<string, unknown> }',description:'Emitted for every successful command in --json mode: a type ' +'discriminator, the package that owns what the response is about, ' +- 'its data payload, and an optional meta sidecar.',+ 'its data payload, and an optional meta object beside data.',fields: [{name: 'apiVersion',@@ -65,7 +65,7 @@ export const doc = {name: 'meta',type: 'Record<string, unknown>',description:- 'Optional sidecar, emitted as a sibling of data (never merged in). A `deprecations` field is an array of `{id, replacements}` entries; each stable lifecycle id names the replacement commands without changing the command data.',+ "Optional, emitted as a sibling of data (never merged in). `answeredBy` is on every successful result of a release that has it: `{cli, core, copy}`, the answering CLI version, the Core it pairs with (or null), and which copy answered: `project` (the project's own CLI), `starting` (the copy that started the run, in a project with no CLI of its own), `matched` (the release equal to the project's Core, when the project's own CLI cannot start), `carried` (outside a project), or `fallback` (the matched release could not be obtained, so the starting copy answered). A `deprecations` field is an array of `{id, replacements}` entries; each stable lifecycle id names the replacement commands without changing the command data. Other fields may be added (spec:AST-017 FR13).",},],},diff --git a/packages/cli/foundation/xle/browser-imports.test.mjs b/packages/cli/foundation/xle/browser-imports.test.mjsnew file mode 100644index 0000000000..c453313f2f--- /dev/null+++ b/packages/cli/foundation/xle/browser-imports.test.mjs@@ -0,0 +1,74 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * `@astryxdesign/cli/xle` (browser.mjs) runs in browsers: nothing it imports,+ * directly or through other modules, may load a Node built-in.+ */++import {describe, expect, it} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';++const ENTRY = path.join(import.meta.dirname, 'browser.mjs');++/** Every module specifier a file imports or re-exports, static or dynamic. */+const SPECIFIER =+ /(?:\bimport\s*(?:[\w*{}\s,$]+\s*from\s*)?|\bexport\s*[\w*{}\s,$]+\s*from\s*|\bimport\s*\(\s*)['"]([^'"]+)['"]/gu;++/**+ * The files `entry` reaches through relative imports, with the bare and+ * `node:` specifiers each one names.+ * @param {string} entry+ * @returns {Map<string, string[]>}+ */+function importGraph(entry) {+ /** @type {Map<string, string[]>} */+ const graph = new Map();+ const queue = [entry];+ while (queue.length > 0) {+ const file = /** @type {string} */ (queue.pop());+ if (graph.has(file)) continue;+ // Comments hold JSDoc type imports (`import('./x').T`), which load nothing.+ const source = fs+ .readFileSync(file, 'utf8')+ .replace(/\/\*[\s\S]*?\*\//gu, '')+ .replace(/^\s*\/\/.*$/gmu, '');+ /** @type {string[]} */+ const external = [];+ for (const [, spec] of source.matchAll(SPECIFIER)) {+ if (spec.startsWith('.')) {+ queue.push(path.resolve(path.dirname(file), spec));+ } else {+ external.push(spec);+ }+ }+ graph.set(file, external);+ }+ return graph;+}++describe('the xle browser export', () => {+ it('reaches no Node built-in and no AsyncLocalStorage', () => {+ const graph = importGraph(ENTRY);+ // The walk reaches the parser, validator and expander.+ expect(graph.size).toBeGreaterThan(3);+ const builtins = [...graph].flatMap(([file, specs]) =>+ specs+ .filter(+ spec =>+ spec.startsWith('node:') ||+ /^(?:fs|path|os|child_process|async_hooks|url)$/u.test(spec),+ )+ .map(+ spec => `${path.relative(import.meta.dirname, file)} imports ${spec}`,+ ),+ );+ expect(builtins).toEqual([]);+ const storage = [...graph.keys()]+ .filter(file =>+ fs.readFileSync(file, 'utf8').includes('AsyncLocalStorage'),+ )+ .map(file => path.relative(import.meta.dirname, file));+ expect(storage).toEqual([]);+ });+});diff --git a/packages/cli/scripts/generate-cli-readme.mjs b/packages/cli/scripts/generate-cli-readme.mjsindex 5522b354a5..638b8c4bb4 100644--- a/packages/cli/scripts/generate-cli-readme.mjs+++ b/packages/cli/scripts/generate-cli-readme.mjs@@ -74,11 +74,32 @@ function replaceBlock(content, name, block) {return content.replace(re, `${begin}\n\n${block}\n\n${end}`);}+/**+ * A command's `outsideProject` value for the commands table. A group that+ * only holds subcommands declares none, so it shows its subcommands' value when+ * they agree, and `by subcommand` when they differ.+ * @param {any} command a manifest command+ * @returns {string}+ */+function outsideProject(command) {+ if (command.outsideProject) return `\`${command.outsideProject}\``;+ /** @type {Set<string>} */+ const values = new Set();+ const walk = (/** @type {any[]} */ subs) => {+ for (const sub of subs) {+ if (sub.outsideProject) values.add(sub.outsideProject);+ walk(sub.subcommands ?? []);+ }+ };+ walk(command.subcommands ?? []);+ return values.size === 1 ? `\`${[...values][0]}\`` : 'by subcommand';+}+async function build() {const manifest = getManifest();const commandRows = manifest.commands.filter((/** @type {any} */ c) => c.name !== 'manifest')- .map((/** @type {any} */ c) => [`\`${c.name}\``, c.description]);+ .map((/** @type {any} */ c) => [`\`${c.name}\``, c.description, outsideProject(c)]);const errorCodes = await loadDoc('foundation/response/error-codes.doc.mjs');const errorRows = errorCodes.members.map((/** @type {any} */ m) => [`\`${m.value}\``, m.description]);@@ -87,7 +108,11 @@ async function build() {const rtRows = responseTypes.members.map((/** @type {any} */ m) => [`\`${m.value}\``, m.description]);let content = fs.readFileSync(README, 'utf8');- content = replaceBlock(content, 'commands', table(['Command', 'Description'], commandRows));+ content = replaceBlock(+ content,+ 'commands',+ table(['Command', 'Description', 'Outside a project'], commandRows),+ );content = replaceBlock(content, 'error-codes', table(['Code', 'Meaning'], errorRows));content = replaceBlock(content, 'response-types', table(['Type', 'What `data` carries'], rtRows));diff --git a/packages/cli/scripts/postinstall.mjs b/packages/cli/scripts/postinstall.mjsindex c5eca8b1a9..3c297ebe37 100644--- a/packages/cli/scripts/postinstall.mjs+++ b/packages/cli/scripts/postinstall.mjs@@ -24,7 +24,7 @@ import {fileURLToPath, pathToFileURL} from 'node:url';// is safe to load at install time.import {shouldNudge,- SETUP_NUDGE,+ setupNudge,} from '../foundation/agent-docs/agent-doc-state.mjs';const HERE = fileURLToPath(import.meta.url);@@ -50,6 +50,25 @@ async function projectIsSetUp(root) {}}+/**+ * The stem the CLI's picker prints for this project. At install time no+ * integration is loaded, so this is the package-manager guess. Falls back to+ * the contract's scoped form when the picker cannot load.+ * @param {string} root+ * @returns {Promise<string | undefined>}+ */+export async function cliInvocation(root) {+ try {+ // Node builtins only, like the contract.+ const {getCliInvocation} = await import(+ '../foundation/env/package-manager.mjs'+ );+ return getCliInvocation(root);+ } catch {+ return undefined;+ }+}+async function main() {const root = process.env.INIT_CWD || process.cwd();const nudge = shouldNudge({@@ -58,7 +77,7 @@ async function main() {isSetUp: await projectIsSetUp(root),});if (nudge) {- process.stdout.write(SETUP_NUDGE);+ process.stdout.write(setupNudge(await cliInvocation(root)));}}diff --git a/packages/cli/test-utils/global-local-fixtures.mjs b/packages/cli/test-utils/global-local-fixtures.mjsnew file mode 100644index 0000000000..83f6e5e216--- /dev/null+++ b/packages/cli/test-utils/global-local-fixtures.mjs@@ -0,0 +1,356 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Fixtures for the global and project table's tests (spec AST-081+ * FR11): real copies of this CLI, packed the way it is published and placed+ * in every install layout the table names, and a package registry that runs+ * inside the test process.+ *+ * - `packedCli()` packs this package once per process (`npm pack`), and+ * `extractTarball` unpacks it with no external tool, so the copies hold+ * exactly the published files.+ * - `placeCli(dir, version)` puts a copy at `dir`, labeled `version`: every+ * file is a hard link to the unpacked package except a rewritten+ * package.json, and its `node_modules` links to this package's installed+ * dependencies, so a copy costs almost nothing and runs as the release it+ * is labeled.+ * - `globalCli(layout, version)` places one where a package manager or a Node+ * version manager puts a global install, with an `astryx` command for the+ * search path.+ * - `seedPackedRelease(cacheDir, version)` puts one in the per-user release+ * cache with the marker an install leaves.+ * - `startRegistry({latest})` answers package questions for the CLI and Core+ * from inside this process, the way the cross-platform smoke workflow does,+ * with no network.+ *+ * @position packages/cli/test-utils — used by test/global-local.test.mjs.+ */++import * as fs from 'node:fs';+import * as http from 'node:http';+import * as os from 'node:os';+import * as path from 'node:path';+import * as zlib from 'node:zlib';+import {createHash} from 'node:crypto';+import {spawnSync} from 'node:child_process';+import {fileURLToPath} from 'node:url';+import {releaseTree} from '../foundation/release/cache.mjs';+import {installCore, tempDir, writeJson} from './release-fixtures.mjs';++/** This CLI package's folder. */+export const CLI_DIR = fileURLToPath(new URL('..', import.meta.url));++/**+ * Unpack a `.tgz` written by `npm pack` into `dest`, dropping its leading+ * `package/` folder.+ * @param {string} file+ * @param {string} dest+ */+export function extractTarball(file, dest) {+ const buf = zlib.gunzipSync(fs.readFileSync(file));+ let off = 0;+ /** @type {string | null} */+ let longName = null;+ while (off + 512 <= buf.length) {+ const header = buf.subarray(off, off + 512);+ if (header.every(b => b === 0)) break;+ const field = (/** @type {number} */ start, /** @type {number} */ len) =>+ header+ .subarray(start, start + len)+ .toString('utf8')+ .replace(/\0.*$/su, '');+ let name = field(0, 100);+ const prefix = field(345, 155);+ if (prefix) name = `${prefix}/${name}`;+ const size = parseInt(field(124, 12).trim() || '0', 8);+ const type = String.fromCharCode(header[156]);+ const body = buf.subarray(off + 512, off + 512 + size);+ off += 512 + Math.ceil(size / 512) * 512;+ if (type === 'x') {+ const match = /\d+ path=([^\n]+)\n/u.exec(body.toString('utf8'));+ if (match) longName = match[1];+ continue;+ }+ if (type === 'L') {+ longName = body.toString('utf8').replace(/\0.*$/su, '');+ continue;+ }+ if (longName) name = longName;+ longName = null;+ const rel = name.replace(/^[^/]+\//u, '');+ if (!rel || rel.split('/').includes('..')) continue;+ const target = path.join(dest, ...rel.split('/'));+ if (type === '5') {+ fs.mkdirSync(target, {recursive: true});+ } else if (type === '0' || type === '\0') {+ fs.mkdirSync(path.dirname(target), {recursive: true});+ fs.writeFileSync(target, body);+ if (/\.(?:mjs|cjs|js)$/u.test(rel) && rel.includes('/bin/')) {+ fs.chmodSync(target, 0o755);+ }+ }+ }+}++/** @type {string | null} */+let packed = null;++/**+ * This CLI, packed once per process and unpacked.+ * @returns {string} the unpacked package folder+ */+export function packedCli() {+ if (packed) return packed;+ const out = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-packed-cli-'));+ const result = spawnSync(+ process.platform === 'win32' ? 'npm.cmd' : 'npm',+ ['pack', '--ignore-scripts', '--json', '--pack-destination', out],+ {cwd: CLI_DIR, encoding: 'utf8', shell: process.platform === 'win32'},+ );+ if (result.status !== 0) {+ throw new Error(`npm pack failed: ${result.stderr}`);+ }+ const [{filename}] = JSON.parse(result.stdout);+ const dir = path.join(out, 'package');+ extractTarball(path.join(out, filename), dir);+ packed = dir;+ return dir;+}++/**+ * Hard-link every file under `from` into `to`, copying across devices.+ * @param {string} from+ * @param {string} to+ */+function linkTree(from, to) {+ fs.mkdirSync(to, {recursive: true});+ for (const entry of fs.readdirSync(from, {withFileTypes: true})) {+ const src = path.join(from, entry.name);+ const dst = path.join(to, entry.name);+ if (entry.isDirectory()) linkTree(src, dst);+ else {+ try {+ fs.linkSync(src, dst);+ } catch {+ fs.copyFileSync(src, dst);+ }+ }+ }+}++/**+ * Put a copy of the packed CLI at `dir`, labeled `version`.+ * @param {string} dir the package folder to create+ * @param {string} version+ * The copy leaves out the global copy's background Core step+ * (core-worker.mjs), as a release that predates it does, so no test's run+ * starts a download behind its back; `coreStep: true` keeps it.+ * @param {{engines?: Record<string, string>, coreStep?: boolean}} [options]+ * @returns {{dir: string, bin: string}}+ */+export function placeCli(dir, version, options = {}) {+ const from = packedCli();+ linkTree(from, dir);+ if (!options.coreStep) {+ fs.rmSync(path.join(dir, 'foundation', 'release', 'core-worker.mjs'), {+ force: true,+ });+ }+ const pkgFile = path.join(dir, 'package.json');+ const pkg = JSON.parse(fs.readFileSync(pkgFile, 'utf8'));+ fs.unlinkSync(pkgFile);+ fs.writeFileSync(+ pkgFile,+ `${JSON.stringify({...pkg, version, ...(options.engines ? {engines: options.engines} : {})}, null, 2)}\n`,+ );+ fs.symlinkSync(+ path.join(CLI_DIR, 'node_modules'),+ path.join(dir, 'node_modules'),+ process.platform === 'win32' ? 'junction' : 'dir',+ );+ return {dir, bin: path.join(dir, 'clients', 'cli', 'bin', 'astryx.mjs')};+}++/**+ * Where each layout keeps a global install, relative to a home folder: the+ * package folder and the folder its `astryx` command is in.+ * @type {Record<string, {pkg: string[], bin: string[]}>}+ */+const LAYOUTS = {+ npm: {+ pkg: ['.npm-global', 'lib', 'node_modules', '@astryxdesign', 'cli'],+ bin: ['.npm-global', 'bin'],+ },+ pnpm: {+ pkg: [+ '.local',+ 'share',+ 'pnpm',+ 'global',+ '5',+ 'node_modules',+ '@astryxdesign',+ 'cli',+ ],+ bin: ['.local', 'share', 'pnpm'],+ },+ nvm: {+ pkg: [+ '.nvm',+ 'versions',+ 'node',+ 'v22.13.0',+ 'lib',+ 'node_modules',+ '@astryxdesign',+ 'cli',+ ],+ bin: ['.nvm', 'versions', 'node', 'v22.13.0', 'bin'],+ },+ fnm: {+ pkg: [+ '.local',+ 'share',+ 'fnm',+ 'node-versions',+ 'v24.0.0',+ 'installation',+ 'lib',+ 'node_modules',+ '@astryxdesign',+ 'cli',+ ],+ bin: [+ '.local',+ 'share',+ 'fnm',+ 'node-versions',+ 'v24.0.0',+ 'installation',+ 'bin',+ ],+ },+ volta: {+ pkg: [+ '.volta',+ 'tools',+ 'image',+ 'packages',+ '@astryxdesign',+ 'cli',+ 'lib',+ 'node_modules',+ '@astryxdesign',+ 'cli',+ ],+ bin: ['.volta', 'bin'],+ },+};++/**+ * A global install of the packed CLI in `layout`, under `root`, with its+ * `astryx` command linked into its bin folder.+ * @param {keyof typeof LAYOUTS} layout+ * @param {string} version+ * @param {{root?: string, engines?: Record<string, string>, coreStep?: boolean}} [options]+ * @returns {{dir: string, bin: string, binDir: string}}+ */+export function globalCli(layout, version, options = {}) {+ const root = options.root ?? tempDir(`global-${layout}`);+ const {pkg, bin} = LAYOUTS[layout];+ const placed = placeCli(path.join(root, ...pkg), version, options);+ const binDir = path.join(root, ...bin);+ fs.mkdirSync(binDir, {recursive: true});+ fs.symlinkSync(placed.bin, path.join(binDir, 'astryx'));+ return {...placed, binDir};+}++/**+ * A verified release of the packed CLI in a cache folder, the way an install+ * leaves it, with a stand-in Core.+ * @param {string} cacheDir the `astryx` cache folder+ * @param {string} version+ * @param {{engines?: Record<string, string>}} [options]+ * @returns {{dir: string, bin: string}}+ */+export function seedPackedRelease(cacheDir, version, options = {}) {+ const dir = path.join(cacheDir, 'releases', version);+ writeJson(path.join(dir, 'package.json'), {+ name: 'astryx-release',+ private: true,+ });+ const cli = placeCli(+ path.join(dir, 'node_modules', '@astryxdesign', 'cli'),+ version,+ options,+ );+ installCore(dir, version);+ /** @type {Record<string, string>} */+ const files = {};+ for (const rel of [+ 'node_modules/@astryxdesign/cli/package.json',+ 'node_modules/@astryxdesign/core/package.json',+ path.relative(dir, cli.bin).split(path.sep).join('/'),+ ]) {+ files[rel] = createHash('sha256')+ .update(fs.readFileSync(path.join(dir, rel)))+ .digest('hex');+ }+ writeJson(path.join(dir, 'release.json'), {+ version,+ verifiedAt: 'test',+ files,+ tree: releaseTree(dir),+ });+ return {dir, bin: cli.bin};+}++/**+ * A package registry inside this process: packuments for the CLI and Core+ * with the given versions and `latest` tag; every other request is not+ * found.+ * @param {{versions: string[], latest: string}} options+ * @returns {Promise<{url: string, close: () => Promise<void>}>}+ */+export function startRegistry({versions, latest}) {+ const server = http.createServer((req, res) => {+ const url = decodeURIComponent((req.url ?? '').split('?')[0]);+ const match = /^\/(@astryxdesign\/(?:cli|core))(?:\/([^/]+))?$/u.exec(url);+ if (!match) {+ res.writeHead(404, {'content-type': 'application/json'});+ res.end('{}');+ return;+ }+ const [, name, tag] = match;+ const self = `http://127.0.0.1:${/** @type {any} */ (server.address()).port}`;+ const packument = {+ name,+ 'dist-tags': {latest},+ versions: Object.fromEntries(+ versions.map(v => [+ v,+ {+ name,+ version: v,+ dist: {+ tarball: `${self}/${name}/-/${name.split('/')[1]}-${v}.tgz`,+ },+ },+ ]),+ ),+ };+ const body = tag+ ? packument.versions[packument['dist-tags'][tag] ?? tag]+ : packument;+ res.writeHead(body ? 200 : 404, {'content-type': 'application/json'});+ res.end(JSON.stringify(body ?? {}));+ });+ return new Promise(resolve => {+ server.listen(0, '127.0.0.1', () => {+ resolve({+ url: `http://127.0.0.1:${/** @type {any} */ (server.address()).port}/`,+ close: () => new Promise(done => server.close(() => done())),+ });+ });+ });+}diff --git a/packages/cli/test-utils/release-fixtures.mjs b/packages/cli/test-utils/release-fixtures.mjsnew file mode 100644index 0000000000..fd39dcad4e--- /dev/null+++ b/packages/cli/test-utils/release-fixtures.mjs@@ -0,0 +1,202 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Fixture builders shared by the global-mode tests: projects with an+ * installed Core and CLI of any version, and stand-in CLI packages whose+ * `astryx` command reports what it received.+ */++import {createHash} from 'node:crypto';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {releaseTree} from '../foundation/release/cache.mjs';++/** @type {string[]} */+const made = [];++/**+ * A fresh temporary folder, removed by {@link cleanupFixtures}.+ * @param {string} [label]+ * @returns {string}+ */+export function tempDir(label = 'release') {+ const dir = fs.realpathSync(+ fs.mkdtempSync(path.join(os.tmpdir(), `astryx-${label}-`)),+ );+ made.push(dir);+ return dir;+}++/** Remove every folder {@link tempDir} made. */+export function cleanupFixtures() {+ for (const dir of made.splice(0)) {+ // A global copy's background Core step, started as a run ends, may still+ // be writing its record into a test's cache folder: retry until it is done.+ fs.rmSync(dir, {+ recursive: true,+ force: true,+ maxRetries: 20,+ retryDelay: 100,+ });+ }+}++/**+ * Write a JSON file, creating its folder.+ * @param {string} file+ * @param {unknown} value+ */+export function writeJson(file, value) {+ fs.mkdirSync(path.dirname(file), {recursive: true});+ fs.writeFileSync(file, `${JSON.stringify(value, null, 2)}\n`);+}++/**+ * The source of a stand-in `astryx` command. It prints, as one JSON line on+ * stdout, the version it was built as, its arguments, its working folder,+ * whatever arrived on stdin, and its stderr marker, then exits with the+ * status `--exit <n>` names (0 by default). `--version` prints the version+ * alone, as a real CLI does.+ * @param {string} version+ * @returns {string}+ */+export function standInBin(version) {+ return `#!/usr/bin/env node+const args = process.argv.slice(2);+if (args[0] === '--version') { console.log(${JSON.stringify(version)}); process.exit(0); }+let stdin = '';+try { if (!process.stdin.isTTY) stdin = require('node:fs').readFileSync(0, 'utf-8'); } catch {}+console.log(JSON.stringify({version: ${JSON.stringify(version)}, args, cwd: process.cwd(), stdin}));+console.error('stand-in ' + ${JSON.stringify(version)});+const at = args.indexOf('--exit');+process.exit(at === -1 ? 0 : Number(args[at + 1]));+`;+}++/**+ * Install a stand-in `@astryxdesign/cli` of `version` into `dir`'s+ * node_modules (or at `dir` itself with `{at: true}`).+ * @param {string} dir+ * @param {string} version+ * @param {{bin?: boolean, engines?: Record<string, string>}} [options]+ * `bin: false` leaves the command out; `engines` is written as declared+ * @returns {string} the package folder+ */+export function installStandInCli(dir, version, options = {}) {+ const pkgDir = path.join(dir, 'node_modules', '@astryxdesign', 'cli');+ /** @type {Record<string, unknown>} */+ const pkg = {name: '@astryxdesign/cli', version, type: 'commonjs'};+ if (options.engines) pkg.engines = options.engines;+ if (options.bin !== false) {+ Object.assign(pkg, {bin: {astryx: './bin.cjs'}});+ fs.mkdirSync(pkgDir, {recursive: true});+ fs.writeFileSync(path.join(pkgDir, 'bin.cjs'), standInBin(version));+ }+ writeJson(path.join(pkgDir, 'package.json'), pkg);+ return pkgDir;+}++/**+ * Install a stand-in `@astryxdesign/core` of `version` into `dir`.+ * @param {string} dir+ * @param {string} version+ * @returns {string}+ */+export function installCore(dir, version) {+ const pkgDir = path.join(dir, 'node_modules', '@astryxdesign', 'core');+ writeJson(path.join(pkgDir, 'package.json'), {+ name: '@astryxdesign/core',+ version,+ });+ return pkgDir;+}++/**+ * A project folder whose package.json declares `deps`.+ * @param {string} dir+ * @param {Record<string, string>} deps+ * @returns {string}+ */+export function project(dir, deps) {+ writeJson(path.join(dir, 'package.json'), {+ name: path.basename(dir),+ private: true,+ dependencies: deps,+ });+ return dir;+}++/**+ * A verified release in a cache folder, made of stand-ins: the layout and+ * marker `ensureRelease` leaves.+ * @param {string} cacheDir+ * @param {string} version+ * @param {{engines?: Record<string, string>}} [options] the CLI's `engines`+ * @returns {string} the release folder+ */+export function seedRelease(cacheDir, version, options = {}) {+ const dir = path.join(cacheDir, 'releases', version);+ writeJson(path.join(dir, 'package.json'), {+ name: 'astryx-release',+ private: true,+ });+ installStandInCli(dir, version, options);+ installCore(dir, version);+ /** @type {Record<string, string>} */+ const files = {};+ for (const rel of [+ 'node_modules/@astryxdesign/cli/package.json',+ 'node_modules/@astryxdesign/core/package.json',+ 'node_modules/@astryxdesign/cli/bin.cjs',+ ]) {+ files[rel] = createHash('sha256')+ .update(fs.readFileSync(path.join(dir, rel)))+ .digest('hex');+ }+ writeJson(path.join(dir, 'release.json'), {+ version,+ verifiedAt: 'test',+ files,+ tree: releaseTree(dir),+ });+ return dir;+}++/**+ * This CLI's own version. A test that runs the real bin in a project whose+ * Core is another release is handed to that release (spec AST-081 FR2), so a+ * fixture that means "the installed Core" without caring which release uses+ * this version.+ */+export const CLI_VERSION = JSON.parse(+ fs.readFileSync(new URL('../package.json', import.meta.url), 'utf-8'),+).version;++/** This CLI package's folder. */+const THIS_CLI = path.resolve(+ path.dirname(new URL(import.meta.url).pathname),+ '..',+);++/**+ * Make `dir` a project whose own CLI is this copy, linked into its+ * node_modules, with no Core installed. Runs there answer as the project's own+ * CLI (`copy: project`), so no carried Core stands in for the missing one.+ * @param {string} dir+ * @returns {string} dir+ */+export function linkThisCliAsProjectCli(dir) {+ const pkgFile = path.join(dir, 'package.json');+ if (!fs.existsSync(pkgFile)) {+ writeJson(pkgFile, {+ name: 'app',+ private: true,+ devDependencies: {'@astryxdesign/cli': CLI_VERSION},+ });+ }+ const link = path.join(dir, 'node_modules', '@astryxdesign', 'cli');+ fs.mkdirSync(path.dirname(link), {recursive: true});+ if (!fs.existsSync(link)) fs.symlinkSync(THIS_CLI, link, 'dir');+ return dir;+}diff --git a/packages/cli/test/__golden__/component-props.json b/packages/cli/test/__golden__/component-props.jsonindex a8b6954338..c1d8bbc8c2 100644--- a/packages/cli/test/__golden__/component-props.json+++ b/packages/cli/test/__golden__/component-props.json@@ -15,5 +15,12 @@"default": "'calm'","description": "Visual weight."}- ]+ ],+ "meta": {+ "answeredBy": {+ "cli": "<cli version>",+ "core": "<cli version>",+ "copy": "project"+ }+ }}diff --git a/packages/cli/test/__golden__/component-zh.json b/packages/cli/test/__golden__/component-zh.jsonindex c36f8e1fa3..992975cc1b 100644--- a/packages/cli/test/__golden__/component-zh.json+++ b/packages/cli/test/__golden__/component-zh.json@@ -46,5 +46,12 @@"package": "@acme/kit","import": "@acme/kit","sourceAvailable": true+ },+ "meta": {+ "answeredBy": {+ "cli": "<cli version>",+ "core": "<cli version>",+ "copy": "project"+ }}}diff --git a/packages/cli/test/__golden__/component.json b/packages/cli/test/__golden__/component.jsonindex 138836a42d..8dbc4e77b9 100644--- a/packages/cli/test/__golden__/component.json+++ b/packages/cli/test/__golden__/component.json@@ -46,5 +46,12 @@"package": "@acme/kit","import": "@acme/kit","sourceAvailable": true+ },+ "meta": {+ "answeredBy": {+ "cli": "<cli version>",+ "core": "<cli version>",+ "copy": "project"+ }}}diff --git a/packages/cli/test/__golden__/docs-list.json b/packages/cli/test/__golden__/docs-list.jsonindex 48ff4078d6..9ae4d37d4a 100644--- a/packages/cli/test/__golden__/docs-list.json+++ b/packages/cli/test/__golden__/docs-list.json@@ -15,6 +15,11 @@"description": "Commands, programmatic APIs, integration authoring, and output contracts.","package": "@astryxdesign/cli"},+ {+ "topic": "global",+ "description": "Install Astryx once on your computer and use it in any folder. Each project still runs its own version of Astryx, so a global install never changes what a project gets.",+ "package": "@astryxdesign/cli"+ },{"topic": "internationalization","description": "Set the active locale, load catalogs, coexist with your own i18n library, handle RTL, and test translations.",@@ -55,6 +60,11 @@"description": "Every topic that no section places yet. Each keeps its own name; open one by it.","package": "@astryxdesign/cli"}- ]+ ],+ "answeredBy": {+ "cli": "<cli version>",+ "core": "<cli version>",+ "copy": "project"+ }}}diff --git a/packages/cli/test/__golden__/docs-section.json b/packages/cli/test/__golden__/docs-section.jsonindex 63179d4a88..9cfe32524c 100644--- a/packages/cli/test/__golden__/docs-section.json+++ b/packages/cli/test/__golden__/docs-section.json@@ -19,5 +19,12 @@"up": "astryx docs acme-guide --index","previous": "astryx docs acme-guide start"}+ },+ "meta": {+ "answeredBy": {+ "cli": "<cli version>",+ "core": "<cli version>",+ "copy": "project"+ }}}diff --git a/packages/cli/test/__golden__/docs-topic.json b/packages/cli/test/__golden__/docs-topic.jsonindex ca6d994b4e..0f72633440 100644--- a/packages/cli/test/__golden__/docs-topic.json+++ b/packages/cli/test/__golden__/docs-topic.json@@ -39,5 +39,12 @@"up": "astryx docs unorganized","previous": "astryx docs working-with-ai"}+ },+ "meta": {+ "answeredBy": {+ "cli": "<cli version>",+ "core": "<cli version>",+ "copy": "project"+ }}}diff --git a/packages/cli/test/__golden__/search.json b/packages/cli/test/__golden__/search.jsonindex 4dda24f4ce..c74de74185 100644--- a/packages/cli/test/__golden__/search.json+++ b/packages/cli/test/__golden__/search.json@@ -48,5 +48,12 @@"command": "astryx theme add ocean"}]+ },+ "meta": {+ "answeredBy": {+ "cli": "<cli version>",+ "core": "<cli version>",+ "copy": "project"+ }}}diff --git a/packages/cli/test/__golden__/template.json b/packages/cli/test/__golden__/template.jsonindex be09ccf6cb..613d7639a2 100644--- a/packages/cli/test/__golden__/template.json+++ b/packages/cli/test/__golden__/template.json@@ -9,5 +9,12 @@"components": [],"source": "export default function Hero() { return <section>zorblax</section>; }\n","demoMediaReplaced": 0+ },+ "meta": {+ "answeredBy": {+ "cli": "<cli version>",+ "core": "<cli version>",+ "copy": "project"+ }}}diff --git a/packages/cli/test/__golden__/theme-add-list.json b/packages/cli/test/__golden__/theme-add-list.jsonindex 7fc58a5c39..34d1870147 100644--- a/packages/cli/test/__golden__/theme-add-list.json+++ b/packages/cli/test/__golden__/theme-add-list.json@@ -58,5 +58,12 @@"maintained": true,"package": "@acme/kit"}- ]+ ],+ "meta": {+ "answeredBy": {+ "cli": "<cli version>",+ "core": "<cli version>",+ "copy": "project"+ }+ }}diff --git a/packages/cli/test/__golden__/theme-list.json b/packages/cli/test/__golden__/theme-list.jsonindex 81dd19e186..c588a83ba8 100644--- a/packages/cli/test/__golden__/theme-list.json+++ b/packages/cli/test/__golden__/theme-list.json@@ -12,5 +12,12 @@"default": false,"source": "package"}- ]+ ],+ "meta": {+ "answeredBy": {+ "cli": "<cli version>",+ "core": "<cli version>",+ "copy": "project"+ }+ }}diff --git a/packages/cli/test/docs-topic-refs.test.mjs b/packages/cli/test/docs-topic-refs.test.mjsnew file mode 100644index 0000000000..b58807fd8b--- /dev/null+++ b/packages/cli/test/docs-topic-refs.test.mjs@@ -0,0 +1,62 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Every `astryx docs <topic>` that the changesets, the READMEs, and the+ * computer-level agent skill name resolves to a real docs topic, so a release+ * note or the skill never points a reader at a page that does not exist.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {fileURLToPath} from 'node:url';+import {describe, expect, it} from 'vitest';+import {docs} from '../api/docs/docs.mjs';+import {renderComputerAgentText} from '../foundation/agent-docs/computer-agent-text.mjs';++const CLI = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+const REPO = path.resolve(CLI, '..', '..');++/** Each topic `astryx docs <topic>` names in `text`, placeholders left out. */+function topicsIn(/** @type {string} */ text) {+ return [...text.matchAll(/astryx docs ([a-z][\w/-]*)/gu)]+ .map(match => match[1].replace(/\/+$/u, ''))+ .filter(topic => topic.length > 0);+}++const sources = [+ ...fs+ .readdirSync(path.join(REPO, '.changeset'))+ .filter(name => name.endsWith('.md'))+ .map(name => path.join(REPO, '.changeset', name)),+ path.join(REPO, 'README.md'),+ path.join(CLI, 'README.md'),+].map(file => ({+ name: path.relative(REPO, file),+ text: fs.readFileSync(file, 'utf8'),+}));+sources.push({+ name: 'the computer-level agent skill',+ text: renderComputerAgentText({command: 'astryx'}),+});++describe('docs topics named in release notes, READMEs, and the skill', () => {+ it('each resolves to a real topic', async () => {+ /** @type {string[]} */+ const missing = [];+ let checked = 0;+ for (const {name, text} of sources) {+ for (const topic of new Set(topicsIn(text))) {+ checked++;+ try {+ await docs(topic, undefined, {cwd: REPO});+ } catch (error) {+ missing.push(+ `${name}: astryx docs ${topic} (${/** @type {any} */ (error).code ?? error})`,+ );+ }+ }+ }+ expect(checked).toBeGreaterThan(5);+ expect(missing).toEqual([]);+ }, 60_000);+});diff --git a/packages/cli/test/global-local.test.mjs b/packages/cli/test/global-local.test.mjsnew file mode 100644index 0000000000..631af0a24b--- /dev/null+++ b/packages/cli/test/global-local.test.mjs@@ -0,0 +1,2206 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file One test per row of AST-081's "Who answers when global and project+ * copies meet" table (spec AST-081 FR11). Each row runs real copies of this+ * CLI, packed the way it is published and labeled with test versions, in the+ * install layouts the row names, with a private home folder, cache, and+ * search path, and checks who answered and what the run printed.+ *+ * Rows that depend on an operating system's own file system (G25, G26) test+ * their path rules here; on macOS and Windows themselves they run only in+ * the cross-platform smoke workflow.+ */++import {afterAll, afterEach, beforeAll, describe, expect, it} from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {spawn, spawnSync} from 'node:child_process';+import {+ globalCli,+ packedCli,+ placeCli,+ seedPackedRelease,+ startRegistry,+} from '../test-utils/global-local-fixtures.mjs';+import {+ CLI_VERSION,+ cleanupFixtures,+ installCore,+ project,+ tempDir,+ writeJson,+} from '../test-utils/release-fixtures.mjs';+import {installPlaceOf, isGlobalCopy} from '../foundation/release/choose.mjs';+import {globalUpgradeCommand} from '../foundation/release/notices.mjs';+import {relativeWithin, samePath} from '../foundation/fs/path-compare.mjs';+import {userCacheDir} from '../foundation/env/user-dirs.mjs';+import {astryxCommandsOnSearchPath} from '../foundation/env/search-path.mjs';+import {npmCommand, tryLock} from '../foundation/release/cache.mjs';+import {LEASE_SILENCE_MS} from '../foundation/release/lock-lease.mjs';++const POSIX = process.platform !== 'win32';+const ROOT = typeof process.getuid === 'function' && process.getuid() === 0;+const OFFLINE = 'http://127.0.0.1:9/';++beforeAll(() => {+ packedCli();+}, 120_000);+afterEach(cleanupFixtures);+afterAll(() => {+ fs.rmSync(path.dirname(packedCli()), {recursive: true, force: true});+});++/**+ * A private computer: a home folder, a cache, and a search path.+ * @param {{path?: string[]}} [options]+ */+function computer(options = {}) {+ const home = tempDir('home');+ const cache = path.join(home, '.cache');+ // A `node` command for scripts that start with `#!/usr/bin/env node`, and+ // the runner's npm, linked to its entry file as distributions install it,+ // so a run finds npm wherever this Node keeps it.+ const nodeBin = tempDir('node-bin');+ fs.symlinkSync(process.execPath, path.join(nodeBin, 'node'));+ const npm = npmCommand();+ if (POSIX && npm.prefix.length > 0) {+ fs.symlinkSync(npm.prefix[0], path.join(nodeBin, 'npm'));+ }+ return {+ home,+ cache,+ /** The `astryx` cache folder global mode uses. */+ astryxCache: path.join(cache, 'astryx'),+ path: [...(options.path ?? []), nodeBin],+ };+}++/**+ * The environment a run gets on a private computer.+ * @param {ReturnType<typeof computer>} pc+ * @param {Record<string, string | undefined>} [env]+ */+function envOf(pc, env = {}) {+ const base = Object.fromEntries(+ Object.entries(process.env).filter(+ // A proxy would carry the request for the local test registry away.+ ([k]) =>+ !/^(?:npm_|XDG_|ASTRYX|CI$|NO_UPDATE_NOTIFIER$|(?:https?|all|no)_proxy$)/iu.test(+ k,+ ),+ ),+ );+ return {+ ...base,+ HOME: pc.home,+ USERPROFILE: pc.home,+ XDG_CACHE_HOME: pc.cache,+ XDG_CONFIG_HOME: path.join(pc.home, '.config'),+ PATH: pc.path.join(path.delimiter),+ npm_config_registry: OFFLINE,+ npm_config_update_notifier: 'false',+ // An unreachable registry fails at once instead of after npm's backoff.+ npm_config_fetch_retry_mintimeout: '50',+ npm_config_fetch_retry_maxtimeout: '100',+ NO_COLOR: '1',+ ...env,+ };+}++/**+ * Run an `astryx` entry file with node, on a private computer.+ * @param {string} bin+ * @param {string[]} args+ * @param {{cwd: string, pc: ReturnType<typeof computer>, env?: Record<string, string | undefined>}} options+ */+function run(bin, args, {cwd, pc, env = {}}) {+ const result = spawnSync(process.execPath, [bin, ...args], {+ cwd,+ encoding: 'utf8',+ env: envOf(pc, env),+ timeout: 60_000,+ });+ return {+ status: result.status,+ stdout: result.stdout.trim(),+ stderr: result.stderr,+ /** The stderr lines that start with `astryx: `. */+ lines: result.stderr+ .split(/\r?\n/u)+ .filter(line => line.startsWith('astryx: ')),+ /** The update notice lines (FR10). */+ notice: result.stderr+ .split(/\r?\n/u)+ .filter(line =>+ /^(?:A new release of Astryx|To upgrade|The astryx command)/u.test(+ line,+ ),+ ),+ };+}++/**+ * A project with Core installed at `core`, and its own CLI at `cli`.+ * @param {{core?: string, cli?: string, brokenCli?: string, declare?: Record<string, string>}} spec+ */+function makeProject({core, cli, brokenCli, declare}) {+ const deps = {+ ...(core ? {'@astryxdesign/core': core} : {}),+ ...(cli ? {'@astryxdesign/cli': cli} : {}),+ ...(brokenCli ? {'@astryxdesign/cli': brokenCli} : {}),+ ...declare,+ };+ const dir = project(tempDir('project'), deps);+ if (core) installCore(dir, core);+ if (cli)+ placeCli(path.join(dir, 'node_modules', '@astryxdesign', 'cli'), cli);+ // A project CLI that cannot start: its package, with no astryx command.+ if (brokenCli) {+ writeJson(+ path.join(dir, 'node_modules', '@astryxdesign', 'cli', 'package.json'),+ {+ name: '@astryxdesign/cli',+ version: brokenCli,+ },+ );+ }+ return dir;+}++/**+ * What discover lists as available beyond the official Astryx list, which it+ * always reads.+ * @param {any} discover+ * @returns {any[]}+ */+const notOfficial = discover =>+ (discover.meta?.available ?? []).filter(+ (/** @type {any} */ entry) => entry.source !== 'Astryx',+ );++/**+ * The once-a-day hint in a project with no CLI of its own.+ * @param {string} answered+ * @param {string} core+ */+const noCliHint = (answered, core) =>+ `astryx: this project has no Astryx CLI installed; answered by CLI ${answered} while its Core is ${core}. To match, run: npm install @astryxdesign/cli@${core}`;++/** @param {string} version */+const handedTo = version => (/** @type {string} */ from) =>+ `astryx: answered by this project's CLI ${version}, handed over from CLI ${from}`;+/** @param {string} version */+const matchedLine = version =>+ `astryx: answered by CLI ${version} with Core ${version}, the release that matches this project's Core`;+/** @param {string} version */+const outsideLine = version =>+ `astryx: answered by CLI ${version} with Core ${version}, outside a project`;++/**+ * Every file under `dir`, for before-and-after comparisons.+ * @param {string} dir+ * @returns {string[]}+ */+function filesIn(dir) {+ /** @type {string[]} */+ const out = [];+ const walk = (/** @type {string} */ d) => {+ for (const entry of fs.readdirSync(d, {withFileTypes: true})) {+ const p = path.join(d, entry.name);+ if (entry.isDirectory()) walk(p);+ else out.push(path.relative(dir, p));+ }+ };+ walk(dir);+ return out.sort();+}++/**+ * Write the global copy's state.+ * @param {ReturnType<typeof computer>} pc+ * @param {Record<string, unknown>} state+ */+function globalState(pc, state) {+ writeJson(path.join(pc.home, '.config', 'astryx', 'state.json'), state);+}++/**+ * The saved state.+ * @param {ReturnType<typeof computer>} pc+ * @returns {Record<string, any>}+ */+function readState(pc) {+ try {+ return JSON.parse(+ fs.readFileSync(+ path.join(pc.home, '.config', 'astryx', 'state.json'),+ 'utf8',+ ),+ );+ } catch {+ return {};+ }+}++/**+ * An integration (by default `@acme/widgets`) installed in `root`'s+ * node_modules, with one doc topic; `manifest` replaces its manifest's text.+ * @param {string} root+ * @param {{topic: string, peers?: Record<string, string>, name?: string, manifest?: string}} options+ */+function acmeWidgets(root, {topic, peers, name = '@acme/widgets', manifest}) {+ const dir = path.join(root, 'node_modules', ...name.split('/'));+ writeJson(path.join(dir, 'package.json'), {+ name,+ version: '1.0.0',+ ...(peers ? {peerDependencies: peers} : {}),+ });+ fs.writeFileSync(+ path.join(dir, 'astryx.integration.mjs'),+ manifest ?? "export default {docs: './docs'};\n",+ );+ fs.mkdirSync(path.join(dir, 'docs'), {recursive: true});+ fs.writeFileSync(+ path.join(dir, 'docs', `${topic}.doc.mjs`),+ `export const docs = ${JSON.stringify({+ type: 'generic',+ name: topic,+ title: 'Deploying',+ description: 'How to ship an app built with Acme widgets.',+ category: 'guide',+ sections: [+ {+ title: 'Overview',+ content: [{type: 'prose', text: 'Push the button.'}],+ },+ ],+ })};\n`,+ );+ return dir;+}++/** The two lines of a newer-release notice. */+const available = (/** @type {string} */ cur, /** @type {string} */ next) =>+ `A new release of Astryx is available: ${cur} → ${next}`;++describe.skipIf(!POSIX)(+ 'who answers when global and project copies meet',+ () => {+ it('G1 global copy newer than the project CLI, which matches its Core', () => {+ const pc = computer();+ const g = globalCli('npm', '9.0.1', {root: pc.home});+ const dir = makeProject({core: '9.0.0', cli: '9.0.0'});+ const r = run(g.bin, ['--version'], {cwd: dir, pc});+ expect(r.status).toBe(0);+ expect(r.stdout).toBe('9.0.0');+ expect(r.lines).toEqual([handedTo('9.0.0')('9.0.1')]);+ });++ it('G2 global copy older than the project CLI', () => {+ const pc = computer();+ const g = globalCli('npm', '9.0.0', {root: pc.home});+ const dir = makeProject({core: '9.0.1', cli: '9.0.1'});+ const r = run(g.bin, ['--version'], {cwd: dir, pc});+ expect(r.stdout).toBe('9.0.1');+ expect(r.lines).toEqual([handedTo('9.0.1')('9.0.0')]);+ });++ it("G3 the project CLI differs from its Core: the project's own CLI answers, as before global mode", () => {+ const pc = computer();+ const g = globalCli('npm', '9.0.5', {root: pc.home});+ seedPackedRelease(pc.astryxCache, '9.0.1');+ const dir = makeProject({core: '9.0.1', cli: '9.0.0'});+ const r = run(g.bin, ['--version'], {cwd: dir, pc});+ expect(r.stdout).toBe('9.0.0');+ expect(r.lines).toEqual([handedTo('9.0.0')('9.0.5')]);+ });++ it('G4 Core only, no CLI: the copy that started the run answers, as released, with a hint once a day; nothing is installed', () => {+ const pc = computer();+ const g = globalCli('npm', '9.0.0', {root: pc.home});+ const dir = makeProject({core: '9.0.1'});+ const r = run(g.bin, ['--version'], {cwd: dir, pc});+ expect(r.stdout).toBe('9.0.0');+ expect(r.lines).toEqual([noCliHint('9.0.0', '9.0.1')]);+ // Once a day per project.+ expect(run(g.bin, ['--version'], {cwd: dir, pc}).lines).toEqual([]);+ const json = run(g.bin, ['docs', '--json'], {cwd: dir, pc});+ expect(JSON.parse(json.stdout).meta.answeredBy).toEqual({+ cli: '9.0.0',+ core: '9.0.1',+ copy: 'starting',+ });+ // Nothing is installed for the project (the global copy's own Core+ // step, G52, is the only thing that may touch the cache).+ expect(+ fs.existsSync(path.join(pc.astryxCache, 'releases', '9.0.1')),+ ).toBe(false);+ expect(+ fs.existsSync(+ path.join(pc.astryxCache, 'releases', '.failed-9.0.1.json'),+ ),+ ).toBe(false);+ // A copy equal to the project's Core prints no hint.+ const same = makeProject({core: '9.0.0'});+ expect(run(g.bin, ['--version'], {cwd: same, pc}).lines).toEqual([]);+ });++ it('G5 a fresh clone, nothing installed: the copy that started the run answers, naming the Core its lockfile records, writing nothing there', () => {+ const pc = computer();+ const g = globalCli('npm', '9.0.0', {root: pc.home});+ const dir = makeProject({declare: {'@astryxdesign/core': '^9.0.0'}});+ writeJson(path.join(dir, 'package-lock.json'), {+ lockfileVersion: 3,+ packages: {+ '': {dependencies: {'@astryxdesign/core': '^9.0.0'}},+ 'node_modules/@astryxdesign/core': {version: '9.0.1'},+ },+ });+ const before = filesIn(dir);+ const r = run(g.bin, ['--version'], {cwd: dir, pc});+ expect(r.stdout).toBe('9.0.0');+ expect(r.lines).toEqual([noCliHint('9.0.0', '9.0.1')]);+ // A command that reads Core uses the answering release's own Core; when+ // it cannot be downloaded, the error says so for this project.+ const offline = run(g.bin, ['component', 'Button', '--json'], {+ cwd: dir,+ pc,+ });+ const error = JSON.parse(offline.stdout);+ expect(error.code).toBe('ERR_VERSIONS_UNAVAILABLE');+ expect(error.error).toMatch(+ /^This project has no Core installed, and Core 9\.0\.0 could not be downloaded \(.+\)\. Install the project's dependencies, then run again\.$/u,+ );+ expect(error.error).not.toMatch(/Outside a project/u);+ expect(filesIn(dir)).toEqual(before);+ });++ it("in a fresh clone, doctor names the lockfile's Core as the daily hint and notice do", () => {+ const pc = computer();+ const g = globalCli('npm', '9.0.0', {root: pc.home});+ globalState(pc, {+ latest: '9.0.5',+ checkOkAt: Date.now(),+ firstRunAt: Date.now() - 2 * 24 * 60 * 60_000,+ });+ const dir = makeProject({declare: {'@astryxdesign/core': '^9.0.0'}});+ writeJson(path.join(dir, 'package-lock.json'), {+ lockfileVersion: 3,+ packages: {+ '': {dependencies: {'@astryxdesign/core': '^9.0.0'}},+ 'node_modules/@astryxdesign/core': {version: '9.0.1'},+ },+ });+ const notice = run(g.bin, ['--version'], {cwd: dir, pc}).notice;+ expect(notice[1]).toBe(+ 'To upgrade, run: npm install @astryxdesign/[email protected] @astryxdesign/[email protected], then npx astryx upgrade --from 9.0.1 --apply',+ );+ const doctor = JSON.parse(+ run(g.bin, ['doctor', '--json'], {cwd: dir, pc}).stdout,+ );+ const check = (/** @type {string} */ id) =>+ doctor.data.checks.find((/** @type {any} */ c) => c.id === id);+ // FR2's warning, with the Core the lockfile records.+ expect(check('version-alignment')).toMatchObject({+ status: 'warn',+ message:+ 'This project has no Astryx CLI installed; CLI 9.0.0, the one you started, answered while its Core is 9.0.1.',+ fix: 'To match, run: npm install @astryxdesign/[email protected].',+ });+ // The same release and upgrade step as the notice.+ expect(check('newest-release').message).toBe(+ 'This project uses Astryx 9.0.1; 9.0.5 is the newest.',+ );+ expect(check('newest-release').fix).toContain(+ 'npx astryx upgrade --from 9.0.1 --apply',+ );+ });++ it('G6 the installed Core wins over a lockfile that disagrees, for the release a project whose CLI cannot start gets', () => {+ const pc = computer();+ const g = globalCli('npm', '9.0.0', {root: pc.home});+ seedPackedRelease(pc.astryxCache, '9.0.1');+ const dir = makeProject({core: '9.0.1', brokenCli: '9.0.0'});+ writeJson(path.join(dir, 'package-lock.json'), {+ lockfileVersion: 3,+ packages: {'node_modules/@astryxdesign/core': {version: '9.0.0'}},+ });+ const r = run(g.bin, ['--version'], {cwd: dir, pc});+ expect(r.stdout).toBe('9.0.1');+ expect(r.lines).toEqual([matchedLine('9.0.1')]);+ });++ it('G7 a workspace member with its own Core but no CLI of its own, and any other member, use the root CLI', () => {+ const pc = computer();+ const g = globalCli('npm', '9.0.5', {root: pc.home});+ seedPackedRelease(pc.astryxCache, '9.0.1');+ const root = makeProject({core: '9.0.0', cli: '9.0.0'});+ const member = path.join(root, 'packages', 'app');+ project(member, {'@astryxdesign/core': '9.0.1'});+ installCore(member, '9.0.1');+ const other = path.join(root, 'packages', 'docs');+ fs.mkdirSync(other, {recursive: true});+ expect(run(g.bin, ['--version'], {cwd: member, pc}).stdout).toBe('9.0.0');+ const r = run(g.bin, ['--version'], {cwd: other, pc});+ expect(r.stdout).toBe('9.0.0');+ expect(r.lines).toEqual([handedTo('9.0.0')('9.0.5')]);+ });++ it('G8 a folder inside another project answers with the enclosing project (the released read reach)', () => {+ const pc = computer();+ const g = globalCli('npm', '9.0.5', {root: pc.home});+ const root = makeProject({core: '9.0.0', cli: '9.0.0'});+ const nested = path.join(root, 'apps', 'nested');+ project(nested, {'@astryxdesign/core': '9.0.1'});+ fs.mkdirSync(path.join(root, 'vendor', 'repo', '.git'), {+ recursive: true,+ });+ for (const cwd of [nested, path.join(root, 'vendor', 'repo')]) {+ expect(run(g.bin, ['--version'], {cwd, pc}).stdout).toBe('9.0.0');+ }+ });++ it('G9 outside a project: every copy answers itself, the global copy included, whatever releases are cached', () => {+ const pc = computer();+ const g = globalCli('npm', '9.0.0', {root: pc.home});+ seedPackedRelease(pc.astryxCache, '9.0.2');+ globalState(pc, {firstRunAt: Date.now()});+ const empty = tempDir('empty');+ const r = run(g.bin, ['--version'], {cwd: empty, pc});+ expect(r.stdout).toBe('9.0.0');+ expect(r.lines).toEqual([outsideLine('9.0.0')]);+ const runner = placeCli(+ path.join(+ tempDir('npx'),+ '_npx',+ 'abc',+ 'node_modules',+ '@astryxdesign',+ 'cli',+ ),+ '9.0.3',+ );+ const own = run(runner.bin, ['--version'], {cwd: empty, pc});+ expect(own.stdout).toBe('9.0.3');+ expect(own.lines).toEqual([outsideLine('9.0.3')]);+ });++ it("G10 a version typed on a package runner: exactly that release outside a project, the project's release inside one", () => {+ const pc = computer();+ const runner = placeCli(+ path.join(+ tempDir('npx'),+ '_npx',+ 'def',+ 'node_modules',+ '@astryxdesign',+ 'cli',+ ),+ '9.0.3',+ );+ expect(+ run(runner.bin, ['--version'], {cwd: tempDir('empty'), pc}).stdout,+ ).toBe('9.0.3');+ const dir = makeProject({core: '9.0.1', cli: '9.0.1'});+ const r = run(runner.bin, ['--version'], {cwd: dir, pc});+ expect(r.stdout).toBe('9.0.1');+ expect(r.lines).toEqual([handedTo('9.0.1')('9.0.3')]);+ });++ it('G11 a global copy that predates the hand-off answers itself; newer copies and doctor name its replacement, even in a fresh home', () => {+ const pc = computer();+ // A release from before the hand-off: no release-choice module.+ const old = globalCli('npm', '9.0.0', {root: pc.home});+ fs.rmSync(path.join(old.dir, 'foundation', 'release', 'choose.mjs'));+ pc.path.unshift(old.binDir);+ const dir = makeProject({core: '9.0.1', cli: '9.0.1'});+ const projectBin = path.join(+ dir,+ 'node_modules',+ '@astryxdesign',+ 'cli',+ 'clients',+ 'cli',+ 'bin',+ 'astryx.mjs',+ );+ const r = run(projectBin, ['--version'], {cwd: dir, pc});+ expect(r.stdout).toBe('9.0.1');+ expect(r.lines).toEqual([]);+ expect(r.notice).toEqual([+ 'The astryx command on this computer runs CLI 9.0.0, which answers every folder itself.',+ 'To upgrade, run: npm i -g --prefix ~/.npm-global @astryxdesign/cli@latest',+ ]);+ expect(run(projectBin, ['--version'], {cwd: dir, pc}).notice).toEqual([]);+ const doctor = JSON.parse(+ run(projectBin, ['doctor', '--json'], {cwd: dir, pc}).stdout,+ );+ expect(+ doctor.data.checks.find(+ (/** @type {any} */ c) => c.id === 'cli-on-path',+ ),+ ).toMatchObject({+ status: 'warn',+ fix: 'To upgrade, run: `npm i -g --prefix ~/.npm-global @astryxdesign/cli@latest`.',+ });+ });++ it('G12 two global installs: the first on the search path starts and answers itself; doctor lists both', () => {+ const pc = computer();+ const npm = globalCli('npm', '9.0.0', {root: pc.home});+ const pnpm = globalCli('pnpm', '9.0.1', {root: pc.home});+ pc.path.unshift(npm.binDir, pnpm.binDir);+ const empty = tempDir('empty');+ expect(run(npm.bin, ['--version'], {cwd: empty, pc}).stdout).toBe(+ '9.0.0',+ );+ expect(run(pnpm.bin, ['--version'], {cwd: empty, pc}).stdout).toBe(+ '9.0.1',+ );+ const doctor = JSON.parse(+ run(npm.bin, ['doctor', '--json'], {cwd: empty, pc}).stdout,+ );+ const check = doctor.data.checks.find(+ (/** @type {any} */ c) => c.id === 'cli-on-path',+ );+ expect(check.status).toBe('pass');+ expect(check.message).toContain(path.join(npm.binDir, 'astryx'));+ expect(check.message).toContain(+ `Later on the search path: ${path.join(pnpm.binDir, 'astryx')} (CLI 9.0.1)`,+ );+ });++ it('G13 an astryx earlier on the search path that is not the Astryx CLI: init --user and doctor warn', () => {+ const pc = computer();+ const other = tempDir('other');+ fs.writeFileSync(path.join(other, 'astryx'), '#!/bin/sh\necho other\n');+ fs.chmodSync(path.join(other, 'astryx'), 0o755);+ const g = globalCli('npm', '9.0.0', {root: pc.home});+ pc.path.unshift(other, g.binDir);+ const empty = tempDir('empty');+ const init = JSON.parse(+ run(g.bin, ['--json', 'init', '--user'], {cwd: empty, pc}).stdout,+ );+ expect(init.data.warnings[0]).toContain('No `astryx` command');+ const doctor = JSON.parse(+ run(g.bin, ['doctor', '--json'], {cwd: empty, pc}).stdout,+ );+ expect(+ doctor.data.checks.find(+ (/** @type {any} */ c) => c.id === 'cli-on-path',+ ).status,+ ).toBe('warn');+ });++ it('G14 a Node version manager: each Node has its own global copy, which answers itself', () => {+ const pc = computer();+ for (const layout of /** @type {const} */ (['nvm', 'fnm', 'volta'])) {+ const copy = globalCli(layout, '9.0.0', {root: pc.home});+ expect(isGlobalCopy(copy.dir, pc.astryxCache)).toBe(true);+ expect(+ run(copy.bin, ['--version'], {cwd: tempDir('empty'), pc}).stdout,+ ).toBe('9.0.0');+ }+ });++ it('G15 a project pinned through a package manager shim: as for that project, and nothing written there', () => {+ const pc = computer();+ const g = globalCli('npm', '9.0.0', {root: pc.home});+ seedPackedRelease(pc.astryxCache, '9.0.1');+ const dir = makeProject({core: '9.0.1', brokenCli: '9.0.1'});+ const pkg = JSON.parse(+ fs.readFileSync(path.join(dir, 'package.json'), 'utf8'),+ );+ writeJson(path.join(dir, 'package.json'), {+ ...pkg,+ packageManager: '[email protected]',+ });+ const before = filesIn(dir);+ expect(run(g.bin, ['--version'], {cwd: dir, pc}).stdout).toBe('9.0.1');+ // A release that must be fetched and cannot be: the starting copy+ // answers, as before global mode, without touching the project.+ const missing = makeProject({core: '9.0.7', brokenCli: '9.0.7'});+ const missingBefore = filesIn(missing);+ const r = run(g.bin, ['--version'], {cwd: missing, pc});+ expect(r.status).toBe(0);+ expect(r.stdout).toBe('9.0.0');+ expect(filesIn(missing)).toEqual(missingBefore);+ expect(filesIn(dir)).toEqual(before);+ });++ it.skipIf(ROOT)(+ 'G16 a global copy installed with administrator rights: nothing is written to its install folder',+ () => {+ const pc = computer();+ const g = globalCli('npm', '9.0.0', {root: pc.home});+ const prefix = path.join(pc.home, '.npm-global');+ const before = filesIn(prefix);+ fs.chmodSync(g.dir, 0o555);+ try {+ const r = run(g.bin, ['--version'], {cwd: tempDir('empty'), pc});+ expect(r.status).toBe(0);+ expect(r.stdout).toBe('9.0.0');+ } finally {+ fs.chmodSync(g.dir, 0o755);+ }+ expect(filesIn(prefix)).toEqual(before);+ },+ );++ it.skipIf(ROOT)(+ 'G17 the cache cannot be written: the global copy still answers outside and in a Core-only project; when a project whose CLI cannot start needs a release, it answers instead, with a warning and copy fallback',+ () => {+ const pc = computer();+ const g = globalCli('npm', '9.0.0', {root: pc.home});+ fs.mkdirSync(pc.astryxCache, {recursive: true});+ fs.chmodSync(pc.astryxCache, 0o555);+ try {+ const outside = run(g.bin, ['--version'], {+ cwd: tempDir('empty'),+ pc,+ });+ expect(outside.status).toBe(0);+ expect(outside.stdout).toBe('9.0.0');+ const coreOnly = makeProject({core: '9.0.1'});+ expect(run(g.bin, ['--version'], {cwd: coreOnly, pc}).stdout).toBe(+ '9.0.0',+ );+ const dir = makeProject({core: '9.0.1', brokenCli: '9.0.1'});+ const text = run(g.bin, ['--version'], {cwd: dir, pc});+ expect(text.status).toBe(0);+ expect(text.stdout).toBe('9.0.0');+ expect(text.lines).toEqual([+ expect.stringMatching(+ /^astryx: could not get Astryx 9\.0\.1 to match this project's Core \(the release cache .* cannot be written.*\); answering with CLI 9\.0\.0 instead$/u,+ ),+ ]);+ const json = run(g.bin, ['docs', '--json'], {cwd: dir, pc});+ expect(json.status).toBe(0);+ expect(JSON.parse(json.stdout).meta.answeredBy.copy).toBe('fallback');+ } finally {+ fs.chmodSync(pc.astryxCache, 0o755);+ }+ },+ );++ it('G18 cache and configuration folders set by environment: absolute ones are used, relative ones ignored', () => {+ const pc = computer();+ const g = globalCli('npm', '9.0.0', {root: pc.home});+ const dir = makeProject({core: '9.0.0', cli: '9.0.0'});+ const before = filesIn(dir);+ const r = run(g.bin, ['--version'], {+ cwd: dir,+ pc,+ env: {XDG_CACHE_HOME: 'rel-cache', XDG_CONFIG_HOME: 'rel-config'},+ });+ expect(r.status).toBe(0);+ expect(filesIn(dir)).toEqual(before);+ expect(fs.existsSync(path.join(pc.home, '.config', 'astryx'))).toBe(true);+ expect(+ userCacheDir({+ home: pc.home,+ platform: 'linux',+ env: {XDG_CACHE_HOME: '/abs'},+ }),+ ).toBe(path.join('/abs', 'astryx'));+ });++ it('G19 continuous integration (CI set, a fresh home): no check and no notice; the guide is written in the background', async () => {+ const pc = computer();+ const g = globalCli('npm', '9.0.0', {root: pc.home});+ const r = run(g.bin, ['--version'], {+ cwd: tempDir('empty'),+ pc,+ env: {CI: 'true'},+ });+ expect(r.lines).toEqual([outsideLine('9.0.0')]);+ expect(r.notice).toEqual([]);+ expect(readState(pc).checkedAt).toBeUndefined();+ expect(readState(pc).firstRunAt).toBeUndefined();+ const skill = path.join(+ pc.home,+ '.agents',+ 'skills',+ 'astryx',+ 'SKILL.md',+ );+ for (let i = 0; i < 100 && !fs.existsSync(skill); i++) {+ await new Promise(done => setTimeout(done, 100));+ }+ expect(fs.readFileSync(skill, 'utf8')).toContain('name: astryx');+ });++ it.skipIf(ROOT)(+ 'G20 a read-only home folder: the run answers, and nothing is written',+ () => {+ const pc = computer();+ const g = globalCli('npm', '9.0.0', {root: pc.home});+ fs.chmodSync(pc.home, 0o555);+ try {+ const r = run(g.bin, ['--version'], {cwd: tempDir('empty'), pc});+ expect(r.status).toBe(0);+ expect(r.stdout).toBe('9.0.0');+ expect(fs.existsSync(path.join(pc.home, '.agents'))).toBe(false);+ } finally {+ fs.chmodSync(pc.home, 0o755);+ }+ },+ );++ it("G21 a shared cache: another computer's lock is taken over once it goes unrenewed", () => {+ const lock = path.join(tempDir('cache'), 'releases', '.lock-9.0.1');+ fs.mkdirSync(lock, {recursive: true});+ writeJson(path.join(lock, 'owner.json'), {+ pid: 7,+ host: 'another-computer',+ });+ const t0 = Date.now();+ expect(tryLock(lock, {now: t0})).toBe(false);+ expect(tryLock(lock, {now: t0 + LEASE_SILENCE_MS - 1})).toBe(false);+ expect(tryLock(lock, {now: t0 + LEASE_SILENCE_MS})).toBe(true);+ });++ it('G22 a project behind the newest release: the notice after the command, once a day, after a real check of the registry', async () => {+ const registry = await startRegistry({+ versions: ['9.0.1', '9.0.5'],+ latest: '9.0.5',+ });+ try {+ const pc = computer();+ const g = globalCli('npm', '9.0.0', {root: pc.home});+ globalState(pc, {firstRunAt: Date.now() - 2 * 24 * 60 * 60_000});+ const env = {npm_config_registry: registry.url};+ run(g.bin, ['--version'], {cwd: tempDir('empty'), pc, env});+ // That run started two background steps: the check and the+ // computer-level agent text. Each takes the state file's lock to+ // record its result, so a later run's notice could find the lock+ // held. Wait for both completion records, not for a time: the+ // check's latest release with its lock released, and the agent+ // text written for this release.+ const stateDir = path.join(pc.home, '.config', 'astryx');+ const settled = () => {+ const state = readState(pc);+ return (+ state.latest === '9.0.5' &&+ state.agentText?.writtenBy === '9.0.0' &&+ !fs.existsSync(path.join(stateDir, '.lock-check')) &&+ !fs.existsSync(path.join(stateDir, '.lock-state'))+ );+ };+ const deadline = Date.now() + 150_000;+ while (!settled() && Date.now() < deadline) {+ await new Promise(done => setTimeout(done, 100));+ }+ expect(readState(pc).latest).toBe('9.0.5');+ expect(readState(pc).agentText?.writtenBy).toBe('9.0.0');+ // The check installed nothing.+ expect(+ fs.existsSync(path.join(pc.astryxCache, 'releases', '9.0.5')),+ ).toBe(false);+ const dir = makeProject({core: '9.0.1', cli: '9.0.1'});+ writeJson(path.join(dir, 'package-lock.json'), {lockfileVersion: 3});+ const json = run(g.bin, ['--version', '--json'], {cwd: dir, pc, env});+ expect(json.notice).toEqual([]);+ const first = run(g.bin, ['--version'], {cwd: dir, pc, env});+ expect(first.lines).toEqual([handedTo('9.0.1')('9.0.0')]);+ expect(first.notice).toEqual([+ available('9.0.1', '9.0.5'),+ 'To upgrade, run: npm install @astryxdesign/[email protected] @astryxdesign/[email protected], then npx astryx upgrade --from 9.0.1 --apply',+ ]);+ // The notice comes after the command's own output.+ expect(first.stderr.trim().split('\n').at(-1)).toBe(first.notice[1]);+ expect(run(g.bin, ['--version'], {cwd: dir, pc, env}).notice).toEqual(+ [],+ );+ } finally {+ await registry.close();+ }+ }, 240_000);++ it("a host's door names the upgrade step of the project update notice, printed as the run ends (b32)", () => {+ const pc = computer();+ const g = globalCli('npm', '9.0.0', {root: pc.home});+ globalState(pc, {+ latest: '9.0.5',+ checkOkAt: Date.now(),+ firstRunAt: Date.now() - 2 * 24 * 60 * 60_000,+ });+ const dir = makeProject({core: '9.0.0'});+ writeJson(path.join(dir, 'package-lock.json'), {lockfileVersion: 3});+ // A host that runs the CLI inside its door, as the programmatic entry does.+ const host = path.join(tempDir('host'), 'host.mjs');+ fs.writeFileSync(+ host,+ [+ "import {pathToFileURL} from 'node:url';",+ `const at = rel => pathToFileURL(${JSON.stringify(g.dir)} + '/' + rel).href;`,+ "const {runWithCliDoor} = await import(at('foundation/env/cli-command.mjs'));",+ "const {startRun} = await import(at('foundation/release/handoff.mjs'));",+ `await runWithCliDoor('host astryx', () => startRun({cliRoot: ${JSON.stringify(g.dir)}, argv: ['--version']}));`,+ '',+ ].join('\n'),+ );+ const r = run(host, [], {cwd: dir, pc});+ expect(r.status).toBe(0);+ expect(r.notice).toEqual([+ available('9.0.0', '9.0.5'),+ 'To upgrade, run: npm install @astryxdesign/[email protected] @astryxdesign/[email protected], then host astryx upgrade --from 9.0.0 --apply',+ ]);+ });++ it('G23 the newest release needs a newer Node: the global copy answers, and the notice and doctor name the Node first', () => {+ const pc = computer();+ const g = globalCli('npm', '9.0.0', {root: pc.home});+ globalState(pc, {+ latest: '9.0.5',+ latestNode: '>=99',+ checkOkAt: Date.now(),+ checkedAt: Date.now(),+ firstRunAt: Date.now(),+ });+ const empty = tempDir('empty');+ const r = run(g.bin, ['--version'], {cwd: empty, pc});+ expect(r.stdout).toBe('9.0.0');+ expect(r.notice).toEqual([+ available('9.0.0', '9.0.5'),+ `To upgrade, install Node >=99 (this computer runs Node ${process.versions.node}), then run: npm i -g --prefix ~/.npm-global @astryxdesign/cli@latest`,+ ]);+ const doctor = JSON.parse(+ run(g.bin, ['doctor', '--json'], {cwd: empty, pc}).stdout,+ );+ expect(+ doctor.data.checks.find(+ (/** @type {any} */ c) => c.id === 'newest-release',+ ),+ ).toMatchObject({+ status: 'info',+ fix: `To upgrade, install Node >=99 (this computer runs Node ${process.versions.node}), then run: npm i -g --prefix ~/.npm-global @astryxdesign/cli@latest.`,+ });+ });++ it('G24 a link to a project folder answers as the folder does', () => {+ const pc = computer();+ const g = globalCli('npm', '9.0.5', {root: pc.home});+ const dir = makeProject({core: '9.0.0', cli: '9.0.0'});+ const link = path.join(tempDir('links'), 'app');+ fs.symlinkSync(dir, link, 'dir');+ const r = run(g.bin, ['--version'], {cwd: link, pc});+ expect(r.stdout).toBe('9.0.0');+ expect(r.lines).toEqual([handedTo('9.0.0')('9.0.5')]);+ });++ it('G25 a file system that ignores letter case: paths compare without case there (path rules)', () => {+ for (const platform of /** @type {const} */ (['darwin', 'win32'])) {+ expect(samePath('/Users/Ada/App', '/users/ada/app', platform)).toBe(+ true,+ );+ }+ expect(samePath('/home/ada/App', '/home/ada/app', 'linux')).toBe(false);+ expect(+ relativeWithin(+ '/Users/Ada/Proj',+ '/users/ada/proj/node_modules',+ 'darwin',+ ),+ ).toBe('node_modules');+ expect(+ relativeWithin(+ 'C:\\Users\\Ada\\Proj',+ 'c:\\users\\ada\\PROJ\\sub',+ 'win32',+ ),+ ).toBe('sub');+ });++ it('G26 Windows paths and installs follow the same rules (path rules)', () => {+ expect(+ installPlaceOf(+ 'C:\\Users\\ada\\AppData\\Roaming\\npm\\node_modules\\@astryxdesign\\cli',+ ),+ ).toEqual({+ runner: false,+ owner: 'C:\\Users\\ada\\AppData\\Roaming\\npm',+ knownGlobal: false,+ });+ expect(+ installPlaceOf(+ 'C:\\Users\\ada\\AppData\\Local\\Yarn\\Data\\global\\node_modules\\@astryxdesign\\cli',+ ).knownGlobal,+ ).toBe(true);+ expect(+ installPlaceOf(+ 'C:\\Users\\ada\\AppData\\Local\\npm-cache\\_npx\\1a2b\\node_modules\\@astryxdesign\\cli',+ ).runner,+ ).toBe(true);+ expect(+ userCacheDir({+ home: 'C:\\Users\\ada',+ platform: 'win32',+ env: {LOCALAPPDATA: 'C:\\Users\\ada\\AppData\\Local'},+ }),+ ).toBe('C:\\Users\\ada\\AppData\\Local\\astryx\\Cache');+ // npm's Windows shim names the package beside it.+ const bin = tempDir('winbin');+ const pkg = path.join(bin, 'node_modules', '@astryxdesign', 'cli');+ writeJson(path.join(pkg, 'package.json'), {+ name: '@astryxdesign/cli',+ version: '9.0.0',+ });+ fs.writeFileSync(+ path.join(bin, 'astryx.cmd'),+ '@ECHO off\r\n"%~dp0\\node_modules\\@astryxdesign\\cli\\clients\\cli\\bin\\astryx.mjs" %*\r\n',+ );+ expect(+ astryxCommandsOnSearchPath({searchPath: bin, platform: 'win32'}),+ ).toEqual([+ {+ file: path.join(bin, 'astryx.cmd'),+ astryx: true,+ cliRoot: pkg,+ version: '9.0.0',+ handsOff: false,+ },+ ]);+ });++ it('G27 a package script puts the project CLI first: it answers, whatever its version', () => {+ const pc = computer();+ seedPackedRelease(pc.astryxCache, '9.0.1');+ const dir = makeProject({core: '9.0.1', cli: '9.0.0'});+ const binDir = path.join(dir, 'node_modules', '.bin');+ fs.mkdirSync(binDir, {recursive: true});+ const projectBin = path.join(+ dir,+ 'node_modules',+ '@astryxdesign',+ 'cli',+ 'clients',+ 'cli',+ 'bin',+ 'astryx.mjs',+ );+ fs.symlinkSync(projectBin, path.join(binDir, 'astryx'));+ pc.path.unshift(binDir);+ const result = spawnSync('astryx', ['--version'], {+ cwd: dir,+ encoding: 'utf8',+ env: {+ ...Object.fromEntries(+ Object.entries(process.env).filter(+ ([key]) => !/^(?:npm_|XDG_|CI$|NO_UPDATE_NOTIFIER$)/iu.test(key),+ ),+ ),+ HOME: pc.home,+ XDG_CACHE_HOME: pc.cache,+ XDG_CONFIG_HOME: path.join(pc.home, '.config'),+ PATH: pc.path.join(path.delimiter),+ npm_config_registry: OFFLINE,+ },+ });+ expect(result.stdout.trim()).toBe('9.0.0');+ });++ it("G28 a Yarn Plug'n'Play project, whose own CLI Astryx cannot see, is answered by the copy that started the run", () => {+ const pc = computer();+ const g = globalCli('npm', '9.0.0', {root: pc.home});+ const dir = makeProject({declare: {'@astryxdesign/core': '^9.0.0'}});+ fs.writeFileSync(path.join(dir, '.pnp.cjs'), '');+ fs.writeFileSync(+ path.join(dir, 'yarn.lock'),+ '__metadata:\n version: 8\n\n"@astryxdesign/core@npm:^9.0.0":\n version: 9.0.1\n',+ );+ const r = run(g.bin, ['--version'], {cwd: dir, pc});+ expect(r.stdout).toBe('9.0.0');+ expect(r.lines).toEqual([+ expect.stringMatching(+ /^astryx: this project has no Astryx CLI installed; answered by CLI 9\.0\.0 while its Core is 9\.0\.1\. To match, run: yarn add @astryxdesign\/cli@9\.0\.1$/u,+ ),+ ]);+ });++ it('G29 a package runner that reuses the global install answers as the global copy', () => {+ const pc = computer();+ const g = globalCli('npm', '9.0.0', {root: pc.home});+ const r = run(g.bin, ['--version'], {+ cwd: tempDir('empty'),+ pc,+ env: {npm_command: 'exec', npm_lifecycle_event: 'npx'},+ });+ expect(r.stdout).toBe('9.0.0');+ expect(r.lines).toEqual([outsideLine('9.0.0')]);+ });++ it('G30 init --user inside a project answers for the computer and writes nothing in the project', () => {+ const pc = computer();+ const g = globalCli('npm', '9.0.5', {root: pc.home});+ const dir = makeProject({core: '9.0.0', cli: '9.0.0'});+ const before = filesIn(dir);+ const r = run(g.bin, ['init', '--user'], {cwd: dir, pc});+ expect(r.status).toBe(0);+ expect(r.lines).toEqual([+ 'astryx: answered by CLI 9.0.5 with Core 9.0.5, for this computer',+ ]);+ expect(+ fs.existsSync(+ path.join(pc.home, '.claude', 'skills', 'astryx', 'SKILL.md'),+ ),+ ).toBe(true);+ expect(filesIn(dir)).toEqual(before);+ });++ it('G31 a damaged cached release is not used: the run installs it again, or, when it cannot, the starting copy answers instead', () => {+ const pc = computer();+ const g = globalCli('npm', '9.0.0', {root: pc.home});+ const cached = seedPackedRelease(pc.astryxCache, '9.0.2');+ const dir = makeProject({core: '9.0.2', brokenCli: '9.0.2'});+ expect(run(g.bin, ['--version'], {cwd: dir, pc}).stdout).toBe('9.0.2');+ fs.rmSync(+ path.join(+ cached.dir,+ 'node_modules',+ '@astryxdesign',+ 'core',+ 'package.json',+ ),+ );+ const r = run(g.bin, ['--version'], {cwd: dir, pc});+ expect(r.status).toBe(0);+ expect(r.stdout).toBe('9.0.0');+ expect(r.lines.filter(l => l.includes('could not get'))).toEqual([+ expect.stringMatching(/^astryx: could not get Astryx 9\.0\.2 /u),+ ]);+ });++ it('G32 a workspace whose own CLI sits beside its own Core answers with that CLI', () => {+ const pc = computer();+ const g = globalCli('npm', '9.0.0', {root: pc.home});+ const root = tempDir('repo');+ writeJson(path.join(root, 'package.json'), {name: 'repo', private: true});+ writeJson(path.join(root, 'packages', 'core', 'package.json'), {+ name: '@astryxdesign/core',+ version: '9.0.4',+ });+ placeCli(path.join(root, 'packages', 'cli'), '9.0.4');+ // The repository root and another member; `packages/cli` itself reads its+ // own node_modules, which these copies share with this checkout.+ const member = path.join(root, 'apps', 'site');+ fs.mkdirSync(member, {recursive: true});+ for (const cwd of [root, member]) {+ const r = run(g.bin, ['--version'], {cwd, pc});+ expect(r.stdout).toBe('9.0.4');+ expect(r.lines).toEqual([handedTo('9.0.4')('9.0.0')]);+ }+ // Inside the CLI's own package, whose node_modules links this+ // checkout's Core: label the workspace with that Core's version.+ const repo = tempDir('repo');+ writeJson(path.join(repo, 'package.json'), {name: 'repo', private: true});+ writeJson(path.join(repo, 'packages', 'core', 'package.json'), {+ name: '@astryxdesign/core',+ version: CLI_VERSION,+ });+ const own = placeCli(path.join(repo, 'packages', 'cli'), CLI_VERSION);+ for (const cwd of [own.dir, path.join(own.dir, 'foundation')]) {+ const r = run(g.bin, ['--version'], {cwd, pc});+ expect(r.stdout).toBe(CLI_VERSION);+ expect(r.lines).toEqual([handedTo(CLI_VERSION)('9.0.0')]);+ }+ });++ it('G33 the global copy behind the newest release: the notice after the command names the package manager that installed it', () => {+ for (const [layout, command] of /** @type {const} */ ([+ // The npm layout is a prefix in the home folder (`~/.npm-global`),+ // so the upgrade names it.+ ['npm', 'npm i -g --prefix ~/.npm-global @astryxdesign/cli@latest'],+ ['pnpm', 'pnpm add -g @astryxdesign/cli@latest'],+ ['volta', 'volta install @astryxdesign/cli@latest'],+ ])) {+ const pc = computer();+ const g = globalCli(layout, '9.0.0', {root: pc.home});+ globalState(pc, {+ latest: '9.0.5',+ checkOkAt: Date.now(),+ firstRunAt: Date.now(),+ });+ const empty = tempDir('empty');+ const r = run(g.bin, ['--version'], {cwd: empty, pc});+ expect(r.status).toBe(0);+ expect(r.notice).toEqual([+ available('9.0.0', '9.0.5'),+ `To upgrade, run: ${command}`,+ ]);+ expect(run(g.bin, ['--version'], {cwd: empty, pc}).notice).toEqual([]);+ }+ // A failed command prints no notice.+ const pc = computer();+ const g = globalCli('npm', '9.0.0', {root: pc.home});+ globalState(pc, {latest: '9.0.5', checkOkAt: Date.now(), firstRunAt: 0});+ const failed = run(g.bin, ['no-such-command'], {+ cwd: tempDir('empty'),+ pc,+ });+ expect(failed.status).not.toBe(0);+ expect(failed.notice).toEqual([]);+ });++ it('G34 NO_UPDATE_NOTIFIER or CI set: no check and no notice, whatever is due', () => {+ for (const env of [{NO_UPDATE_NOTIFIER: '1'}, {CI: '1'}]) {+ const pc = computer();+ const g = globalCli('npm', '9.0.0', {root: pc.home});+ globalState(pc, {+ latest: '9.0.5',+ checkOkAt: 1,+ checkedAt: 1,+ firstRunAt: 1,+ });+ const r = run(g.bin, ['--version'], {cwd: tempDir('empty'), pc, env});+ expect(r.notice).toEqual([]);+ expect(readState(pc).checkedAt).toBe(1);+ expect(readState(pc).notifiedAt).toBeUndefined();+ }+ });++ it('G35 outside a project: an integration installed beside the global copy contributes its docs, components, and discover entry', () => {+ const pc = computer();+ const g = globalCli('npm', '9.0.0', {root: pc.home});+ acmeWidgets(path.resolve(g.dir, '..', '..', '..'), {+ topic: 'acme-deploying',+ });+ const empty = tempDir('empty');+ const docs = JSON.parse(+ run(g.bin, ['docs', '--json'], {cwd: empty, pc}).stdout,+ );+ expect(+ docs.data.find((/** @type {any} */ t) => t.topic === 'acme-deploying'),+ ).toMatchObject({package: '@acme/widgets'});+ const discover = JSON.parse(+ run(g.bin, ['discover', '--json'], {cwd: empty, pc}).stdout,+ );+ expect(discover.data.map((/** @type {any} */ p) => p.name)).toContain(+ '@acme/widgets',+ );+ const doctor = JSON.parse(+ run(g.bin, ['doctor', '--json'], {cwd: empty, pc}).stdout,+ );+ expect(+ doctor.data.checks.find(+ (/** @type {any} */ c) => c.id === 'computer-integrations',+ ),+ ).toMatchObject({+ status: 'pass',+ message: 'Used outside a project: @acme/[email protected].',+ });+ });++ it("G36 inside a project: an integration installed for the computer adds nothing, and discover and doctor list it as available with the project's install command", () => {+ const pc = computer();+ const g = globalCli('npm', '9.0.0', {root: pc.home});+ acmeWidgets(path.resolve(g.dir, '..', '..', '..'), {+ topic: 'acme-deploying',+ });+ // The global copy is on the search path, as it is once installed.+ pc.path.unshift(g.binDir);+ const dir = makeProject({core: '9.0.0', cli: '9.0.0'});+ writeJson(path.join(dir, 'package-lock.json'), {lockfileVersion: 3});+ const docs = JSON.parse(+ run(g.bin, ['docs', '--json'], {cwd: dir, pc}).stdout,+ );+ expect(+ docs.data.some((/** @type {any} */ t) => t.topic === 'acme-deploying'),+ ).toBe(false);+ const discover = JSON.parse(+ run(g.bin, ['discover', '--json'], {cwd: dir, pc}).stdout,+ );+ expect(discover.data).toEqual([]);+ expect(notOfficial(discover)).toEqual([+ {+ name: '@acme/widgets',+ components: [],+ version: '1.0.0',+ source: 'installed for this computer',+ install: 'npm install @acme/widgets',+ },+ ]);+ const doctor = JSON.parse(+ run(g.bin, ['doctor', '--json'], {cwd: dir, pc}).stdout,+ );+ expect(+ doctor.data.checks.find(+ (/** @type {any} */ c) => c.id === 'computer-integrations',+ ),+ ).toMatchObject({+ status: 'info',+ fix: 'To use one in this project, run `npm install @acme/widgets`.',+ });+ });++ it("G37 a project that installs the same integration uses only its own copy, outside the project's folder rules too", () => {+ const pc = computer();+ const g = globalCli('npm', '9.0.0', {root: pc.home});+ acmeWidgets(path.resolve(g.dir, '..', '..', '..'), {+ topic: 'acme-global',+ });+ // The global copy is on the search path, as it is once installed.+ pc.path.unshift(g.binDir);+ const dir = makeProject({core: '9.0.0', cli: '9.0.0'});+ const pkg = JSON.parse(+ fs.readFileSync(path.join(dir, 'package.json'), 'utf8'),+ );+ writeJson(path.join(dir, 'package.json'), {+ ...pkg,+ dependencies: {...pkg.dependencies, '@acme/widgets': '1.0.0'},+ });+ acmeWidgets(dir, {topic: 'acme-project'});+ const docs = JSON.parse(+ run(g.bin, ['docs', '--json'], {cwd: dir, pc}).stdout,+ );+ const topics = docs.data.map((/** @type {any} */ t) => t.topic);+ expect(topics).toContain('acme-project');+ expect(topics).not.toContain('acme-global');+ const discover = JSON.parse(+ run(g.bin, ['discover', '--json'], {cwd: dir, pc}).stdout,+ );+ expect(notOfficial(discover)).toEqual([]);+ });++ it('G38 an integration whose peer range excludes the answering release is skipped outside a project, and doctor warns', () => {+ const pc = computer();+ const g = globalCli('npm', '9.0.0', {root: pc.home});+ acmeWidgets(path.resolve(g.dir, '..', '..', '..'), {+ topic: 'acme-deploying',+ peers: {'@astryxdesign/core': '>=10.0.0'},+ });+ const empty = tempDir('empty');+ const docs = JSON.parse(+ run(g.bin, ['docs', '--json'], {cwd: empty, pc}).stdout,+ );+ expect(+ docs.data.some((/** @type {any} */ t) => t.topic === 'acme-deploying'),+ ).toBe(false);+ const doctor = JSON.parse(+ run(g.bin, ['doctor', '--json'], {cwd: empty, pc}).stdout,+ );+ expect(+ doctor.data.checks.find(+ (/** @type {any} */ c) => c.id === 'computer-integrations',+ ),+ ).toMatchObject({+ status: 'warn',+ message:+ "Skipped @acme/[email protected]: it needs @astryxdesign/core >=10.0.0, and this computer's CLI is 9.0.0.",+ });+ });++ it("G39 a door's package set: integrations installed with the CLI in one root count, with no host entry", () => {+ const pc = computer();+ const root = tempDir('runtime');+ writeJson(path.join(root, 'package.json'), {+ name: 'door-runtime',+ private: true,+ dependencies: {+ '@astryxdesign/cli': '9.0.0',+ '@acme/widgets': '1.0.0',+ },+ });+ const cli = placeCli(+ path.join(root, 'node_modules', '@astryxdesign', 'cli'),+ '9.0.0',+ );+ acmeWidgets(root, {topic: 'acme-door'});+ const docs = JSON.parse(+ run(cli.bin, ['docs', '--json'], {cwd: tempDir('empty'), pc}).stdout,+ );+ expect(+ docs.data.find((/** @type {any} */ t) => t.topic === 'acme-door'),+ ).toMatchObject({package: '@acme/widgets'});+ });++ it('G40 pnpm global folders: one shared folder before pnpm 11, a folder per package since, with or without the global virtual store', () => {+ const pc = computer();+ // Before pnpm 11: the CLI's files are in `global/5/.pnpm`, and+ // `global/5/package.json` lists everything installed globally.+ const g5 = path.join(pc.home, '.local', 'share', 'pnpm', 'global', '5');+ const real5 = placeCli(+ path.join(+ g5,+ '.pnpm',+ '@[email protected]',+ 'node_modules',+ '@astryxdesign',+ 'cli',+ ),+ '9.0.0',+ );+ writeJson(path.join(g5, 'package.json'), {+ dependencies: {'@astryxdesign/cli': '9.0.0', '@acme/widgets': '1.0.0'},+ });+ fs.mkdirSync(path.join(g5, 'node_modules', '@astryxdesign'), {+ recursive: true,+ });+ fs.symlinkSync(+ real5.dir,+ path.join(g5, 'node_modules', '@astryxdesign', 'cli'),+ );+ acmeWidgets(g5, {topic: 'acme-pnpm10'});+ const empty = tempDir('empty');+ const docs10 = JSON.parse(+ run(real5.bin, ['docs', '--json'], {cwd: empty, pc}).stdout,+ );+ expect(docs10.data.map((/** @type {any} */ t) => t.topic)).toContain(+ 'acme-pnpm10',+ );++ // pnpm 11 and later: each global package has a folder of its own under+ // `global/v11`, and the files are in `store/v11/links`.+ const pc2 = computer();+ const home = path.join(pc2.home, '.local', 'share', 'pnpm');+ const store = placeCli(+ path.join(+ home,+ 'store',+ 'v11',+ 'links',+ '@astryxdesign',+ 'cli',+ '9.0.0',+ 'h1',+ 'node_modules',+ '@astryxdesign',+ 'cli',+ ),+ '9.0.0',+ );+ const cliFolder = path.join(home, 'global', 'v11', 'a1');+ writeJson(path.join(cliFolder, 'package.json'), {+ dependencies: {'@astryxdesign/cli': '9.0.0'},+ });+ fs.mkdirSync(path.join(cliFolder, 'node_modules', '@astryxdesign'), {+ recursive: true,+ });+ fs.symlinkSync(+ store.dir,+ path.join(cliFolder, 'node_modules', '@astryxdesign', 'cli'),+ );+ const widgetsFolder = path.join(home, 'global', 'v11', 'b2');+ writeJson(path.join(widgetsFolder, 'package.json'), {+ dependencies: {'@acme/widgets': '1.0.0'},+ });+ acmeWidgets(widgetsFolder, {topic: 'acme-pnpm11'});+ const docs11 = JSON.parse(+ run(store.bin, ['docs', '--json'], {cwd: tempDir('empty'), pc: pc2})+ .stdout,+ );+ expect(docs11.data.map((/** @type {any} */ t) => t.topic)).toContain(+ 'acme-pnpm11',+ );++ // pnpm 12: no global virtual store, so the CLI's files sit inside its+ // own global folder, under `.pnpm`.+ const pc3 = computer();+ const g12 = path.join(+ pc3.home,+ '.local',+ 'share',+ 'pnpm',+ 'global',+ 'v11',+ );+ const own = path.join(g12, 'c3');+ writeJson(path.join(own, 'package.json'), {+ dependencies: {'@astryxdesign/cli': '9.0.0'},+ });+ const inner = placeCli(+ path.join(+ own,+ 'node_modules',+ '.pnpm',+ '@[email protected]',+ 'node_modules',+ '@astryxdesign',+ 'cli',+ ),+ '9.0.0',+ );+ fs.mkdirSync(path.join(own, 'node_modules', '@astryxdesign'), {+ recursive: true,+ });+ fs.symlinkSync(+ inner.dir,+ path.join(own, 'node_modules', '@astryxdesign', 'cli'),+ );+ const sibling = path.join(g12, 'd4');+ writeJson(path.join(sibling, 'package.json'), {+ dependencies: {'@acme/widgets': '1.0.0'},+ });+ acmeWidgets(sibling, {topic: 'acme-pnpm12'});+ const docs12 = JSON.parse(+ run(inner.bin, ['docs', '--json'], {cwd: tempDir('empty'), pc: pc3})+ .stdout,+ );+ expect(docs12.data.map((/** @type {any} */ t) => t.topic)).toContain(+ 'acme-pnpm12',+ );+ });++ it("G41 an integration's own source folder, outside a project: the folder's copy is used, and doctor says so without a warning", () => {+ const pc = computer();+ const g = globalCli('npm', '9.0.0', {root: pc.home});+ acmeWidgets(path.resolve(g.dir, '..', '..', '..'), {+ topic: 'acme-global',+ });+ const source = tempDir('source');+ writeJson(path.join(source, 'package.json'), {+ name: '@acme/widgets',+ version: '2.0.0',+ });+ fs.writeFileSync(+ path.join(source, 'astryx.integration.mjs'),+ 'export default {};\n',+ );+ const docs = JSON.parse(+ run(g.bin, ['docs', '--json'], {cwd: source, pc}).stdout,+ );+ expect(docs.data.map((/** @type {any} */ t) => t.topic)).not.toContain(+ 'acme-global',+ );+ const doctor = JSON.parse(+ run(g.bin, ['doctor', '--json'], {cwd: source, pc}).stdout,+ );+ expect(+ doctor.data.checks.find(+ (/** @type {any} */ c) => c.id === 'computer-integrations',+ ),+ ).toMatchObject({+ status: 'pass',+ message:+ '@acme/[email protected] is not used here: this folder loads its own copy of @acme/widgets.',+ });+ });++ it('G42 inside a project, an integration installed for the computer is offered only when its peer range admits the project release and it loads', () => {+ const pc = computer();+ const g = globalCli('npm', '9.0.0', {root: pc.home});+ const lib = path.resolve(g.dir, '..', '..', '..');+ acmeWidgets(lib, {topic: 'acme-ok'});+ acmeWidgets(lib, {+ topic: 'acme-old',+ name: '@acme/old',+ peers: {'@astryxdesign/core': '>=10.0.0'},+ });+ acmeWidgets(lib, {+ topic: 'acme-broken',+ name: '@acme/broken',+ manifest: "throw new Error('broken');\n",+ });+ pc.path.unshift(g.binDir);+ const dir = makeProject({core: '9.0.0', cli: '9.0.0'});+ writeJson(path.join(dir, 'package-lock.json'), {lockfileVersion: 3});+ const discover = JSON.parse(+ run(g.bin, ['discover', '--json'], {cwd: dir, pc}).stdout,+ );+ expect(+ notOfficial(discover).map((/** @type {any} */ p) => p.name),+ ).toEqual(['@acme/widgets']);+ const doctor = JSON.parse(+ run(g.bin, ['doctor', '--json'], {cwd: dir, pc}).stdout,+ );+ expect(+ doctor.data.checks.find(+ (/** @type {any} */ c) => c.id === 'computer-integrations',+ ).fix,+ ).toBe('To use one in this project, run `npm install @acme/widgets`.');+ });++ it("G43 inside a project a door's package set answers for: its integrations are offered as available", () => {+ const pc = computer();+ const root = tempDir('runtime');+ writeJson(path.join(root, 'package.json'), {+ name: 'door-runtime',+ private: true,+ dependencies: {'@astryxdesign/cli': '9.0.0', '@acme/widgets': '1.0.0'},+ });+ const cli = placeCli(+ path.join(root, 'node_modules', '@astryxdesign', 'cli'),+ '9.0.0',+ );+ acmeWidgets(root, {topic: 'acme-door'});+ // The project installs only Core 9.0.0, so the door's copy, which+ // started the run, answers it.+ const dir = makeProject({core: '9.0.0'});+ writeJson(path.join(dir, 'package-lock.json'), {lockfileVersion: 3});+ const discover = JSON.parse(+ run(cli.bin, ['discover', '--json'], {cwd: dir, pc}).stdout,+ );+ expect(discover.meta.answeredBy.copy).toBe('starting');+ expect(notOfficial(discover)).toEqual([+ {+ name: '@acme/widgets',+ components: [],+ version: '1.0.0',+ source: 'installed for this computer',+ install: 'npm install @acme/widgets',+ },+ ]);+ });++ it("G44 npm's own prefix (npm i -g --prefix ~/.local): the upgrade names that prefix, integrations installed there apply outside a project, and doctor finds ~/.local/bin/astryx", () => {+ const pc = computer();+ const prefix = path.join(pc.home, '.local');+ const cli = placeCli(+ path.join(prefix, 'lib', 'node_modules', '@astryxdesign', 'cli'),+ '9.0.0',+ );+ fs.mkdirSync(path.join(prefix, 'bin'), {recursive: true});+ fs.symlinkSync(cli.bin, path.join(prefix, 'bin', 'astryx'));+ pc.path.unshift(path.join(prefix, 'bin'));+ acmeWidgets(path.join(prefix, 'lib'), {topic: 'acme-prefix'});+ globalState(pc, {latest: '9.0.5', checkOkAt: Date.now(), firstRunAt: 0});+ const empty = tempDir('empty');+ const docs = run(cli.bin, ['docs', '--json'], {cwd: empty, pc});+ expect(+ JSON.parse(docs.stdout).data.map((/** @type {any} */ t) => t.topic),+ ).toContain('acme-prefix');+ // --json prints no notice; a text run does.+ expect(docs.notice).toEqual([]);+ expect(run(cli.bin, ['--version'], {cwd: empty, pc}).notice).toEqual([+ available('9.0.0', '9.0.5'),+ 'To upgrade, run: npm i -g --prefix ~/.local @astryxdesign/cli@latest',+ ]);+ const doctor = JSON.parse(+ run(cli.bin, ['doctor', '--json'], {cwd: empty, pc}).stdout,+ );+ const onPath = doctor.data.checks.find(+ (/** @type {any} */ c) => c.id === 'cli-on-path',+ );+ expect(onPath.status).toBe('pass');+ expect(onPath.message).toContain(path.join(prefix, 'bin', 'astryx'));+ });++ it("G45 the agent guide: the global copy's first run writes one file and links Claude Code's folder to it; a folder Astryx did not create is kept and doctor names it; --remove-agents removes the file and the link", async () => {+ const pc = computer();+ const g = globalCli('npm', '9.0.0', {root: pc.home});+ const file = path.join(+ pc.home,+ '.agents',+ 'skills',+ 'astryx',+ 'SKILL.md',+ );+ const claude = path.join(pc.home, '.claude', 'skills', 'astryx');+ run(g.bin, ['--version'], {cwd: tempDir('empty'), pc});+ for (let i = 0; i < 100 && !fs.existsSync(claude); i++) {+ await new Promise(done => setTimeout(done, 100));+ }+ expect(fs.readFileSync(file, 'utf8')).toContain('name: astryx');+ expect(fs.lstatSync(claude).isSymbolicLink()).toBe(true);+ expect(fs.readFileSync(path.join(claude, 'SKILL.md'), 'utf8')).toBe(+ fs.readFileSync(file, 'utf8'),+ );+ const removed = run(g.bin, ['init', '--user', '--remove-agents'], {+ cwd: tempDir('empty'),+ pc,+ });+ expect(removed.status).toBe(0);+ expect(fs.existsSync(file)).toBe(false);+ expect(fs.existsSync(claude)).toBe(false);++ // A folder someone else put there is never replaced.+ fs.mkdirSync(claude, {recursive: true});+ fs.writeFileSync(path.join(claude, 'SKILL.md'), 'mine\n');+ expect(+ run(g.bin, ['init', '--user'], {cwd: tempDir('empty'), pc}).status,+ ).toBe(0);+ expect(fs.readFileSync(path.join(claude, 'SKILL.md'), 'utf8')).toBe(+ 'mine\n',+ );+ const doctor = JSON.parse(+ run(g.bin, ['doctor', '--json'], {cwd: tempDir('empty'), pc}).stdout,+ );+ expect(+ doctor.data.checks.find(+ (/** @type {any} */ c) => c.id === 'computer-agent-text',+ ).message,+ ).toContain(+ `Not linked, because something Astryx did not create is there: ~${path.sep}${path.join('.claude', 'skills', 'astryx')}`,+ );+ });++ it('G46 docs global inside a project whose release predates it: the copy that started the run answers, for this computer, never handed off', () => {+ const pc = computer();+ const g = globalCli('npm', '9.0.5', {root: pc.home});+ const dir = makeProject({core: '9.0.0', cli: '9.0.0'});+ for (const args of [+ ['docs', 'global'],+ ['docs', 'global/problems'],+ ]) {+ const r = run(g.bin, args, {cwd: dir, pc});+ expect(r.status).toBe(0);+ expect(r.lines).toEqual([+ 'astryx: answered by CLI 9.0.5 with Core 9.0.5, for this computer',+ ]);+ }+ // Any other docs topic is still the project's.+ expect(run(g.bin, ['docs'], {cwd: dir, pc}).lines).toEqual([+ "astryx: answered by this project's CLI 9.0.0, handed over from CLI 9.0.5",+ ]);+ });++ it('G47 a project whose own CLI is newer than its Core, online or offline: that CLI answers and nothing is fetched', () => {+ const pc = computer();+ const g = globalCli('npm', '9.0.0', {root: pc.home});+ const dir = makeProject({core: '9.0.3', cli: '9.0.4'});+ for (const registry of [undefined, OFFLINE]) {+ const env = registry ? {npm_config_registry: registry} : {};+ const r = run(g.bin, ['--version'], {cwd: dir, pc, env});+ expect(r.status).toBe(0);+ expect(r.stdout).toBe('9.0.4');+ expect(r.lines.some(l => l.includes('could not get Astryx'))).toBe(+ false,+ );+ const json = run(g.bin, ['docs', '--json'], {cwd: dir, pc, env});+ expect(JSON.parse(json.stdout).meta.answeredBy).toMatchObject({+ cli: '9.0.4',+ copy: 'project',+ });+ }+ expect(+ fs.existsSync(path.join(pc.astryxCache, 'releases', '9.0.3')),+ ).toBe(false);+ });++ it('G48 offline, a project whose own CLI cannot start: the starting copy answers, with one warning and copy fallback', () => {+ const pc = computer();+ const g = globalCli('npm', '9.0.0', {root: pc.home});+ const dir = makeProject({core: '9.0.3', brokenCli: '9.0.3'});+ const r = run(g.bin, ['--version'], {cwd: dir, pc});+ expect(r.status).toBe(0);+ expect(r.stdout).toBe('9.0.0');+ // After the line saying it tries to install the release, one warning.+ expect(r.lines.filter(l => !l.includes('installing'))).toEqual([+ expect.stringMatching(+ /^astryx: could not get Astryx 9\.0\.3 to match this project's Core \(.+\); answering with CLI 9\.0\.0 instead$/u,+ ),+ ]);+ const json = run(g.bin, ['docs', '--json'], {cwd: dir, pc});+ expect(JSON.parse(json.stdout).meta.answeredBy).toMatchObject({+ cli: '9.0.0',+ copy: 'fallback',+ });+ });++ it('G49 offline, a release that failed to install is retried after 2 minutes, then after 10 once it fails again, by any copy sharing the cache; a success forgets it', () => {+ const pc = computer();+ const g = globalCli('npm', '9.0.0', {root: pc.home});+ const dir = makeProject({core: '9.0.3', brokenCli: '9.0.3'});+ const record = path.join(+ pc.astryxCache,+ 'releases',+ '.failed-9.0.3.json',+ );+ const installs = (/** @type {{lines: string[]}} */ r) =>+ r.lines.filter(l => l.includes('installing')).length;+ /** Move the last failure `minutes` into the past. @param {number} minutes */+ const age = minutes => {+ const old = JSON.parse(fs.readFileSync(record, 'utf8'));+ fs.writeFileSync(+ record,+ JSON.stringify({...old, at: old.at - minutes * 60_000}),+ );+ };+ expect(installs(run(g.bin, ['--version'], {cwd: dir, pc}))).toBe(1);+ expect(JSON.parse(fs.readFileSync(record, 'utf8')).failures).toBe(1);+ // Within 2 minutes, from this copy or another, no install starts.+ const other = globalCli('npm', '9.0.1', {+ root: path.join(pc.home, 'other'),+ });+ for (const bin of [g.bin, other.bin]) {+ const again = run(bin, ['--version'], {cwd: dir, pc});+ expect(again.status).toBe(0);+ expect(installs(again)).toBe(0);+ expect(again.lines).toEqual([+ expect.stringMatching(+ /^astryx: could not get Astryx 9\.0\.3 to match this project's Core \(.+; last tried 1 minute ago, tried again after 2 minutes\); answering with CLI 9\.0\.[01] instead$/u,+ ),+ ]);+ }+ // After 2 minutes it tries again; a second failure waits 10.+ age(3);+ expect(installs(run(g.bin, ['--version'], {cwd: dir, pc}))).toBe(1);+ expect(JSON.parse(fs.readFileSync(record, 'utf8')).failures).toBe(2);+ age(3);+ const waiting = run(g.bin, ['--version'], {cwd: dir, pc});+ expect(installs(waiting)).toBe(0);+ expect(waiting.lines[0]).toMatch(/tried again after 10 minutes\)/u);+ age(8);+ expect(installs(run(g.bin, ['--version'], {cwd: dir, pc}))).toBe(1);+ // A success forgets the record.+ seedPackedRelease(pc.astryxCache, '9.0.3');+ age(11);+ expect(run(g.bin, ['--version'], {cwd: dir, pc}).stdout).toBe('9.0.3');+ expect(fs.existsSync(record)).toBe(false);+ });++ it('G50 a global copy in a Bun global folder moved with BUN_INSTALL: global only while BUN_INSTALL names it; an app under a folder named install/global is not', () => {+ const pc = computer();+ const bunHome = path.join(pc.home, 'mybun');+ const global = path.join(bunHome, 'install', 'global');+ writeJson(path.join(global, 'package.json'), {+ dependencies: {'@astryxdesign/cli': '9.0.0'},+ });+ fs.writeFileSync(path.join(global, 'bun.lock'), '{}');+ const copy = placeCli(+ path.join(global, 'node_modules', '@astryxdesign', 'cli'),+ '9.0.0',+ );+ const where = {home: pc.home, platform: /** @type {const} */ ('linux')};+ expect(+ isGlobalCopy(copy.dir, pc.astryxCache, {+ ...where,+ env: {BUN_INSTALL: bunHome},+ }),+ ).toBe(true);+ expect(+ globalUpgradeCommand(copy.dir, {...where, env: {BUN_INSTALL: bunHome}}),+ ).toBe('bun add -g @astryxdesign/cli@latest');+ // Nothing names that folder: not global, so no check and no skill.+ expect(isGlobalCopy(copy.dir, pc.astryxCache, {...where, env: {}})).toBe(+ false,+ );+ // An npm app whose folder happens to end in install/global.+ const app = path.join(pc.home, 'work', 'install', 'global');+ writeJson(path.join(app, 'package.json'), {+ name: 'app',+ dependencies: {'@astryxdesign/cli': '9.0.0'},+ });+ const own = placeCli(+ path.join(app, 'node_modules', '@astryxdesign', 'cli'),+ '9.0.0',+ );+ expect(isGlobalCopy(own.dir, pc.astryxCache, {...where, env: {}})).toBe(+ false,+ );+ });++ it("G51 a global copy in a Yarn 1 global folder moved with global-folder: global when Yarn's settings name it; an app made with yarn add alone is not", () => {+ const pc = computer();+ const global = path.join(pc.home, 'myyarn-global');+ const yarnLike = (/** @type {string} */ dir) => {+ writeJson(path.join(dir, 'package.json'), {+ dependencies: {'@astryxdesign/cli': '9.0.0'},+ });+ fs.writeFileSync(path.join(dir, 'yarn.lock'), '');+ return placeCli(+ path.join(dir, 'node_modules', '@astryxdesign', 'cli'),+ '9.0.0',+ );+ };+ const copy = yarnLike(global);+ const where = {+ home: pc.home,+ platform: /** @type {const} */ ('linux'),+ env: {},+ };+ // Not named by Yarn's settings yet: not global.+ expect(isGlobalCopy(copy.dir, pc.astryxCache, where)).toBe(false);+ // `yarn config set global-folder ~/myyarn-global` writes ~/.yarnrc.+ fs.writeFileSync(+ path.join(pc.home, '.yarnrc'),+ 'global-folder "~/myyarn-global"\n',+ );+ expect(isGlobalCopy(copy.dir, pc.astryxCache, where)).toBe(true);+ expect(globalUpgradeCommand(copy.dir, where)).toBe(+ 'yarn global add @astryxdesign/cli@latest',+ );+ // And through the environment.+ fs.rmSync(path.join(pc.home, '.yarnrc'));+ expect(+ isGlobalCopy(copy.dir, pc.astryxCache, {+ ...where,+ env: {YARN_GLOBAL_FOLDER: global},+ }),+ ).toBe(true);+ // A fresh app made with `yarn add @astryxdesign/core @astryxdesign/cli`+ // holds the same files: never global.+ const app = yarnLike(path.join(pc.home, 'my-app'));+ expect(isGlobalCopy(app.dir, pc.astryxCache, where)).toBe(false);+ // Its own CLI, run in it, starts no update check and writes no skill.+ const r = run(app.bin, ['--version'], {+ cwd: path.join(pc.home, 'my-app'),+ pc,+ });+ expect(r.status).toBe(0);+ expect(+ fs.existsSync(path.join(pc.home, '.agents', 'skills', 'astryx')),+ ).toBe(false);+ expect(+ fs.existsSync(path.join(pc.home, '.config', 'astryx', 'state.json')),+ ).toBe(false);+ });++ it.skipIf(process.platform === 'win32')(+ 'G52 the global copy installs its own Core into the cache in the background, never in CI or on Windows and never blocking a command; offline, the failure waits out the backoff',+ async () => {+ const pc = computer();+ const g = globalCli('npm', '9.0.0', {root: pc.home, coreStep: true});+ const empty = tempDir('empty');+ const failed = path.join(+ pc.astryxCache,+ 'releases',+ '.failed-9.0.0.json',+ );+ // In CI, no download starts.+ expect(+ run(g.bin, ['--version'], {cwd: empty, pc, env: {CI: 'true'}}).status,+ ).toBe(0);+ await new Promise(resolve => setTimeout(resolve, 2000));+ expect(fs.existsSync(failed)).toBe(false);+ // Otherwise the detached step tries it; the run itself returns at once.+ const started = Date.now();+ const r = run(g.bin, ['--version'], {cwd: empty, pc});+ expect(r.status).toBe(0);+ expect(r.stdout).toBe('9.0.0');+ expect(Date.now() - started).toBeLessThan(15_000);+ // Offline here: the step records the failure for the backoff.+ for (let i = 0; i < 100 && !fs.existsSync(failed); i++) {+ await new Promise(resolve => setTimeout(resolve, 200));+ }+ expect(fs.existsSync(failed)).toBe(true);+ // A cached release means nothing more to do.+ fs.rmSync(failed);+ seedPackedRelease(pc.astryxCache, '9.0.0');+ expect(run(g.bin, ['--version'], {cwd: empty, pc}).status).toBe(0);+ await new Promise(resolve => setTimeout(resolve, 2000));+ expect(fs.existsSync(failed)).toBe(false);+ },+ 60_000,+ );++ it("G53 pnpm's global virtual store: a project's own CLI kept in the store's links folder is not global; one a pnpm global folder links to is", () => {+ const pc = computer();+ const home = path.join(pc.home, '.local', 'share', 'pnpm');+ const where = {+ home: pc.home,+ platform: /** @type {const} */ ('linux'),+ env: {},+ };+ /** A CLI in the store's links folder. @param {string} hash */+ const inStore = hash =>+ placeCli(+ path.join(+ home,+ 'store',+ 'v11',+ 'links',+ '@astryxdesign',+ 'cli',+ '9.0.0',+ hash,+ 'node_modules',+ '@astryxdesign',+ 'cli',+ ),+ '9.0.0',+ );+ // A project links its own CLI from the store: not global, so no check+ // and no skill for each project run.+ const projectCli = inStore('p1');+ const app = path.join(pc.home, 'app');+ writeJson(path.join(app, 'package.json'), {+ name: 'app',+ dependencies: {'@astryxdesign/cli': '9.0.0'},+ });+ fs.mkdirSync(path.join(app, 'node_modules', '@astryxdesign'), {+ recursive: true,+ });+ fs.symlinkSync(+ projectCli.dir,+ path.join(app, 'node_modules', '@astryxdesign', 'cli'),+ );+ expect(isGlobalCopy(projectCli.dir, pc.astryxCache, where)).toBe(false);+ // `pnpm add -g` links one from a global folder: global.+ const globalCli11 = inStore('g1');+ const folder = path.join(home, 'global', 'v11', 'a1');+ writeJson(path.join(folder, 'package.json'), {+ dependencies: {'@astryxdesign/cli': '9.0.0'},+ });+ fs.mkdirSync(path.join(folder, 'node_modules', '@astryxdesign'), {+ recursive: true,+ });+ fs.symlinkSync(+ globalCli11.dir,+ path.join(folder, 'node_modules', '@astryxdesign', 'cli'),+ );+ expect(isGlobalCopy(globalCli11.dir, pc.astryxCache, where)).toBe(true);+ expect(isGlobalCopy(projectCli.dir, pc.astryxCache, where)).toBe(false);+ // Run in the project, its own CLI starts no check and writes no skill.+ const r = run(projectCli.bin, ['--version'], {cwd: app, pc});+ expect(r.status).toBe(0);+ expect(+ fs.existsSync(path.join(pc.home, '.agents', 'skills', 'astryx')),+ ).toBe(false);+ });++ it('G54 a folder deeper than the nearby look in a project with its own CLI: that CLI answers, and no false hint', () => {+ const pc = computer();+ const g = globalCli('npm', '9.0.5', {root: pc.home});+ const dir = makeProject({core: '9.0.0', cli: '9.0.0'});+ for (const rel of [+ ['src', 'a', 'b', 'c', 'd', 'e'],+ ['src', 'app', '(shop)', 'orders', '[id]', 'edit', 'deeper'],+ ]) {+ const deep = path.join(dir, ...rel);+ fs.mkdirSync(deep, {recursive: true});+ const r = run(g.bin, ['--version'], {cwd: deep, pc});+ expect(r.stdout).toBe('9.0.0');+ expect(r.lines).toEqual([handedTo('9.0.0')('9.0.5')]);+ }+ });++ it('G55 a --json run in a fresh clone returns before the background Core step ends, with clean JSON', async () => {+ const pc = computer();+ const g = globalCli('npm', '9.0.0', {root: pc.home});+ // A slow stand-in for the step, which marks when it starts and ends.+ const startedMark = path.join(pc.home, 'core-step-started');+ const marker = path.join(pc.home, 'core-step-ended');+ const worker = path.join(+ g.dir,+ 'foundation',+ 'release',+ 'core-worker.mjs',+ );+ fs.rmSync(worker, {force: true});+ fs.writeFileSync(+ worker,+ [+ "import * as fs from 'node:fs';",+ `fs.writeFileSync(${JSON.stringify(startedMark)}, '');`,+ `setTimeout(() => fs.writeFileSync(${JSON.stringify(marker)}, ''), 20000);`,+ ].join('\n'),+ );+ const dir = makeProject({declare: {'@astryxdesign/core': '^9.0.0'}});+ writeJson(path.join(dir, 'package-lock.json'), {+ lockfileVersion: 3,+ packages: {'node_modules/@astryxdesign/core': {version: '9.0.0'}},+ });+ const started = Date.now();+ // spawnSync waits until the run's output pipes close.+ const r = run(g.bin, ['docs', '--json'], {cwd: dir, pc});+ expect(Date.now() - started).toBeLessThan(10_000);+ expect(() => JSON.parse(r.stdout)).not.toThrow();+ expect(r.stderr).toBe('');+ expect(fs.existsSync(marker)).toBe(false);+ // The step did start, after the command; on Windows it never starts.+ for (let i = 0; i < 50 && !fs.existsSync(startedMark); i++) {+ await new Promise(resolve => setTimeout(resolve, 100));+ }+ expect(fs.existsSync(startedMark)).toBe(process.platform !== 'win32');+ });++ it("G56 an open search outside a project gets the release's Core as component does; when it cannot, it says what it skipped, never silently", () => {+ const pc = computer();+ const g = globalCli('npm', '9.0.0', {root: pc.home});+ const empty = tempDir('empty');+ // Offline, with nothing cached: one install attempt, then the rest of+ // the search, flagged.+ const json = run(g.bin, ['search', 'button', '--json'], {cwd: empty, pc});+ expect(json.status).toBe(0);+ expect(JSON.parse(json.stdout).meta.partial).toMatchObject({+ skipped: ['component', 'hook', 'template'],+ reason: expect.stringContaining('could not be installed'),+ });+ const text = run(g.bin, ['search', 'button'], {cwd: empty, pc});+ expect(text.status).toBe(0);+ expect(+ text.lines.filter(l =>+ l.startsWith(+ 'astryx: components, hooks, and templates were not searched: ',+ ),+ ),+ ).toHaveLength(1);+ // With the release cached, the search reads its Core: nothing skipped.+ seedPackedRelease(pc.astryxCache, '9.0.0');+ const cached = run(g.bin, ['search', 'button', '--json'], {+ cwd: empty,+ pc,+ });+ expect(JSON.parse(cached.stdout).meta?.partial).toBeUndefined();+ });++ it("G57 a folder deeper than the nearby look in a project with only Core: that Core is read, never the starting copy's", () => {+ const pc = computer();+ const g = globalCli('npm', '9.0.0', {root: pc.home});+ const dir = makeProject({core: '9.0.1'});+ for (const rel of [+ ['a', 'b', 'c', 'd', 'e'],+ ['src', 'a', 'b', 'c', 'd', 'e'],+ ['src', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'],+ ['src', 'app', '(shop)', 'orders', '[id]', 'edit'],+ ]) {+ const deep = path.join(dir, ...rel);+ fs.mkdirSync(deep, {recursive: true});+ const json = run(g.bin, ['docs', '--json'], {cwd: deep, pc});+ expect(JSON.parse(json.stdout).meta.answeredBy, rel.join('/')).toEqual({+ cli: '9.0.0',+ core: '9.0.1',+ copy: 'starting',+ });+ // The command reads the project's Core (here an empty stand-in with+ // no components), not the one the copy carries, which has Button.+ const component = run(g.bin, ['component', 'Button', '--json'], {+ cwd: deep,+ pc,+ });+ expect(+ component.status,+ `${rel.join('/')}: ${component.stdout}`,+ ).not.toBe(0);+ expect(JSON.parse(component.stdout).code).not.toBe(+ 'ERR_VERSIONS_UNAVAILABLE',+ );+ }+ });++ it.skipIf(process.platform === 'win32')(+ "G58 an interrupt reaches the project's CLI exactly once: passed on after 5 seconds when only the starting copy got it, never when the whole group did and the CLI stopped in time",+ async () => {+ const pc = computer();+ const g = globalCli('npm', '9.0.5', {root: pc.home});+ /**+ * A project whose own CLI records each interrupt it gets, then stops+ * as `onInterrupt` says.+ * @param {string} onInterrupt+ */+ const stubProject = onInterrupt => {+ const dir = project(tempDir('project'), {+ '@astryxdesign/cli': '9.0.0',+ });+ const cliDir = path.join(dir, 'node_modules', '@astryxdesign', 'cli');+ writeJson(path.join(cliDir, 'package.json'), {+ name: '@astryxdesign/cli',+ version: '9.0.0',+ type: 'module',+ bin: {astryx: 'clients/cli/bin/astryx.mjs'},+ });+ const bin = path.join(cliDir, 'clients', 'cli', 'bin', 'astryx.mjs');+ fs.mkdirSync(path.dirname(bin), {recursive: true});+ fs.writeFileSync(+ bin,+ [+ "import * as fs from 'node:fs';",+ "const log = process.cwd() + '/interrupts.log';",+ "fs.writeFileSync(log, '');",+ onInterrupt,+ "fs.writeFileSync(process.cwd() + '/child.pid', String(process.pid));",+ 'setInterval(() => {}, 1000);',+ ].join('\n'),+ );+ return dir;+ };+ const HANDLES =+ "process.on('SIGINT', () => { fs.appendFileSync(log, 'SIGINT\\n'); setTimeout(() => process.exit(130), 200); });";+ /**+ * Start a run in `dir` and interrupt it: the starting copy alone, as an+ * agent's kill('SIGINT') does, or its whole process group, as a+ * terminal's Ctrl-C does.+ * @param {string} dir+ * @param {'alone' | 'group'} target+ */+ const interrupt = async (dir, target) => {+ const child = spawn(process.execPath, [g.bin, '--version'], {+ cwd: dir,+ env: envOf(pc),+ stdio: 'pipe',+ // A process group of its own, so the group can be signalled.+ detached: true,+ });+ const pidFile = path.join(dir, 'child.pid');+ for (let i = 0; i < 100 && !fs.existsSync(pidFile); i++) {+ await new Promise(resolve => setTimeout(resolve, 100));+ }+ expect(fs.existsSync(pidFile)).toBe(true);+ const childPid = Number(fs.readFileSync(pidFile, 'utf8'));+ const started = Date.now();+ if (target === 'group') {+ process.kill(-(/** @type {number} */ (child.pid)), 'SIGINT');+ } else {+ child.kill('SIGINT');+ }+ /** @type {[number | null, NodeJS.Signals | null] | null} */+ const ended = await new Promise(resolve => {+ const timer = setTimeout(() => resolve(null), 15_000);+ child.on('exit', (c, s) => {+ clearTimeout(timer);+ resolve([c, s]);+ });+ });+ if (!ended) {+ // The run did not stop: end both, then fail below.+ child.kill('SIGKILL');+ try {+ process.kill(childPid, 'SIGKILL');+ } catch {+ // Already gone.+ }+ }+ const [code, signal] = ended ?? [null, null];+ let alive = true;+ try {+ process.kill(childPid, 0);+ } catch {+ alive = false;+ }+ return {+ code,+ signal,+ alive,+ seconds: (Date.now() - started) / 1000,+ interrupts: fs+ .readFileSync(path.join(dir, 'interrupts.log'), 'utf8')+ .split('\n')+ .filter(Boolean).length,+ };+ };+ // The starting copy alone: passed on once, after the grace; the run+ // ends with the CLI's exit status.+ const alone = await interrupt(stubProject(HANDLES), 'alone');+ expect(alone).toMatchObject({+ code: 130,+ signal: null,+ alive: false,+ interrupts: 1,+ });+ expect(alone.seconds).toBeGreaterThanOrEqual(5);+ expect(alone.seconds).toBeLessThan(10);+ // The whole group: the CLI already has it and stops in time, so it is+ // not passed on again.+ const group = await interrupt(stubProject(HANDLES), 'group');+ expect(group).toMatchObject({+ code: 130,+ signal: null,+ alive: false,+ interrupts: 1,+ });+ expect(group.seconds).toBeLessThan(5);+ // A CLI that leaves the interrupt to Node ends by the signal, and so+ // does the run.+ const dies = await interrupt(stubProject(''), 'alone');+ expect(dies).toMatchObject({+ code: null,+ signal: 'SIGINT',+ alive: false,+ });+ },+ 60_000,+ );+ },+);++it('names every row of the table exactly once', () => {+ const text = fs.readFileSync(new URL(import.meta.url), 'utf8');+ const rows = [+ ...text.matchAll(/^\s+it(?:\.skipIf\([^)]*\)\()?\(?\s*['"](G\d+) /gmu),+ ].map(m => m[1]);+ expect(rows).toEqual(Array.from({length: 58}, (_, i) => `G${i + 1}`));+ expect(os.EOL).toBeTypeOf('string');+});diff --git a/packages/cli/test/global-mode-docs.test.mjs b/packages/cli/test/global-mode-docs.test.mjsnew file mode 100644index 0000000000..d5a906177d--- /dev/null+++ b/packages/cli/test/global-mode-docs.test.mjs@@ -0,0 +1,257 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file The global-mode docs say what the CLI does (spec AST-081).+ *+ * - Every command's "In global mode" note is checked against the command run+ * in an empty folder: the error code and message it quotes, the issue code+ * it names, or the checks it lists are the ones the run produces.+ * - Every terminal line a global-mode page shows (its `text` code blocks) is+ * one the CLI prints, built here from the CLI's own strings, so a docs line+ * and the code cannot drift apart.+ * - `astryx search` finds the right page for global, uninstall, and CI.+ */++import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {fileURLToPath, pathToFileURL} from 'node:url';+import {afterAll, beforeAll, describe, expect, it} from 'vitest';+import {runCli} from '../test-utils/run-cli.mjs';+import {search} from '../api/search/search.mjs';+import {+ handedToProjectLine,+ progressText,+ fallbackLine,+ whoAnsweredLine,+} from '../foundation/release/handoff.mjs';+import {+ availableLine,+ noCliHintLine,+ oldGlobalLines,+ upgradeLine,+} from '../foundation/release/notices.mjs';++const CLI = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+const COMMANDS = path.join(CLI, 'clients', 'cli', 'commands');+const TREE = path.join(CLI, 'assets', 'docs', 'tree');+const SLOW = 60_000;++/** @type {string[]} */+const dirs = [];+const empty = () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-global-docs-'));+ dirs.push(dir);+ return dir;+};+afterAll(() => {+ for (const dir of dirs) fs.rmSync(dir, {recursive: true, force: true});+});++// No run reaches the network.+const realFetch = globalThis.fetch;+beforeAll(() => {+ globalThis.fetch = async () => {+ throw new Error('offline');+ };+});+afterAll(() => {+ globalThis.fetch = realFetch;+});++/**+ * @param {string} file+ * @returns {Promise<any>}+ */+async function load(file) {+ const mod = await import(pathToFileURL(file).href);+ return mod.doc ?? mod.docs;+}++/**+ * A command's "In global mode" note.+ * @param {string} name the command doc's file stem+ */+async function noteOf(name) {+ const doc = await load(path.join(COMMANDS, `${name}.doc.mjs`));+ const note = (doc.notes ?? []).find(+ (/** @type {any} */ b) =>+ b.type === 'prose' && b.text.startsWith('In global mode: '),+ );+ return /** @type {string} */ (note?.text ?? '');+}++/**+ * Run a command in an empty folder with `--json`.+ * @param {string[]} args+ */+async function outside(args) {+ const r = await runCli(['--json', ...args], empty());+ return {status: r.status, envelope: JSON.parse(r.stdout)};+}++/** Error messages the commands print outside a project, for the line check. */+/** @type {Set<string>} */+const refusals = new Set();++describe('each command note says what the command does outside a project', () => {+ it.each([+ ['swizzle', ['swizzle', 'Button']],+ ['theme-use', ['theme', 'use', 'ocean']],+ ['theme-remove', ['theme', 'remove', 'ocean']],+ ['theme-add', ['theme', 'add', 'butter']],+ ['integration-add', ['integration', 'add', 'component', 'Foo']],+ ['upgrade', ['upgrade', '--from', '0.6.0', '--apply']],+ ])(+ '%s: stops with the code and message its note quotes',+ async (name, args) => {+ const {status, envelope} = await outside(args);+ expect(status).toBe(1);+ expect(envelope.code).toMatch(/^ERR_/u);+ const note = await noteOf(name);+ expect(note).toContain(`\`${envelope.code}\``);+ if (name !== 'upgrade') expect(note).toContain(`"${envelope.error}"`);+ refusals.add(`Error: ${envelope.error}`);+ },+ SLOW,+ );++ it.each([+ ['doctor-integration-validate', ['doctor', 'integration', 'validate']],+ ['integration-verify', ['integration', 'verify']],+ ['integration-pack', ['integration', 'pack', '--check']],+ ])(+ '%s: reports the one issue its note names, and exits 1',+ async (name, args) => {+ const {status, envelope} = await outside(args);+ expect(status).toBe(1);+ expect(+ envelope.data.issues.map((/** @type {any} */ i) => i.code),+ ).toEqual(['no_package']);+ expect(await noteOf(name)).toContain('`no_package`');+ },+ SLOW,+ );++ it(+ 'integration check: its validate check reports no_package, and it exits 1',+ async () => {+ const {status, envelope} = await outside(['integration', 'check']);+ expect(status).toBe(1);+ const validate = envelope.data.checks.find(+ (/** @type {any} */ c) => c.check === 'validate',+ );+ expect(+ validate.response.data.issues.map((/** @type {any} */ i) => i.code),+ ).toEqual(['no_package']);+ expect(await noteOf('integration-check')).toContain('`no_package`');+ },+ SLOW,+ );++ it(+ 'doctor: lists exactly the checks it runs outside a project',+ async () => {+ const {status, envelope} = await outside(['doctor']);+ expect(status).toBe(0);+ const note = await noteOf('doctor');+ const ids = envelope.data.checks.map((/** @type {any} */ c) => c.id);+ expect([...note.matchAll(/`([a-z-]+)`/gu)].map(m => m[1])).toEqual(+ expect.arrayContaining(ids),+ );+ for (const id of ids) expect(note).toContain(`\`${id}\``);+ },+ SLOW,+ );++ it(+ 'init: writes AGENTS.md and no getting-started steps; theme add with no slug lists themes',+ async () => {+ const dir = empty();+ const r = await runCli(['--json', 'init'], dir);+ expect(r.status).toBe(0);+ expect(fs.existsSync(path.join(dir, 'AGENTS.md'))).toBe(true);+ expect(JSON.parse(r.stdout).data.nextSteps).toBe(false);+ expect(await noteOf('init')).toContain('AGENTS.md');+ const list = await outside(['theme', 'add']);+ expect(list.envelope.type).toBe('theme.list');+ expect(await noteOf('theme-add')).toContain(+ 'with no slug lists the themes',+ );+ },+ SLOW,+ );+});++/** Every terminal line the CLI prints in global mode, built from its strings. */+function cliLines() {+ const matched = {copy: 'matched', version: '0.6.8', coreVersion: '0.6.8'};+ const carried = {copy: 'carried', version: '0.7.2', coreVersion: '0.7.2'};+ const npm = 'npm i -g @astryxdesign/cli@latest';+ return new Set([+ whoAnsweredLine(/** @type {any} */ (carried)),+ whoAnsweredLine(/** @type {any} */ (carried), true),+ whoAnsweredLine(/** @type {any} */ (matched)),+ handedToProjectLine('0.6.8', '0.7.2'),+ progressText('install', '0.6.8'),+ progressText('wait', '0.6.8'),+ availableLine('0.7.2', '0.7.3'),+ availableLine('0.7.1', '0.7.3'),+ upgradeLine(npm, null),+ upgradeLine(npm, '>=22', '20.11.0'),+ upgradeLine(+ 'pnpm add @astryxdesign/[email protected] @astryxdesign/[email protected], then pnpm exec astryx upgrade --from 0.7.1 --apply',+ null,+ ),+ ...oldGlobalLines({version: '0.6.4', command: npm}),+ ...[+ 'the registry could not be reached',+ 'the registry does not have it',+ 'the release cache /home/me/.cache/astryx/releases cannot be written (EACCES)',+ ].map(reason => fallbackLine('0.6.8', reason, '0.7.2')),+ noCliHintLine('0.7.2', '0.6.8', 'npm install @astryxdesign/[email protected]'),+ ...refusals,+ ]);+}++describe('global-mode pages show only lines the CLI prints', () => {+ it('every line of every text block on a global-mode page', async () => {+ const lines = cliLines();+ /** @type {string[]} */+ const unknown = [];+ let checked = 0;+ for (const name of fs.readdirSync(TREE).sort()) {+ if (!name.endsWith('.doc.mjs')) continue;+ const doc = await load(path.join(TREE, name));+ if (doc.placement?.parent !== 'namespace:global') continue;+ for (const section of doc.sections ?? []) {+ for (const block of section.content ?? []) {+ if (block.type !== 'code' || block.lang !== 'text') continue;+ for (const line of block.code.split('\n')) {+ checked++;+ if (!lines.has(line)) unknown.push(`${name}: ${line}`);+ }+ }+ }+ }+ expect(checked).toBeGreaterThan(10);+ expect(unknown).toEqual([]);+ });+});++describe('search finds the global-mode pages', () => {+ it.each([+ ['global', 'global'],+ ['global mode', 'global'],+ ['uninstall', 'uninstall'],+ ['ci', 'ci-and-containers'],+ ['which setup', 'project-global-or-both'],+ ['project or global', 'project-global-or-both'],+ ])('"%s" finds %s', async (query, page) => {+ const r = await search(query);+ const names = r.data.results+ .slice(0, 3)+ .map((/** @type {any} */ m) => String(m.name).split('/').pop());+ expect(names).toContain(page);+ });+});diff --git a/packages/cli/test/global-mode-notes.test.mjs b/packages/cli/test/global-mode-notes.test.mjsnew file mode 100644index 0000000000..755b5760ec--- /dev/null+++ b/packages/cli/test/global-mode-notes.test.mjs@@ -0,0 +1,182 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Every doc whose behavior changes in global mode says so (spec+ * AST-081). Global mode changes behavior in ways a reader cannot guess from+ * one page: a command that does something else outside a project, or an+ * integration that applies only outside projects when installed for the+ * computer. Each such doc carries one note in a single shared form, a prose+ * block that starts with `In global mode:` and links the global guide with+ * `{@link namespace:global}`, so a reader of any of them finds the guide.+ *+ * - Every command doc whose `outsideProject` is not `same` carries one.+ * - So does every authoring doc on integration manifests and their+ * contributions: the integration guides' namespaces, the guides placed+ * under them, and the manifest and discover-source schema docs.+ * - So does every API function doc whose result depends on whether `cwd` is+ * inside a project or on the integrations installed for the computer, in+ * its description (function docs have no notes field).+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {fileURLToPath, pathToFileURL} from 'node:url';+import {describe, expect, it} from 'vitest';++const CLI = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+const NOTE = /^In global mode: [\s\S]*\{@link namespace:global\}/;++/**+ * Every prose text in a doc, wherever it sits.+ * @param {unknown} value+ * @param {string[]} [out]+ * @returns {string[]}+ */+function proseTexts(value, out = []) {+ if (Array.isArray(value)) {+ for (const item of value) proseTexts(item, out);+ } else if (value && typeof value === 'object') {+ const block = /** @type {Record<string, unknown>} */ (value);+ if (block.type === 'prose' && typeof block.text === 'string') {+ out.push(block.text);+ }+ for (const child of Object.values(block)) proseTexts(child, out);+ }+ return out;+}++/** @param {unknown} doc */+const hasNote = doc => proseTexts(doc).some(text => NOTE.test(text));++/**+ * @param {string} file+ * @returns {Promise<any>}+ */+async function load(file) {+ const mod = await import(pathToFileURL(file).href);+ return mod.doc ?? mod.docs;+}++/**+ * Guides under those namespaces about how to write one item's content, whose+ * behavior global mode never changes. Every other guide there carries the+ * note.+ */+const WRITING_DETAIL_GUIDES = new Set([+ 'check-your-docs',+ 'define-the-theme',+ 'document-the-theme',+ 'fonts-and-assets',+ 'generate-a-palette',+ 'links',+ 'sections-and-placement',+ 'short-and-findable',+]);++/** The namespaces whose guides are about integration manifests and what they add. */+const AUTHORING_NAMESPACES = [+ 'integrations',+ 'building-blocks',+ 'configuration',+ 'components',+ 'templates',+ 'docs',+ 'themes',+];++describe('global mode notes', () => {+ it('every command doc that does not answer outside a project as in a new one carries the note', async () => {+ const dir = path.join(CLI, 'clients/cli/commands');+ const missing = [];+ let checked = 0;+ for (const name of fs.readdirSync(dir).sort()) {+ if (!name.endsWith('.doc.mjs')) continue;+ const doc = await load(path.join(dir, name));+ if (!doc?.outsideProject || doc.outsideProject === 'same') continue;+ checked++;+ if (!hasNote(doc.notes)) missing.push(doc.name);+ }+ expect(checked).toBeGreaterThan(5);+ expect(missing).toEqual([]);+ });++ it('every authoring doc on integration manifests and contributions carries the note', async () => {+ const tree = path.join(CLI, 'assets/docs/tree');+ /** @type {Array<{file: string, doc: any}>} */+ const docs = [];+ for (const name of fs.readdirSync(tree).sort()) {+ if (!name.endsWith('.doc.mjs')) continue;+ docs.push({file: name, doc: await load(path.join(tree, name))});+ }+ const parents = new Set(AUTHORING_NAMESPACES.map(n => `namespace:${n}`));+ const authoring = docs.filter(+ ({doc}) =>+ (doc.type === 'namespace' && AUTHORING_NAMESPACES.includes(doc.name)) ||+ (doc.type === 'generic' &&+ parents.has(doc.placement?.parent) &&+ doc.name !== 'global-integrations' &&+ !WRITING_DETAIL_GUIDES.has(doc.name)),+ );+ for (const file of [+ 'authoring/integration/integration.doc.mjs',+ 'authoring/discover/discover.doc.mjs',+ ]) {+ authoring.push({file, doc: await load(path.join(CLI, file))});+ }+ expect(authoring.length).toBeGreaterThan(10);+ expect(+ authoring.filter(({doc}) => !hasNote(doc)).map(({file}) => file),+ ).toEqual([]);+ });++ it('every API function doc whose result depends on global mode carries the note in its description', async () => {+ const missing = [];+ for (const name of [+ 'component',+ 'discover',+ 'docs',+ 'doctor',+ 'init',+ 'search',+ 'upgrade',+ ]) {+ const doc = await load(path.join(CLI, 'api', name, `${name}.doc.mjs`));+ const at = doc.description?.indexOf('In global mode: ') ?? -1;+ if (at < 0 || !NOTE.test(doc.description.slice(at))) missing.push(name);+ }+ expect(missing).toEqual([]);+ });++ it('the global guide links down to every child and each child links back up', async () => {+ const tree = path.join(CLI, 'assets/docs/tree');+ const global = await load(path.join(tree, 'global.doc.mjs'));+ const text =+ proseTexts(global.blocks).join('\n') + JSON.stringify(global.blocks);+ const children = [];+ for (const name of fs.readdirSync(tree).sort()) {+ if (!name.endsWith('.doc.mjs')) continue;+ const doc = await load(path.join(tree, name));+ if (doc.placement?.parent === 'namespace:global') children.push(doc);+ }+ expect(children.map(c => c.name).sort()).toEqual([+ 'ci-and-containers',+ 'computer-agent-guide',+ 'computer-integrations',+ 'install-once',+ 'monorepos',+ 'problems',+ 'project-global-or-both',+ 'reference',+ 'uninstall',+ 'updates',+ 'who-answers',+ ]);+ for (const child of children) {+ expect(text, child.name).toContain(`{@link generic:${child.name}}`);+ expect(+ proseTexts(child).some(t => t.includes('{@link namespace:global}')),+ child.name,+ ).toBe(true);+ }+ });+});diff --git a/packages/cli/test/golden-reads.test.mjs b/packages/cli/test/golden-reads.test.mjsindex 8fb762c52e..c7dc1eb61c 100644--- a/packages/cli/test/golden-reads.test.mjs+++ b/packages/cli/test/golden-reads.test.mjs@@ -15,6 +15,10 @@ import {spawnSync} from 'node:child_process';import * as fs from 'node:fs';import * as path from 'node:path';import {CLI_ROOT} from '../foundation/fs/paths.mjs';+import {+ CLI_VERSION,+ linkThisCliAsProjectCli,+} from '../test-utils/release-fixtures.mjs';const REPO_ROOT = path.resolve(CLI_ROOT, '..', '..');const CLI_BIN = path.join(CLI_ROOT, 'clients', 'cli', 'bin', 'astryx.mjs');@@ -45,6 +49,8 @@ function astryx(args) {});expect(result.status).toBe(0);return result.stdout+ .split(`"${CLI_VERSION}"`)+ .join('"<cli version>"').split(project).join('<project>').split(REPO_ROOT)@@ -76,6 +82,7 @@ beforeAll(() => {// bin; a project without one gets the scoped package instead.fs.mkdirSync(path.join(project, 'node_modules', '.bin'), {recursive: true});fs.writeFileSync(path.join(project, 'node_modules', '.bin', 'astryx'), '');+ linkThisCliAsProjectCli(project);write('package.json', JSON.stringify({name: '@acme/kit', version: '1.2.3'}));write('astryx.integration.mjs',diff --git a/packages/cli/test/integration-check-failures.json b/packages/cli/test/integration-check-failures.jsonindex d5a9addaa6..709e61a360 100644--- a/packages/cli/test/integration-check-failures.json+++ b/packages/cli/test/integration-check-failures.json@@ -28,6 +28,7 @@"inactive_component_replacement","integration_error","invalid_agent_docs",+ "invalid_cli_command","invalid_codemod","invalid_codemod_version","invalid_component",diff --git a/packages/cli/test/runner-commands.test.mjs b/packages/cli/test/runner-commands.test.mjsnew file mode 100644index 0000000000..f98da5cddc--- /dev/null+++ b/packages/cli/test/runner-commands.test.mjs@@ -0,0 +1,76 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Astryx's own docs write commands bare, and nothing tells a reader to+ * run the unscoped name through npx (RUNNER_COMMAND_ALLOWLIST says where a+ * runner is allowed, and why).+ *+ * TODO(doctor-runner-check): replace the matcher below with the Doctor lane's+ * runnerCommandsIn() once it lands, keeping RUNNER_COMMAND_ALLOWLIST.+ */++import {execFileSync} from 'node:child_process';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {fileURLToPath} from 'node:url';+import {describe, expect, it} from 'vitest';+import {RUNNER_COMMAND_ALLOWLIST} from '../foundation/discovery/runner-allowlist.mjs';++const REPO = path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ '../../..',+);+const DOWNLOAD = String.raw`(?:npx|pnpm\s+dlx|yarn\s+dlx|bunx|bun\s+x|npm\s+exec)`;+const PROJECT = String.raw`(?:pnpm\s+exec|pnpm|yarn)`;+/** npx (or another download runner) with the unscoped name. */+const UNSCOPED = new RegExp(+ String.raw`(?<![\w@/-])${DOWNLOAD}\s+astryx(?![\w@/-])`,+ 'gu',+);+/** Any runner in front of an Astryx command. */+const RUNNER = new RegExp(+ String.raw`(?<![\w@/-])(?:${DOWNLOAD}\s+(?:astryx|@astryxdesign/cli(?:@[\w.-]+)?)(?![\w/-])|${PROJECT}\s+astryx\s+[a-z][\w-]*)`,+ 'gu',+);++const files = execFileSync(+ 'git',+ ['ls-files', 'packages/core', 'packages/cli', 'README.md'],+ {cwd: REPO, encoding: 'utf8'},+)+ .split('\n')+ .filter(file => /\.(?:[cm]?[jt]sx?|md)$/u.test(file))+ .filter(file => !RUNNER_COMMAND_ALLOWLIST.skip.some(re => re.test(file)));++/** @param {string} file @param {RegExp} re */+function hits(file, re) {+ const text = fs.readFileSync(path.join(REPO, file), 'utf8');+ return text+ .split('\n')+ .flatMap((line, i) =>+ [...line.matchAll(re)].map(m => `${file}:${i + 1}: ${m[0]}`),+ );+}++describe('runner commands in Astryx docs', () => {+ it('never runs the unscoped name through npx', () => {+ expect(files.length).toBeGreaterThan(100);+ expect(files.flatMap(file => hits(file, UNSCOPED))).toEqual([]);+ });++ it('writes commands bare in docs, except the named runner examples', () => {+ const docs = files.filter(+ file =>+ (file.endsWith('.doc.mjs') || file === 'packages/core/docs.mjs') &&+ !(file in RUNNER_COMMAND_ALLOWLIST.runnerExamples),+ );+ expect(docs.length).toBeGreaterThan(100);+ expect(docs.flatMap(file => hits(file, RUNNER))).toEqual([]);+ });++ it('names only files that exist', () => {+ for (const file of Object.keys(RUNNER_COMMAND_ALLOWLIST.runnerExamples)) {+ expect(fs.existsSync(path.join(REPO, file)), file).toBe(true);+ }+ });+});diff --git a/packages/core/README.md b/packages/core/README.mdindex f1c6d44bc0..e53ca19ca1 100644--- a/packages/core/README.md+++ b/packages/core/README.md@@ -6,10 +6,10 @@ Core UI components, theme system, and utilities for the Astryx design system. Fo>> ```bash> npm install -D @astryxdesign/cli # or: pnpm add -D / yarn add -D / bun add -d-> npx astryx init # resolves to the CLI you just installed+> npx @astryxdesign/cli init # the CLI you just installed> ```>-> `init` writes the Astryx component index into your `AGENTS.md`/`CLAUDE.md` so your agent discovers components, templates, and design tokens instead of guessing. Need a single command without installing? Use the scoped package directly — `npx @astryxdesign/cli <cmd>` (or `pnpm dlx`/`bunx @astryxdesign/cli`). Bare `npx astryx` only works once `@astryxdesign/cli` is a dependency; before that npm resolves it to an unrelated package. See [XDS CLI](#xds-cli).+> `init` writes the Astryx component index into your `AGENTS.md`/`CLAUDE.md` so your agent discovers components, templates, and design tokens instead of guessing. Need a single command without installing? The same scoped command works: `npx @astryxdesign/cli <cmd>`. Always use the scoped name: the unscoped `astryx` resolves to an unrelated npm package until `@astryxdesign/cli` is a dependency. See [XDS CLI](#xds-cli).## Component Docs@@ -21,7 +21,7 @@ npx @astryxdesign/cli component Button # full docs for a componentnpx @astryxdesign/cli component --list # list all components```-> Use the scoped `@astryxdesign/cli` to run without installing; bare `npx astryx` only resolves once the CLI is a dependency.+> Use the scoped `@astryxdesign/cli`: it runs with or without installing, while the unscoped `astryx` resolves to an unrelated npm package until the CLI is a dependency.## Page Layouts@@ -57,7 +57,7 @@ astryx discover # discover external Astryx packagesastryx gap-report # report a missing capability```-> Prefix these with your runner: `npx astryx …` / `pnpm exec astryx …` once the CLI is installed, or `npx @astryxdesign/cli …` to run without installing.+> Run these as `npx @astryxdesign/cli …`, or `pnpm exec astryx …` (or your package manager's equivalent) once the CLI is installed.## Related Packagesdiff --git a/packages/core/docs.mjs b/packages/core/docs.mjsindex 2acf45df9b..8d109a2e37 100644--- a/packages/core/docs.mjs+++ b/packages/core/docs.mjs@@ -13,8 +13,8 @@* ==========================================================================* AI AGENT: do NOT guess component APIs or hand-write CSS. Run:* npx @astryxdesign/cli init- * Use the SCOPED name `@astryxdesign/cli` — bare `npx astryx` resolves to an- * unrelated package until the CLI is a dependency. Then, per component:+ * Use the SCOPED name `@astryxdesign/cli` — the unscoped `astryx` resolves to+ * an unrelated npm package until the CLI is a dependency. Then, per component:* npx @astryxdesign/cli component <Name>* npx @astryxdesign/cli component --list* ==========================================================================@@ -27,8 +27,8 @@ const BANNER = `npx @astryxdesign/cli init- (Use the scoped name @astryxdesign/cli. Bare \`npx astryx\` resolves to an- unrelated package until the CLI is installed as a dependency.)+ (Use the scoped name @astryxdesign/cli. The unscoped name astryx resolves+ to an unrelated npm package until the CLI is installed as a dependency.)init writes the full component guide, page templates, design rules & tokensinto your AGENTS.md / CLAUDE.md. Then, for any component:diff --git a/packages/core/scripts/agent-doc-state.mjs b/packages/core/scripts/agent-doc-state.mjsindex 4290ab5cdb..cd07f69dfd 100644--- a/packages/core/scripts/agent-doc-state.mjs+++ b/packages/core/scripts/agent-doc-state.mjs@@ -145,15 +145,37 @@ function findRepositoryRoot(start) {}/**- * 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+ * The invocation the setup nudge falls back to when the CLI's picker+ * (`getCliInvocation`) cannot be loaded. Scoped package form+ * (`@astryxdesign/cli`) — always resolves to us, even before the CLI is+ * installed. npx with the unscoped name 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';+export const SETUP_INVOCATION = 'npx @astryxdesign/cli';++/**+ * The one-line next-step every setup layer prints. Kept here so layer 1+ * (core), layer 2 (cli postinstall) and layer 3 (each command) can never word+ * it differently. Each layer passes the stem from the CLI's picker when it can+ * load it.+ *+ * @param {string} [invocation] the CLI invocation stem, e.g. `pnpm exec astryx`+ * @param {{before?: string | null}} [options] `before`: a command to run+ * first, such as the one that adds the CLI to a project that has none+ * @returns {string}+ */+export function setupNudge(+ invocation = SETUP_INVOCATION,+ {before = null} = {},+) {+ const run = before+ ? `\`${before}\`, then \`${invocation} init\``+ : `\`${invocation} init\``;+ return `\nNext step: run ${run} to finish setup and install the Astryx agent prompt.\n\n`;+}++/** The nudge with the fallback invocation. */+export const SETUP_NUDGE = setupNudge();/*** Pure decision: should a postinstall print the setup nudge? Shared by BOTHdiff --git a/packages/core/scripts/postinstall.mjs b/packages/core/scripts/postinstall.mjsindex f3a98496f6..5e6537e428 100644--- a/packages/core/scripts/postinstall.mjs+++ b/packages/core/scripts/postinstall.mjs@@ -1,7 +1,8 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * @file @astryxdesign/core postinstall — nudge to run `npx @astryxdesign/cli init`.+ * @file @astryxdesign/core postinstall — nudge to run `astryx init`, prefixed+ * the way the project's installed CLI prints commands.** Enforcement layer 1 of making `astryx init` foolproof: when the design system* is installed and the project hasn't run init yet, print a one-line next-step@@ -19,6 +20,8 @@* during npx's fetch, and once set up.*/+import * as fs from 'node:fs';+import * as path from 'node:path';import {fileURLToPath, pathToFileURL} from 'node:url';const HERE = fileURLToPath(import.meta.url);@@ -37,6 +40,39 @@ async function loadContract() {}}+/**+ * The stem the project's installed CLI would print, from its picker+ * (`getCliInvocation`). Core cannot depend on the CLI, so this looks for an+ * installed copy from the project upward and imports the picker by path; with+ * no CLI there, or one too old to have the picker, it returns undefined and+ * the contract's scoped fallback is printed. At install time no integration is+ * loaded, so this is the package-manager guess.+ * @param {string} root+ * @returns {Promise<string | undefined>}+ */+export async function cliInvocation(root) {+ try {+ let dir = path.resolve(root);+ for (;;) {+ const picker = path.join(+ dir,+ 'node_modules/@astryxdesign/cli/foundation/env/package-manager.mjs',+ );+ if (fs.existsSync(picker)) {+ const {getCliInvocation} = await import(pathToFileURL(picker).href);+ return typeof getCliInvocation === 'function'+ ? getCliInvocation(root)+ : undefined;+ }+ const parent = path.dirname(dir);+ if (parent === dir) return undefined;+ dir = parent;+ }+ } catch {+ return undefined;+ }+}+async function main() {const contract = await loadContract();if (!contract) return;@@ -48,7 +84,12 @@ async function main() {isSetUp: contract.isAstryxPromptInReach(root),})) {- process.stdout.write(contract.SETUP_NUDGE);+ const invocation = await cliInvocation(root);+ process.stdout.write(+ typeof contract.setupNudge === 'function'+ ? contract.setupNudge(invocation)+ : contract.SETUP_NUDGE,+ );}}diff --git a/packages/core/src/DropdownMenu/DropdownMenuCheckboxItem.doc.mjs b/packages/core/src/DropdownMenu/DropdownMenuCheckboxItem.doc.mjsindex f64eba5f68..9b1e7f351e 100644--- a/packages/core/src/DropdownMenu/DropdownMenuCheckboxItem.doc.mjs+++ b/packages/core/src/DropdownMenu/DropdownMenuCheckboxItem.doc.mjs@@ -51,7 +51,7 @@ export const docs = {name: 'icon',type: 'IconType',description:- 'Icon to display before the label. See `npx @astryxdesign/cli docs icons` for valid semantic names.',+ 'Icon to display before the label. See `astryx docs icons` for valid semantic names.',},{name: 'value',diff --git a/packages/core/src/DropdownMenu/DropdownMenuCheckboxItem.tsx b/packages/core/src/DropdownMenu/DropdownMenuCheckboxItem.tsxindex c3fa35e93c..5eb2263a62 100644--- a/packages/core/src/DropdownMenu/DropdownMenuCheckboxItem.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenuCheckboxItem.tsx@@ -98,7 +98,7 @@ export interface DropdownMenuCheckboxItemProps extends Omit<description?: ReactNode;/*** Icon to display before the label. Accepts a semantic icon name (see- * `npx @astryxdesign/cli docs icons`) or a rendered node.+ * `astryx docs icons`) or a rendered node.*/icon?: ReactNode | IconType;/**diff --git a/packages/core/src/DropdownMenu/DropdownMenuRadioItem.doc.mjs b/packages/core/src/DropdownMenu/DropdownMenuRadioItem.doc.mjsindex 315769d4a2..5173a0f48f 100644--- a/packages/core/src/DropdownMenu/DropdownMenuRadioItem.doc.mjs+++ b/packages/core/src/DropdownMenu/DropdownMenuRadioItem.doc.mjs@@ -43,7 +43,7 @@ export const docs = {name: 'icon',type: 'IconType',description:- 'Icon to display before the label. See `npx @astryxdesign/cli docs icons` for valid semantic names.',+ 'Icon to display before the label. See `astryx docs icons` for valid semantic names.',},{name: 'isDisabled',diff --git a/packages/core/src/DropdownMenu/DropdownMenuRadioItem.tsx b/packages/core/src/DropdownMenu/DropdownMenuRadioItem.tsxindex 5e9cb08015..cb8c7aaff7 100644--- a/packages/core/src/DropdownMenu/DropdownMenuRadioItem.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenuRadioItem.tsx@@ -93,7 +93,7 @@ export interface DropdownMenuRadioItemProps extends Omit<description?: ReactNode;/*** Icon to display before the label. Accepts a semantic icon name (see- * `npx @astryxdesign/cli docs icons`) or a rendered node.+ * `astryx docs icons`) or a rendered node.*/icon?: ReactNode | IconType;/**diff --git a/packages/core/src/Indicator/Indicator.doc.mjs b/packages/core/src/Indicator/Indicator.doc.mjsindex 4853a3892e..baeea1c083 100644--- a/packages/core/src/Indicator/Indicator.doc.mjs+++ b/packages/core/src/Indicator/Indicator.doc.mjs@@ -171,7 +171,7 @@ defineTheme({code: `// When the shape itself is wrong, hand the theme a component. It receives// {state, size, isDisabled, children} and nothing else.//-// Use theme tokens, never raw values — run \`npx @astryxdesign/cli docs tokens\` for the+// Use theme tokens, never raw values — run \`astryx docs tokens\` for the// full set. Color: --color-accent, --color-on-accent, --color-border,// --color-border-emphasized, --color-background-surface,// --color-background-muted. Radius: --radius-inner, --radius-full.@@ -236,7 +236,7 @@ defineTheme({name: 'brand', indicators: {check: RadioIndicator}});`,{guidance: true,description:- 'Use theme tokens for every color, radius, and border width in a replacement. Run `npx @astryxdesign/cli docs tokens` for the set.',+ 'Use theme tokens for every color, radius, and border width in a replacement. Run `astryx docs tokens` for the set.',},{guidance: true,@@ -297,7 +297,7 @@ export const docsDense = {{guidance: true,description:- 'Use theme tokens for every color, radius, and border width in a replacement. Run `npx @astryxdesign/cli docs tokens` for the set.',+ 'Use theme tokens for every color, radius, and border width in a replacement. Run `astryx docs tokens` for the set.',},{guidance: true,diff --git a/packages/core/src/postinstall.test.mjs b/packages/core/src/postinstall.test.mjsindex 657dff5ccf..e6be3194cc 100644--- a/packages/core/src/postinstall.test.mjs+++ b/packages/core/src/postinstall.test.mjs@@ -24,7 +24,9 @@ import {AGENT_DOC_PATHS,INIT_MARKERS,SETUP_NUDGE,+ setupNudge,} from '../scripts/agent-doc-state.mjs';+import {cliInvocation} from '../scripts/postinstall.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';@@ -95,6 +97,9 @@ describe('core postinstall — one authoritative source, no drift', () => {expect(AGENT_DOC_PATHS).toEqual(cliLeaf.AGENT_DOC_PATHS);expect(INIT_MARKERS).toEqual(cliLeaf.INIT_MARKERS);expect(SETUP_NUDGE).toBe(cliLeaf.SETUP_NUDGE);+ expect(setupNudge('pnpm exec astryx')).toBe(+ cliLeaf.setupNudge('pnpm exec astryx'),+ );});it('agrees with the CLI leaf on a real project', () => {@@ -181,3 +186,31 @@ describe('core postinstall — shouldNudge', () => {}});});++describe('core postinstall — the nudge names the command the CLI would print', () => {+ it('words the nudge around the stem it is given', () => {+ expect(setupNudge('pnpm exec astryx')).toContain(+ 'run `pnpm exec astryx init` to finish setup',+ );+ expect(SETUP_NUDGE).toContain('run `npx @astryxdesign/cli init`');+ });++ it("asks the project's installed CLI for its stem", async () => {+ write('package.json', '{"name":"app"}');+ write('pnpm-lock.yaml', '');+ write('node_modules/.bin/astryx', '');+ fs.mkdirSync(path.join(tmp, 'node_modules/@astryxdesign'), {+ recursive: true,+ });+ fs.symlinkSync(+ path.resolve(import.meta.dirname, '../../cli'),+ path.join(tmp, 'node_modules/@astryxdesign/cli'),+ );+ expect(await cliInvocation(tmp)).toBe('pnpm exec astryx');+ });++ it('has no stem to offer when the CLI is not installed', async () => {+ write('package.json', '{"name":"app"}');+ expect(await cliInvocation(tmp)).toBeUndefined();+ });+});