Skip to content

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

TypeScript

fix(cli): the global skill names the install step when astryx is not found (#7888)

Joey04c746814d5d
diff --git a/.changeset/cli-skill-restore-step.md b/.changeset/cli-skill-restore-step.md
new file mode 100644
index 0000000000..c7a6b6afa2
--- /dev/null
+++ b/.changeset/cli-skill-restore-step.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[fix] The agent guide that global mode writes to the home folder now says what to do when `astryx` is not found: run the command that installed the CLI for the computer first, with the same package manager and folder, such as `npm i -g @astryxdesign/cli` or `pnpm add -g @astryxdesign/cli`. On machines that keep the home folder but reset system folders on restart, the guide outlived the CLI installed for the computer and told agents to run a command that was gone. Outside a project, when the guide names `astryx` and no `astryx` command is on the search path, apart from a package runner's own copy, `astryx doctor` now says so and names the install step the guide records, or npm's when it records none. The global-mode guide for CI and containers explains how to keep the CLI across restarts. A guide written for a host's own command is unchanged. No JSON shape or exit code changes.
+
+@josephfarina
diff --git a/docs/specs/AST-081-global-mode/spec.md b/docs/specs/AST-081-global-mode/spec.md
index ba45187f7b..4a74123aed 100644
--- a/docs/specs/AST-081-global-mode/spec.md
+++ b/docs/specs/AST-081-global-mode/spec.md
@@ -252,9 +252,12 @@ works on is `spec:AST-040` FR9's.
does outside a project, is classified under `spec:AST-017`. `doctor` is `own`:
outside a project it checks the computer, reporting the Node version, the
release that answered and the newest release it knows of, and whether the
- computer-level agent text (FR8) is present and current, and it never fails a
- check because the folder has no project. `swizzle` is `refuse`, even with a
- carried Core.
+ computer-level agent text (FR8) is present and current; when that text names
+ `astryx` and no `astryx` command is on the search path, apart from a package
+ runner's own copy, it says so and names the install step the text records,
+ or npm's when it records none;
+ and it never fails a check because the folder has no project. `swizzle` is
+ `refuse`, even with a carried Core.
- **FR5 — Every answer names who answered, and one picker names every printed
command.**
@@ -408,6 +411,11 @@ works on is `spec:AST-040` FR9's.
`@astryxdesign/core` and `@astryxdesign/cli`, or, where the project already
installs Core, the CLI at that Core's version; run `astryx init` there; then
start from a template, check, and deliver the built project.
+ When it names `astryx`, it ends with
+ ``If `astryx` is not found, run `<install step>` first.``, where the
+ step installs the CLI for the computer with the package manager and folder
+ of the global copy that wrote it, without a version; any other copy keeps
+ the step the file records, or names npm's when it records none.
- The computer-level text is one file, `.agents/skills/astryx/SKILL.md` in
the home folder, which most agent tools read. The computer-level agent
files table below names each other folder it reaches: a folder link to its
diff --git a/packages/cli/api/doctor/_adapter.mjs b/packages/cli/api/doctor/_adapter.mjs
index b9e8ef2bbc..ab757fe91d 100644
--- a/packages/cli/api/doctor/_adapter.mjs
+++ b/packages/cli/api/doctor/_adapter.mjs
@@ -19,13 +19,20 @@ import {
lastNoticeSkip,
projectLag,
} from '../../foundation/release/notices.mjs';
-import {coreVersionOf, isGlobalCopy} from '../../foundation/release/choose.mjs';
+import {
+ coreVersionOf,
+ installPlaceOf,
+ isGlobalCopy,
+} from '../../foundation/release/choose.mjs';
import {readReleaseFacts} from '../../foundation/release/project.mjs';
import {astryxCommandsOnSearchPath} from '../../foundation/env/search-path.mjs';
import {readDeclaredDependencies} from '../../foundation/integrations/autolink.mjs';
import {
+ computerSkillFile,
displayHomePath,
inspectComputerAgentText,
+ skillCommandOf,
+ skillInstallStepOf,
} from '../../foundation/agent-docs/computer-agent-text.mjs';
import {computerAgentTextSettings} from '../../foundation/env/user-settings.mjs';
import * as fs from 'node:fs';
@@ -288,12 +295,29 @@ function declaredPackageNames(cwd) {
}
/**
- * 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}>}}
+ * The computer-level agent text's setting, its state on disk, and the command
+ * the skill file tells agents to run and the install step it records for when
+ * that command is not found (each null when there is no file, or it names
+ * none).
+ * @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}>, command: string | null, install: string | null}}
*/
export function computerAgentTextState() {
const settings = computerAgentTextSettings();
- return {settings, entries: inspectComputerAgentText({links: settings.links})};
+ let command = null;
+ let install = null;
+ try {
+ const text = fs.readFileSync(computerSkillFile(), 'utf8');
+ command = skillCommandOf(text);
+ install = skillInstallStepOf(text);
+ } catch {
+ // No skill file, or one that cannot be read: no command to check.
+ }
+ return {
+ settings,
+ entries: inspectComputerAgentText({links: settings.links}),
+ command,
+ install,
+ };
}
export {displayHomePath};
@@ -306,7 +330,7 @@ export {displayHomePath};
* 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}>}}
+ * @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, runner: boolean}>}}
*/
export function releaseFacts(cwd, {project}) {
const answered = answeredBy(cwd);
@@ -333,6 +357,9 @@ export function releaseFacts(cwd, {project}) {
searchPathCommands: astryxCommandsOnSearchPath().map(row => ({
...row,
upgrade: row.cliRoot ? globalUpgradeCommand(row.cliRoot) : null,
+ // A package runner's temporary install, which it puts first on the
+ // search path only for the run it starts.
+ runner: row.cliRoot ? installPlaceOf(row.cliRoot).runner : false,
})),
};
}
diff --git a/packages/cli/api/doctor/doctor.mjs b/packages/cli/api/doctor/doctor.mjs
index 8596a7ed6e..16e76a4f2a 100644
--- a/packages/cli/api/doctor/doctor.mjs
+++ b/packages/cli/api/doctor/doctor.mjs
@@ -66,6 +66,7 @@ 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, RUN_FROM_PROJECT, upgradeLine} from '../../foundation/release/notices.mjs';
+import {COMPUTER_COMMAND, COMPUTER_INSTALL_STEP} from '../../foundation/agent-docs/computer-agent-text.mjs';
import {alignCommand, addCliCommandFor, computerAgentTextState, installCommandFor, insideProjectElsewhere, projectCoreVersion, projectHasOwnCli, computerIntegrationsOutside, computerIntegrationsToAdd, displayHomePath, outsideProject, releaseFacts} from './_adapter.mjs';
/**
@@ -1491,6 +1492,10 @@ export function checkCliCommand(ctx) {
* 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 | null} [agentTextCommand] the command the skill file
+ * tells agents to run, or null
+ * @property {string | null} [agentTextInstall] the install step the skill
+ * file records for when that command is not found, or null
* @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
@@ -1503,7 +1508,7 @@ export function checkCliCommand(ctx) {
* 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]
+ * @property {Array<import('../../foundation/env/search-path.mjs').SearchPathCommand & {upgrade?: string | null, runner?: boolean}>} [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]
@@ -1714,6 +1719,8 @@ export function checkComputerAgentText(ctx) {
};
}
const entries = ctx.agentText ?? /** @type {NonNullable<typeof state>} */ (state).entries;
+ const command = ctx.agentText ? (ctx.agentTextCommand ?? null) : /** @type {NonNullable<typeof state>} */ (state).command;
+ const recorded = (ctx.agentText ? ctx.agentTextInstall : /** @type {NonNullable<typeof state>} */ (state).install) ?? null;
const fix = `Run \`${formatCliCommand('astryx init --user', ctx.cwd)}\`.`;
const [file, ...links] = entries;
const home = (/** @type {{path: string}} */ e) => displayHomePath(e.path);
@@ -1742,9 +1749,29 @@ export function checkComputerAgentText(ctx) {
};
}
const current = file.state === 'current';
+ const status = `${current ? 'The computer-level agent text matches this release' : "The computer-level agent text differs from this release's"}: ${home(file)}.`;
+ // The skill outlives the CLI it names when the home folder outlasts the
+ // folder the CLI is installed in, as on a machine whose system folders
+ // reset on restart. Reported only when no `astryx` command is on the search
+ // path at all, apart from a package runner's own copy, which it puts first
+ // only for the run it starts (the way back when the global CLI is gone).
+ // Any other `astryx`, even one the scan cannot trace to the package, such
+ // as the shim of Volta, asdf or mise, may well run the CLI, so doctor stays
+ // quiet here and cli-on-path reports what it can; never a false "gone".
+ // The reinstalled copy refreshes the text too.
+ const rows = ctx.searchPathCommands;
+ if (command === COMPUTER_COMMAND && rows && !rows.some(r => !r.runner)) {
+ return {
+ ...base,
+ message: `${status} It tells agents to run \`${COMPUTER_COMMAND}\`, but no \`${COMPUTER_COMMAND}\` command is on the search path, so agents that read it find no CLI to run (as when a restart removes the CLI installed for the computer and keeps the home folder).${linkNote}`,
+ fix: recorded
+ ? `Run \`${recorded}\`, the step the skill names for when \`${COMPUTER_COMMAND}\` is not found.`
+ : `Install it for the computer: \`${COMPUTER_INSTALL_STEP}\`.`,
+ };
+ }
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}`,
+ message: `${status}${linkNote}`,
...(!current || missing.length > 0 || dangling.length > 0 ? {fix} : {}),
};
}
diff --git a/packages/cli/assets/docs/tree/ci-and-containers.doc.mjs b/packages/cli/assets/docs/tree/ci-and-containers.doc.mjs
index 5a118506b7..622ae4d76a 100644
--- a/packages/cli/assets/docs/tree/ci-and-containers.doc.mjs
+++ b/packages/cli/assets/docs/tree/ci-and-containers.doc.mjs
@@ -24,6 +24,9 @@ export const docs = {
'docker',
'read-only home',
'cache the release cache',
+ 'agent machine',
+ 'restart',
+ 'ephemeral machine',
],
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.",
@@ -74,6 +77,16 @@ export const docs = {
},
],
},
+ {
+ id: 'short-lived',
+ title: 'Machines that keep only the home folder',
+ content: [
+ {
+ type: 'prose',
+ text: 'Some agent machines keep the home folder across restarts but not system folders. A global install there disappears on restart while the agent guide in the home folder stays, so agents are told to run a global astryx command that is gone; the guide says to run the command that installed the CLI, such as `npm i -g @astryxdesign/cli`, when that command is not found, and `astryx doctor` names the same step. To keep the CLI across restarts, install it into a folder in your home and put its `bin` folder on your PATH, as for a permission error ({@link generic:install-once}), or run that command when the machine starts.',
+ },
+ ],
+ },
{
id: 'more',
title: 'More on global mode',
diff --git a/packages/cli/clients/cli/commands/doctor.doc.mjs b/packages/cli/clients/cli/commands/doctor.doc.mjs
index fba76c3418..ae02d51e74 100644
--- a/packages/cli/clients/cli/commands/doctor.doc.mjs
+++ b/packages/cli/clients/cli/commands/doctor.doc.mjs
@@ -21,7 +21,7 @@ export const doc = {
"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). ' +
+ "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); when that text names `astryx` and no `astryx` command is on the search path, apart from a package runner's own copy, it says so and names the install step the text records, or npm's when it records none. " +
'It never fails a check because the folder has no project.',
fn: 'doctor',
subcommands: ['integration'],
diff --git a/packages/cli/clients/cli/commands/outside-project.test.mjs b/packages/cli/clients/cli/commands/outside-project.test.mjs
index 650f688375..5cd5459f8d 100644
--- a/packages/cli/clients/cli/commands/outside-project.test.mjs
+++ b/packages/cli/clients/cli/commands/outside-project.test.mjs
@@ -392,6 +392,97 @@ describe('doctor: the computer-level agent text', () => {
const A = '/home/me/.agents/skills/astryx/SKILL.md';
const C = '/home/me/.claude/skills/astryx';
+ it('a skill naming `astryx` with no Astryx CLI on the search path: says whether it is current, and names the step it records', () => {
+ const check = (/** @type {Record<string, any>} */ over) =>
+ checkComputerAgentText({
+ nodeVersion: '22.13.0',
+ answeredBy: {cli: '1.2.0', core: '1.2.0', copy: 'carried'},
+ latest: null,
+ agentText: [{path: A, state: 'current'}],
+ agentTextCommand: 'astryx',
+ searchPathCommands: [],
+ cwd: os.tmpdir(),
+ ...over,
+ });
+ const recorded = check({agentTextInstall: 'pnpm add -g @astryxdesign/cli'});
+ // A package runner's own copy first on the search path does not count.
+ expect(
+ check({
+ agentTextInstall: 'pnpm add -g @astryxdesign/cli',
+ searchPathCommands: [
+ /** @type {any} */ ({
+ file: '/tmp/_npx/r/node_modules/.bin/astryx',
+ astryx: true,
+ runner: true,
+ }),
+ ],
+ }).fix,
+ ).toBe(
+ 'Run `pnpm add -g @astryxdesign/cli`, the step the skill names for when `astryx` is not found.',
+ );
+ expect(recorded.status).toBe('info');
+ expect(recorded.message).toContain(
+ `The computer-level agent text matches this release: ${A}. It tells agents to run \`astryx\`, but no \`astryx\` command is on the search path`,
+ );
+ expect(recorded.fix).toBe(
+ 'Run `pnpm add -g @astryxdesign/cli`, the step the skill names for when `astryx` is not found.',
+ );
+ // A skill from an earlier release records no step: npm's, worded as
+ // cli-on-path words it.
+ const older = check({
+ agentText: [{path: A, state: 'differs'}],
+ agentTextInstall: null,
+ });
+ expect(older.message).toContain(
+ "The computer-level agent text differs from this release's",
+ );
+ expect(older.fix).toBe(
+ 'Install it for the computer: `npm i -g @astryxdesign/cli`.',
+ );
+ // With the Astryx CLI anywhere on the search path, even behind another
+ // program (cli-on-path's to report), or a skill naming a host's command,
+ // there is nothing to restore.
+ for (const over of [
+ {
+ searchPathCommands: [
+ /** @type {any} */ ({
+ file: '/usr/bin/astryx',
+ astryx: true,
+ version: '1.2.0',
+ }),
+ ],
+ },
+ {
+ searchPathCommands: [
+ /** @type {any} */ ({file: '/opt/other/astryx', astryx: false}),
+ /** @type {any} */ ({
+ file: '/usr/bin/astryx',
+ astryx: true,
+ version: '1.2.0',
+ }),
+ ],
+ },
+ {agentTextCommand: 'acme astryx'},
+ // An `astryx` the scan cannot trace (a Volta, asdf or mise shim, or
+ // another program): it may run the CLI, so no report here.
+ {
+ searchPathCommands: [
+ /** @type {any} */ ({
+ file: '/home/me/.volta/bin/astryx',
+ astryx: false,
+ runner: false,
+ }),
+ ],
+ },
+ // Only a package runner's own copy: the CLI is still gone.
+ ]) {
+ const other = check(over);
+ expect(other.message).toBe(
+ `The computer-level agent text matches this release: ${A}.`,
+ );
+ }
+ });
+
it('present and current, linked: no fix', () => {
const check = at([
{path: A, state: 'current'},
@@ -460,6 +551,14 @@ describe('doctor: the computer-level agent text', () => {
const home = tmpDir('home');
vi.stubEnv('HOME', home);
vi.stubEnv('USERPROFILE', home);
+ // The CLI installed for the computer, first on the search path, as the
+ // skill expects.
+ const bin = tmpDir('bin');
+ fs.symlinkSync(
+ path.join(CLI_ROOT, 'clients', 'cli', 'bin', 'astryx.mjs'),
+ path.join(bin, 'astryx'),
+ );
+ vi.stubEnv('PATH', `${bin}${path.delimiter}${process.env.PATH ?? ''}`);
try {
const find = r =>
r.envelope.data.checks.find(c => c.id === 'computer-agent-text');
diff --git a/packages/cli/foundation/agent-docs/computer-agent-text.mjs b/packages/cli/foundation/agent-docs/computer-agent-text.mjs
index fedd842340..18070a0a5a 100644
--- a/packages/cli/foundation/agent-docs/computer-agent-text.mjs
+++ b/packages/cli/foundation/agent-docs/computer-agent-text.mjs
@@ -43,6 +43,10 @@ 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 {CLI_ROOT} from '../fs/paths.mjs';
+import {CLI_PACKAGE} from '../env/package-manager.mjs';
+import {isGlobalCopy} from '../release/choose.mjs';
+import {globalUpgradeCommand} from '../release/notices.mjs';
import {
MARKER_START,
MARKER_END,
@@ -57,6 +61,83 @@ 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';
+/**
+ * What to do when the `astryx` command the text names is not found, as on a
+ * machine whose home folder outlives its system folders: the skill file
+ * survives a restart while the CLI installed for the computer does not.
+ * @param {string} install the install step
+ * @returns {string}
+ */
+export function computerRestoreLine(install) {
+ return `If \`${COMPUTER_COMMAND}\` is not found, run \`${install}\` first.`;
+}
+
+/**
+ * The step the CLI installed for the computer names for itself: the command
+ * that installs it again with the same package manager into the same folder,
+ * as the update notice names it but with no version. Null for any other copy.
+ * @param {string} [cliRoot]
+ * @returns {string | null}
+ */
+function ownInstallStep(cliRoot = CLI_ROOT) {
+ try {
+ if (isGlobalCopy(cliRoot)) {
+ return globalUpgradeCommand(cliRoot).replace(
+ `${CLI_PACKAGE}@latest`,
+ CLI_PACKAGE,
+ );
+ }
+ } catch {
+ // A copy whose install cannot be read names none of its own.
+ }
+ return null;
+}
+
+/**
+ * The step the skill file in `home` records, or null.
+ * @param {string} home
+ * @returns {string | null}
+ */
+function recordedInstallStep(home) {
+ try {
+ return skillInstallStepOf(fs.readFileSync(computerSkillFile(home), 'utf8'));
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * The install step the text names. `judge`: the step a file is judged by, the
+ * one it records first, so every copy of one release, two global installs
+ * included, finds the same text current. `write`: the step a write records,
+ * the global copy's own first, since only the CLI installed for the computer
+ * chooses it. Either way npm's when there is no other.
+ * @param {{cliRoot?: string, home?: string, for?: 'judge' | 'write'}} [options]
+ * @returns {string}
+ */
+export function computerInstallStep({
+ cliRoot = CLI_ROOT,
+ home = os.homedir(),
+ for: use = 'write',
+} = {}) {
+ const own = ownInstallStep(cliRoot);
+ const recorded = recordedInstallStep(home);
+ return (
+ (use === 'judge' ? (recorded ?? own) : (own ?? recorded)) ??
+ COMPUTER_INSTALL_STEP
+ );
+}
+
+/**
+ * The install step a skill file's text records, or null when it records
+ * none.
+ * @param {string} content
+ * @returns {string | null}
+ */
+export function skillInstallStepOf(content) {
+ return /is not found, run `(.+?)` first\./u.exec(content)?.[1] ?? null;
+}
+
/** The skill folder, relative to the home folder, that holds the one file. */
const SKILL_FOLDER = path.join('.agents', 'skills', 'astryx');
@@ -170,11 +251,13 @@ export function computerAgentCommand() {
}
/**
- * The body lines, with `run` as the command.
+ * The body lines, with `run` as the command and `install` as the step that
+ * installs it.
* @param {string} run
+ * @param {string} install
* @returns {string[]}
*/
-function bodyLines(run) {
+function bodyLines(run, install) {
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.',
@@ -190,16 +273,30 @@ function bodyLines(run) {
WORKFLOW_TITLE,
...WORKFLOW_STEPS.map(step => step.replaceAll('`astryx ', `\`${run} `)),
`Before you deliver, re-read each file; ${SELF_CHECK_CSS}. Then build the project and deliver that build, not a description of it.`,
+ // A host's door is the host's to restore; only the global command has an
+ // install step to name.
+ ...(run === COMPUTER_COMMAND ? [computerRestoreLine(install)] : []),
];
}
+/**
+ * The command a skill file's text names: the one in its "Start with" line,
+ * or null when the text has none.
+ * @param {string} content
+ * @returns {string | null}
+ */
+export function skillCommandOf(content) {
+ return /Start with `(.+?) search '/u.exec(content)?.[1] ?? null;
+}
+
/**
* The full skill file.
- * @param {{command?: string}} [options]
+ * @param {{command?: string, install?: string}} [options]
* @returns {string}
*/
export function renderComputerAgentText({
command = computerAgentCommand(),
+ install = COMPUTER_INSTALL_STEP,
} = {}) {
return withHash(
[
@@ -211,7 +308,7 @@ export function renderComputerAgentText({
'---',
'',
MARKER_START,
- ...bodyLines(command),
+ ...bodyLines(command, install),
MARKER_END,
'',
].join('\n'),
@@ -419,7 +516,10 @@ export function inspectComputerAgentText({
command,
links = [],
} = {}) {
- const expected = renderComputerAgentText({command});
+ const expected = renderComputerAgentText({
+ command,
+ install: computerInstallStep({home, for: 'judge'}),
+ });
const folder = path.join(home, SKILL_FOLDER);
const made = new Set(links);
return [
@@ -532,12 +632,24 @@ function writeCopy(at, expected) {
* @returns {{rows: import('../../api/init/init.type.mjs').InitUserFile[], links: string[]}}
*/
export function writeComputerAgentText({home = os.homedir(), command} = {}) {
- const expected = renderComputerAgentText({command});
+ // Judged by the step the file records, so a file another copy of this
+ // release wrote stays as it is; a write records this copy's own step.
+ const judged = renderComputerAgentText({
+ command,
+ install: computerInstallStep({home, for: 'judge'}),
+ });
const file = computerSkillFile(home);
const folder = path.dirname(file);
/** @type {import('../../api/init/init.type.mjs').InitUserFile[]} */
const rows = [];
- const state = stateOf(file, expected);
+ const state = stateOf(file, judged);
+ const expected =
+ state === 'current'
+ ? judged
+ : renderComputerAgentText({
+ command,
+ install: computerInstallStep({home, for: 'write'}),
+ });
if (state === 'foreign' || state === 'edited') {
rows.push({path: file, action: 'kept', reason: keptReason(state)});
} else if (state === 'current') {
diff --git a/packages/cli/foundation/agent-docs/computer-agent-text.test.mjs b/packages/cli/foundation/agent-docs/computer-agent-text.test.mjs
index 94d5af147c..56b5e84328 100644
--- a/packages/cli/foundation/agent-docs/computer-agent-text.test.mjs
+++ b/packages/cli/foundation/agent-docs/computer-agent-text.test.mjs
@@ -24,7 +24,9 @@ import {
computerSkillLinks,
inspectComputerAgentText,
removeComputerAgentText,
+ computerInstallStep,
renderComputerAgentText,
+ skillInstallStepOf,
writeComputerAgentText,
} from './computer-agent-text.mjs';
import {
@@ -155,6 +157,80 @@ describe('renderComputerAgentText', () => {
expect(text).toContain("`acme astryx search '<what you need>'`");
expect(text).not.toMatch(/`astryx /u);
});
+
+ // A machine can keep the home folder and lose the CLI installed for the
+ // computer, so the skill says how to get it back, with no version.
+ it('names the install step for when `astryx` is not found, and only for the global command', () => {
+ expect(
+ renderComputerAgentText({
+ command: 'astryx',
+ install: 'npm i -g @astryxdesign/cli',
+ }),
+ ).toContain(
+ 'If `astryx` is not found, run `npm i -g @astryxdesign/cli` first.',
+ );
+ // It repeats the step that installed the copy writing it, which doctor
+ // reads back.
+ const bun = renderComputerAgentText({
+ command: 'astryx',
+ install: 'bun add -g @astryxdesign/cli',
+ });
+ expect(bun).toContain(
+ 'If `astryx` is not found, run `bun add -g @astryxdesign/cli` first.',
+ );
+ expect(skillInstallStepOf(bun)).toBe('bun add -g @astryxdesign/cli');
+ });
+
+ // Rendering is pure: its default step never depends on the skill in the
+ // home folder of the computer the test runs on.
+ it("renders npm's step by default, whatever skill the caller's home folder holds", () => {
+ const home = tmp('caller-home');
+ const file = computerSkillFile(home);
+ fs.mkdirSync(path.dirname(file), {recursive: true});
+ fs.writeFileSync(
+ file,
+ renderComputerAgentText({
+ command: 'astryx',
+ install: 'pnpm add -g @astryxdesign/cli',
+ }),
+ );
+ const saved = process.env.HOME;
+ process.env.HOME = home;
+ try {
+ expect(renderComputerAgentText({command: 'astryx'})).toContain(
+ 'run `npm i -g @astryxdesign/cli` first.',
+ );
+ } finally {
+ process.env.HOME = saved;
+ }
+ });
+
+ // Only the CLI installed for the computer chooses the step; every other
+ // copy of the release, such as a project's own CLI, keeps the one the file
+ // records, so it neither reports the file as different nor rewrites it.
+ it('keeps the step the file records for a copy that is not installed for the computer', () => {
+ const home = tmp('home');
+ const file = computerSkillFile(home);
+ fs.mkdirSync(path.dirname(file), {recursive: true});
+ const pnpm = renderComputerAgentText({
+ command: 'astryx',
+ install: 'pnpm add -g @astryxdesign/cli',
+ });
+ fs.writeFileSync(file, pnpm);
+ expect(computerInstallStep({home})).toBe('pnpm add -g @astryxdesign/cli');
+ expect(inspectComputerAgentText({home, command: 'astryx'})[0].state).toBe(
+ 'current',
+ );
+ writeComputerAgentText({home, command: 'astryx'});
+ expect(fs.readFileSync(file, 'utf8')).toBe(pnpm);
+ // No file yet: npm's step.
+ expect(computerInstallStep({home: tmp('empty-home')})).toBe(
+ 'npm i -g @astryxdesign/cli',
+ );
+ expect(renderComputerAgentText({command: 'acme astryx'})).not.toContain(
+ 'npm i -g',
+ );
+ });
});
describe('the link table', () => {
diff --git a/packages/cli/test/global-local.test.mjs b/packages/cli/test/global-local.test.mjs
index 6cd4d33196..7fdef447a0 100644
--- a/packages/cli/test/global-local.test.mjs
+++ b/packages/cli/test/global-local.test.mjs
@@ -808,6 +808,232 @@ describe.skipIf(!POSIX)(
).toBe('warn');
});
+ it('the skill outlives the CLI installed for the computer: it repeats the step that installed it, and doctor names it too', () => {
+ for (const [layout, step] of /** @type {const} */ ([
+ // The npm layout is a prefix in the home folder, so the step names it.
+ ['npm', 'npm i -g --prefix ~/.npm-global @astryxdesign/cli'],
+ ['pnpm', 'pnpm add -g @astryxdesign/cli'],
+ ['bun', 'bun add -g @astryxdesign/cli'],
+ ])) {
+ const pc = computer();
+ let g;
+ if (layout === 'bun') {
+ // Bun's global folder, as `bun add -g` makes it.
+ const global = path.join(pc.home, '.bun', 'install', 'global');
+ writeJson(path.join(global, 'package.json'), {
+ dependencies: {'@astryxdesign/cli': '9.0.0'},
+ });
+ fs.writeFileSync(path.join(global, 'bun.lock'), '{}');
+ const placed = placeCli(
+ path.join(global, 'node_modules', '@astryxdesign', 'cli'),
+ '9.0.0',
+ );
+ const binDir = path.join(pc.home, '.bun', 'bin');
+ fs.mkdirSync(binDir, {recursive: true});
+ fs.symlinkSync(placed.bin, path.join(binDir, 'astryx'));
+ g = {...placed, binDir};
+ } else {
+ g = globalCli(layout, '9.0.0', {root: pc.home});
+ }
+ pc.path.unshift(g.binDir);
+ const empty = tempDir('empty');
+ expect(run(g.bin, ['init', '--user'], {cwd: empty, pc}).status).toBe(0);
+ const skill = path.join(
+ pc.home,
+ '.agents',
+ 'skills',
+ 'astryx',
+ 'SKILL.md',
+ );
+ expect(fs.readFileSync(skill, 'utf8')).toContain(
+ `If \`astryx\` is not found, run \`${step}\` first.`,
+ );
+ // A restart removes the CLI installed for the computer and keeps the
+ // home folder. The way back is a package runner, whose own temporary
+ // copy answers; started directly, and with the runner's .bin folder
+ // first on the search path, as npx and pnpm dlx put it. That copy
+ // does not count, so doctor names the step either way.
+ fs.rmSync(path.join(g.binDir, 'astryx'));
+ fs.rmSync(g.dir, {recursive: true, force: true});
+ pc.path.splice(pc.path.indexOf(g.binDir), 1);
+ const runner = placeCli(
+ path.join(
+ tempDir('npx'),
+ '_npx',
+ 'r1',
+ 'node_modules',
+ '@astryxdesign',
+ 'cli',
+ ),
+ '9.0.0',
+ );
+ const runnerBin = path.join(
+ path.dirname(path.dirname(runner.dir)),
+ '.bin',
+ );
+ fs.mkdirSync(runnerBin, {recursive: true});
+ fs.symlinkSync(runner.bin, path.join(runnerBin, 'astryx'));
+ const agentText = () =>
+ JSON.parse(
+ run(runner.bin, ['doctor', '--json'], {cwd: empty, pc}).stdout,
+ ).data.checks.find(
+ (/** @type {any} */ c) => c.id === 'computer-agent-text',
+ );
+ for (const first of [false, true]) {
+ if (first) pc.path.unshift(runnerBin);
+ const check = agentText();
+ expect(check.message).toContain(
+ 'but no `astryx` command is on the search path',
+ );
+ expect(check.fix).toBe(
+ `Run \`${step}\`, the step the skill names for when \`astryx\` is not found.`,
+ );
+ }
+ pc.path.shift();
+ }
+ });
+
+ // Volta's command is a shim of its own, not a link into the package, so
+ // the search-path scan cannot trace it; an astryx on the search path that
+ // cannot be traced may run the CLI, so doctor never calls it gone.
+ it("on a working Volta install, doctor does not report the skill's CLI as gone", () => {
+ const pc = computer();
+ const g = globalCli('volta', '9.0.0', {root: pc.home});
+ fs.rmSync(path.join(g.binDir, 'astryx'));
+ fs.writeFileSync(
+ path.join(g.binDir, 'astryx'),
+ '#!/bin/sh\n# volta-shim\nexit 0\n',
+ );
+ fs.chmodSync(path.join(g.binDir, 'astryx'), 0o755);
+ pc.path.unshift(g.binDir);
+ const empty = tempDir('empty');
+ expect(run(g.bin, ['init', '--user'], {cwd: empty, pc}).status).toBe(0);
+ const check = JSON.parse(
+ run(g.bin, ['doctor', '--json'], {cwd: empty, pc}).stdout,
+ ).data.checks.find(
+ (/** @type {any} */ c) => c.id === 'computer-agent-text',
+ );
+ expect(check.message).toContain('matches this release');
+ expect(check.message).not.toContain('no `astryx` command');
+ expect(check.fix).toBeUndefined();
+ // Run through a package runner's copy too, its .bin first on the
+ // search path, as npx puts it: Volta's shim still counts.
+ const runner = placeCli(
+ path.join(
+ tempDir('npx'),
+ '_npx',
+ 'v1',
+ 'node_modules',
+ '@astryxdesign',
+ 'cli',
+ ),
+ '9.0.0',
+ );
+ const runnerBin = path.join(
+ path.dirname(path.dirname(runner.dir)),
+ '.bin',
+ );
+ fs.mkdirSync(runnerBin, {recursive: true});
+ fs.symlinkSync(runner.bin, path.join(runnerBin, 'astryx'));
+ pc.path.unshift(runnerBin);
+ const viaRunner = JSON.parse(
+ run(runner.bin, ['doctor', '--json'], {cwd: empty, pc}).stdout,
+ ).data.checks.find(
+ (/** @type {any} */ c) => c.id === 'computer-agent-text',
+ );
+ expect(viaRunner.message).not.toContain('no `astryx` command');
+ expect(viaRunner.fix).toBeUndefined();
+ });
+
+ // Any `astryx` the scan cannot trace, such as an asdf or mise shim, may
+ // run the CLI: doctor stays quiet rather than call it gone.
+ it("with an untraceable astryx shim on the search path, doctor run through a package runner does not report the skill's CLI as gone", () => {
+ const pc = computer();
+ const g = globalCli('npm', '9.0.0', {root: pc.home});
+ pc.path.unshift(g.binDir);
+ const empty = tempDir('empty');
+ expect(run(g.bin, ['init', '--user'], {cwd: empty, pc}).status).toBe(0);
+ pc.path.splice(pc.path.indexOf(g.binDir), 1);
+ const shims = path.join(pc.home, '.asdf', 'shims');
+ fs.mkdirSync(shims, {recursive: true});
+ fs.writeFileSync(
+ path.join(shims, 'astryx'),
+ '#!/bin/sh\nexec asdf exec astryx "$@"\n',
+ );
+ fs.chmodSync(path.join(shims, 'astryx'), 0o755);
+ pc.path.unshift(shims);
+ const runner = placeCli(
+ path.join(
+ tempDir('npx'),
+ '_npx',
+ 'a1',
+ 'node_modules',
+ '@astryxdesign',
+ 'cli',
+ ),
+ '9.0.0',
+ );
+ const check = JSON.parse(
+ run(runner.bin, ['doctor', '--json'], {cwd: empty, pc}).stdout,
+ ).data.checks.find(
+ (/** @type {any} */ c) => c.id === 'computer-agent-text',
+ );
+ expect(check.message).not.toContain('no `astryx` command');
+ expect(check.fix).toBeUndefined();
+ });
+
+ it('with the global copy on the search path, doctor gives no restore report', () => {
+ const pc = computer();
+ const g = globalCli('npm', '9.0.0', {root: pc.home});
+ pc.path.unshift(g.binDir);
+ const empty = tempDir('empty');
+ expect(run(g.bin, ['init', '--user'], {cwd: empty, pc}).status).toBe(0);
+ const check = JSON.parse(
+ run(g.bin, ['doctor', '--json'], {cwd: empty, pc}).stdout,
+ ).data.checks.find(
+ (/** @type {any} */ c) => c.id === 'computer-agent-text',
+ );
+ expect(check.message).toContain('matches this release');
+ expect(check.message).not.toContain('no `astryx` command');
+ expect(check.fix).toBeUndefined();
+ });
+
+ it('two global installs of one release find the same skill current, and neither rewrites the step the other wrote', () => {
+ const pc = computer();
+ const npm = globalCli('npm', '9.0.0', {root: pc.home});
+ const pnpm = globalCli('pnpm', '9.0.0', {root: pc.home});
+ pc.path.unshift(npm.binDir, pnpm.binDir);
+ const empty = tempDir('empty');
+ const skill = path.join(
+ pc.home,
+ '.agents',
+ 'skills',
+ 'astryx',
+ 'SKILL.md',
+ );
+ expect(run(npm.bin, ['init', '--user'], {cwd: empty, pc}).status).toBe(0);
+ const written = fs.readFileSync(skill, 'utf8');
+ expect(written).toContain(
+ 'run `npm i -g --prefix ~/.npm-global @astryxdesign/cli` first.',
+ );
+ const fromPnpm = JSON.parse(
+ run(pnpm.bin, ['--json', 'init', '--user'], {cwd: empty, pc}).stdout,
+ );
+ expect(
+ fromPnpm.data.files.find((/** @type {any} */ f) => f.path === skill)
+ .action,
+ ).toBe('unchanged');
+ expect(fs.readFileSync(skill, 'utf8')).toBe(written);
+ const doctor = JSON.parse(
+ run(pnpm.bin, ['doctor', '--json'], {cwd: empty, pc}).stdout,
+ );
+ expect(
+ doctor.data.checks.find(
+ (/** @type {any} */ c) => c.id === 'computer-agent-text',
+ ).message,
+ ).toContain('matches this release');
+ });
+
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'])) {