An open source design system that's fully customizable and agent ready
TypeScript
fix(cli): init writes agent docs every agent reads, at the project root, never in the home folder (#7497)
Joeyb74cf213e638
diff --git a/.changeset/init-agent-docs-one-copy.md b/.changeset/init-agent-docs-one-copy.mdnew file mode 100644index 0000000000..6ed9cf2da2--- /dev/null+++ b/.changeset/init-agent-docs-one-copy.md@@ -0,0 +1,20 @@+---+'@astryxdesign/cli': patch+'@astryxdesign/core': patch+---++[fix] `astryx init` writes the agent docs at the project root, in files the project commits, so that Codex, Gemini CLI, Copilot CLI and Claude Code all read the block, from the project root or any folder below it. It no longer writes agent docs into a project's subfolder, the home folder, or a settings folder in it such as `~/.gemini`.+@josephfarina++- `AGENTS.md` holds the block, created when missing. Before, a project with only `CLAUDE.md` got the block only there, so Codex and Gemini CLI never saw it.+- Claude Code skips `AGENTS.md` in a folder that has a `CLAUDE.md` or `.claude/CLAUDE.md`, so the Claude Code file the project already has keeps a full copy: root `CLAUDE.md`, else `.claude/CLAUDE.md`. It keeps the copy even when it imports `AGENTS.md`, because Claude Code does not follow that import in a session started in a subfolder; started at the root, Claude Code then reads two. When both exist, the copy goes in root `CLAUDE.md`, which projects commit even when they ignore `.claude/`, and a block in `.claude/CLAUDE.md` is removed. Init creates no Claude file. `astryx upgrade` refreshes every copy, except in a project at the top of a home settings folder (below).+- Gemini CLI reads only `GEMINI.md`: init adds a one-line import, `@./AGENTS.md`, creating `GEMINI.md` when it is missing. It adds none when `GEMINI.md` already imports `AGENTS.md`, inline or on its own line. It adds the import even when the project's `.gemini/settings.json` has Gemini read `AGENTS.md` through `context.fileName`: Gemini loads those settings only when it starts at the project root, so a session started in a subfolder would otherwise get no copy. Started at the root, Gemini then reads two.+- The project root is the nearest folder at or above where init runs whose `package.json` declares an `@astryxdesign` package, else the nearest with any `package.json`. The search stops at a repository root and never counts the home folder. With no `package.json` found, init writes where it runs, as before. `docsWritten` still lists each file relative to where init ran, for example `../../AGENTS.md`.+- In the home folder, or in a settings folder in it such as `~/.gemini` or `~/.claude` outside a project, init writes no agent docs, reports `docsError` as `install-failed` with the reason, and still exits 0. This is a compatible fix under `architecture:cli-surface` INV31 (where init writes, and that no mode writes agent docs into the home folder or a settings folder in it) and INV10a (a refusal of a write outside its confined root, made before anything is written). The refused inputs: the home folder itself, and the top of a folder of the home folder whose name starts with a dot (every such folder is a settings folder), even when it holds a `package.json`; a folder below it with its own `package.json` is a project. With `--agent-docs-path`, each file's own folder is checked: from the home folder, `notes/AI.md` is written as before, while `AI.md` or `.claude/CLAUDE.md` is refused. How it fails: no agent docs are written, `docsError` is `install-failed` with the reason, and the exit status stays 0, as before. Migration: run `astryx init` from the project's own folder, or add the block to the file by hand. A project inside a settings folder, such as an agent worktree in `~/.codex/worktrees/` or `~/.cursor/worktrees/`, is set up normally, and `astryx upgrade` refreshes it. Agents read the files in those folders in every project. Run `astryx init --remove-agents` in the home folder to remove a block an earlier version wrote into `~/.claude/CLAUDE.md`. `astryx upgrade` refuses the same folders when it would refresh a block there (INV10a), with or without `--apply`, and with no block there it gives the same reason instead of suggesting `astryx init`; `astryx doctor`'s agent-docs fix and the setup reminder after each command do the same, the reminder by staying quiet. The refused input: a project whose root is the home folder or the top of a settings folder, such as `~/.dotfiles` with a `package.json`. How it fails: the block is left as it is, `agentDocs.action` is `error` (never `would-refresh`), and the warning names the folder and why; the upgrade's other steps and its exit status are as before. Migration: move the project into a folder of its own, or update or remove the block there by hand.+- A `GEMINI.md` that resolves outside the project, for example a link to a shared file, is skipped and reported in `docsError` with one note (not an error line), in the default layout and in a project's own layout; the rest is written and init exits 0.+- The managed block is Astryx-owned (`architecture:cli-surface` INV31): init and `astryx upgrade` write, refresh, and remove only the block, whatever ignore rules or generated markers say, as 0.7.1 did, and never change the text around it. Every write stays inside the project (INV10): run in the folder 0.7.1 wrote, an agent file 0.7.1 wrote there whose path leaves the project still refuses the run with exit 1. The project's Claude Code file (root `CLAUDE.md`, or `.claude/CLAUDE.md` when there is no root one) that resolves outside the project and is a block-less import of an existing `AGENTS.md`, which 0.7.1 left alone, is skipped and reported in `docsError` with one note, and init exits 0. Run from a folder below the project root, where 0.7.1 wrote in that folder instead, a project-root file whose path leaves the project is skipped and reported in `docsError` with one note, the rest is written, and init exits 0.+- While root `CLAUDE.md` is untracked and ignored by the repository's ignore rules (its ignore files from the repository root down, such as a monorepo's root `.gitignore`, its local exclude file, and configured excludes; init asks git, Sapling or Mercurial), a `.claude/CLAUDE.md` the project commits gets the copy too: one the repository tracks counts as committed whatever the ignore rules say, as git and Mercurial ignore only untracked files, and when the repository cannot answer the copy is kept, on the first run as on later ones, and `--agent claude` and `--agent all` write it there, so a fresh clone still gives Claude Code a copy. Such a copy that resolves outside the project refuses the run with exit 1 where 0.7.1 wrote it too; one 0.7.1 did not write (the one `--agent claude` adds, or a block-less import of an existing `AGENTS.md`) is skipped and reported in `docsError` with one note, and init exits 0. So is a `.claude/CLAUDE.md` whose block `--agent claude` would remove beside a `CLAUDE.md`, since 0.7.1's `claude` preset wrote only `CLAUDE.md` there. Beside a committed root `CLAUDE.md`, with `.claude` linked outside the project, three cases that 0.7.1 refused now exit 0 with nothing written: the default with a `.claude/CLAUDE.md` of plain text, and `--agent all` with one of plain text or a block-less import of `AGENTS.md`. 0.7.1 wrote that `.claude/CLAUDE.md`; now root `CLAUDE.md` holds the copy and the linked file gets none, so no write leaves the project and none needs refusing. In a project that keeps its own layout, a `GEMINI.md` that imports no agent file now gets a copy, as the other agent files do.+- The copy in `.claude/CLAUDE.md` is removed only once root `CLAUDE.md` holds the same block, and only the managed block between its markers: the rest of the file stays, and the file is deleted only when nothing but whitespace is left. `astryx init --remove-agents` deletes a file it created only when nothing but whitespace or init's own heading is left; 0.7.0 also deleted a file whose remaining text had a heading and any line with the word "guidance".+- `astryx init --remove-agents` removes the block at the project root, where `init` writes it, and in the folder it runs in. Run from a subfolder, it removes what `init` wrote at the root, and a block an earlier version left in that subfolder; a root agent file with a block that resolves outside the project is left as it is with a note, and the run exits 0, as 0.7.1 did when it touched only the subfolder. Exit codes and the JSON shape are unchanged.+- `--agent claude` and `--agent all` never leave a block in both `CLAUDE.md` and `.claude/CLAUDE.md`, unless the project ignores `CLAUDE.md`: when `CLAUDE.md` gets the block, a block in `.claude/CLAUDE.md` is removed. `--agent all` keeps the `GEMINI.md` import. The `--agent` help and the working-with-AI guide say so. `--agent-docs-path` writes where init runs, as before.+- `astryx doctor` fails when the `GEMINI.md` import points at an `AGENTS.md` with no block. The setup check in the CLI and in `@astryxdesign/core` no longer counts that import as set up, and looks at `GEMINI.md`. The reminder to run `init` that commands print looks at the project root too, so it stops once `init` has run in a nested package.diff --git a/apps/sandbox/.gitignore b/apps/sandbox/.gitignoreindex 5ec66e4e2e..2250577c95 100644--- a/apps/sandbox/.gitignore+++ b/apps/sandbox/.gitignore@@ -2,6 +2,7 @@ node_modules# Auto-generated by `astryx init --features agents` (postinstall)AGENTS.md+GEMINI.mdastryx.config.mjs.claude/CLAUDE.mddiff --git a/docs/architecture/cli-surface.md b/docs/architecture/cli-surface.mdindex ad78770916..63846caf3e 100644--- a/docs/architecture/cli-surface.md+++ b/docs/architecture/cli-surface.md@@ -305,14 +305,20 @@ validate` MUST warn on a PascalCase `.tsx` at the top of the components rootleast one copy, whether it starts at the project root or in a folder belowit, from files the project commits (DEC-2). `--agent` and `--agent-docs-path`name the files instead; an `--agent` preset still never leaves a copy in both- Claude Code files.+ Claude Code files, except as the ignored-root rule below says.- `AGENTS.md` at the project root holds the block. Init creates it when it ismissing.- The project's Claude Code file holds a full copy: root `CLAUDE.md`, else`.claude/CLAUDE.md`. It holds the copy even when it imports `AGENTS.md`,because Claude Code does not follow an import of a file above the folder itstarts in. While root `CLAUDE.md` holds a copy, `.claude/CLAUDE.md` holds- none. Init creates no Claude Code file, and a Claude Code file that is+ none, except while root `CLAUDE.md` is untracked and ignored by the+ repository's ignore rules, including its local exclude file and configured+ excludes: then a `.claude/CLAUDE.md` the project commits (tracked, or not+ ignored) holds a copy too, as it does when the repository cannot say, in+ the default layout and with the `claude` and `all` presets, so a fresh+ clone still gives Claude Code one.+ Init creates no Claude Code file, and a Claude Code file that is`AGENTS.md` under another name holds no second copy.- `GEMINI.md` holds a one-line managed import of `AGENTS.md`. Init createsit when it is missing, and adds no import to a `GEMINI.md` that already@@ -342,6 +348,8 @@ validate` MUST warn on a PascalCase `.tsx` at the top of the components root`astryx init --user` and the global copy's background step write it, asINV10 and FR8 state.- Upgrade refreshes every copy where it is and moves none.+ - The managed block is Astryx-owned: `spec:AST-040`'s protections cover+ consumer-owned content, not the block; INV10 still confines every write.- `--remove-agents` removes the block at the project root and in the workingfolder. Every file it would change resolves inside its own folder, or itchanges nothing.diff --git a/docs/specs/AST-040-consumer-file-modification/spec.md b/docs/specs/AST-040-consumer-file-modification/spec.mdindex 5c6077fbae..14244942bf 100644--- a/docs/specs/AST-040-consumer-file-modification/spec.md+++ b/docs/specs/AST-040-consumer-file-modification/spec.md@@ -116,7 +116,8 @@ CLI too old to finish the migration.- **FR8 — Every modification path follows this contract.** Core, integration,and configuration codemods, and any other operation that modifies existingconsumer files, MUST apply FR1–FR7 identically. A new modification path cannot- opt out, consistent with `spec:AST-017` FR16.+ opt out, consistent with `spec:AST-017` FR16. The managed agent-docs block is+ governed by `architecture:cli-surface` INV31.- **FR9 — An upgrade works on its project.** `astryx upgrade` MUST operate onthe project of the folder it runs in: the nearest folder at or above thatfolder whose `package.json` declares an Astryx package, or that its workspacediff --git a/packages/cli/api/doctor/doctor.mjs b/packages/cli/api/doctor/doctor.mjsindex a04a23292a..b3e56cc657 100644--- a/packages/cli/api/doctor/doctor.mjs+++ b/packages/cli/api/doctor/doctor.mjs@@ -28,7 +28,15 @@ import * as fs from 'node:fs';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 {+ AGENT_DOC_PATHS,+ holdsAstryxBlock,+} from '../../foundation/agent-docs/agent-doc-state.mjs';+import {+ agentDocsTargetDir,+ assertAgentDocsTarget,+ resolveAgentDocsRoot,+} from '../../foundation/agent-docs/agent-docs.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';@@ -610,6 +618,21 @@ export function checkConfiguredIntegrations(ctx) {};}+/**+ * Why init writes no agent docs for `cwd`, or null when it does: the folder+ * it would write to is the home folder or the top of a settings folder in it.+ * @param {string} cwd+ * @returns {string | null}+ */+function agentDocsRefusal(cwd) {+ try {+ assertAgentDocsTarget(agentDocsTargetDir(cwd));+ return null;+ } catch (err) {+ return err instanceof Error && err.name === 'AgentDocsHomeError' ? err.message : null;+ }+}+/*** Check 7 — agent docs exist and contain the Astryx section markers.* @param {DoctorContext} ctx@@ -617,8 +640,15 @@ export function checkConfiguredIntegrations(ctx) {*/export function checkAgentDocs(ctx) {// Every file init can write (one shared list), looked for in the working- // directory and in the project root: run from src/, the docs sit at the root.- const dirs = [...new Set([ctx.cwd, projectRootOf(ctx)])];+ // directory, the project root, and the folder init writes them to: run from+ // src/ or a nested package, the docs sit at the root.+ const dirs = [+ ...new Set(+ [ctx.cwd, projectRootOf(ctx), resolveAgentDocsRoot(ctx.cwd) ?? ctx.cwd].map(dir =>+ path.resolve(dir),+ ),+ ),+ ];const present = dirs.flatMap(dir =>AGENT_DOC_PATHS.map(rel => path.join(dir, rel)).filter(abs =>fs.existsSync(abs),@@ -626,6 +656,15 @@ export function checkAgentDocs(ctx) {);/** @param {string} abs */const shown = abs => path.relative(ctx.cwd, abs) || path.basename(abs);+ // In the home folder, or at the top of a settings folder in it, init+ // writes no agent docs (INV31), so the fix is moving the project or a hand+ // edit, never init.+ const refusal = agentDocsRefusal(ctx.cwd);+ /** @param {string} initFix */+ const fixFor = initFix =>+ refusal+ ? `${refusal} Move the project into a folder of its own, or edit the Astryx block in its agent file by hand.`+ : initFix;if (present.length === 0) {return {@@ -633,29 +672,64 @@ export function checkAgentDocs(ctx) {label: 'AI agent docs',status: 'info',message: `No agent docs found: looked for ${AGENT_DOC_PATHS.join(', ')} in ${dirs.map(dir => path.relative(ctx.cwd, dir) || '.').join(' and ')}.`,- fix: `Generate agent docs with \`${getCliInvocation(ctx.cwd)} init --features agents\`.`,+ fix: fixFor(+ `Generate agent docs with \`${getCliInvocation(ctx.cwd)} init --features agents\`.`,+ ),};}- const withMarkers = present.filter(abs => {+ /** @param {string} abs */+ const read = abs => {try {- const content = fs.readFileSync(abs, 'utf-8');- return (- (content.includes('<!-- ASTRYX:START -->') || content.includes('<!-- XDS:START -->')) &&- (content.includes('<!-- ASTRYX:END -->') || content.includes('<!-- XDS:END -->'))- );+ return fs.readFileSync(abs, 'utf-8');} catch {- return false;+ return '';}+ };+ const withMarkers = present.filter(abs => {+ const content = read(abs);+ return (+ (content.includes('<!-- ASTRYX:START -->') || content.includes('<!-- XDS:START -->')) &&+ (content.includes('<!-- ASTRYX:END -->') || content.includes('<!-- XDS:END -->')) &&+ holdsAstryxBlock(content)+ );});+ // A managed block that only imports another file (init's GEMINI.md import+ // of AGENTS.md) is broken when that file holds no block: the agents that+ // read either file get no Astryx docs.+ const dangling = present.flatMap(abs => {+ const match = /<!-- ASTRYX:START -->\s*@(\S+)\s*<!-- ASTRYX:END -->/.exec(read(abs));+ if (match == null) return [];+ const target = path.resolve(path.dirname(abs), match[1]);+ return holdsAstryxBlock(read(target)) ? [] : [{abs, target}];+ });+ if (dangling.length > 0) {+ return {+ id: 'agent-docs',+ label: 'AI agent docs',+ status: 'fail',+ message: dangling+ .map(+ ({abs, target}) =>+ `${shown(abs)} imports ${shown(target)}, which holds no Astryx block, so agents that read them get no Astryx docs.`,+ )+ .join(' '),+ fix: fixFor(+ `Write the block again with \`${getCliInvocation(ctx.cwd)} init --features agents\`.`,+ ),+ };+ }+if (withMarkers.length === 0) {return {id: 'agent-docs',label: 'AI agent docs',status: 'warn',message: `Agent docs present (${present.map(shown).join(', ')}) but no Astryx section markers found.`,- fix: `Add the Astryx section to your agent docs with \`${getCliInvocation(ctx.cwd)} init --features agents\`.`,+ fix: fixFor(+ `Add the Astryx section to your agent docs with \`${getCliInvocation(ctx.cwd)} init --features agents\`.`,+ ),};}diff --git a/packages/cli/api/init/init.doc.mjs b/packages/cli/api/init/init.doc.mjsindex 62bf19599d..7bc3424110 100644--- a/packages/cli/api/init/init.doc.mjs+++ b/packages/cli/api/init/init.doc.mjs@@ -17,11 +17,22 @@ export const doc = {'Non-interactive project setup: install agent docs and point at the theme + build workflows.',description:'Sets a project up with NO prompts, so it behaves identically for humans, ' +- 'agents, CI, and piped I/O. By default it installs the AGENTS.md/CLAUDE.md ' +- 'agent-docs cheat sheet, including guidance from configured integrations, and ' ++ 'agents, CI, and piped I/O. By default it writes the agent-docs cheat sheet, ' ++ 'including guidance from configured integrations, at the project root (the nearest ' ++ 'package.json that declares an @astryxdesign package, else the nearest package.json, ' ++ 'searching no higher than the repository root): to AGENTS.md, ' ++ "to the project's Claude Code file (CLAUDE.md, else .claude/CLAUDE.md; when CLAUDE.md " ++ 'exists, a block in .claude/CLAUDE.md is removed, unless the project ignores CLAUDE.md, in which case a ' ++ '.claude/CLAUDE.md the project commits keeps a copy), and as a ' ++ 'one-line import of AGENTS.md in GEMINI.md unless GEMINI.md already imports it. ' ++ 'In the home folder, or in a settings folder in it outside a project, it writes none: every ' ++ 'folder of the home folder whose name starts with a dot is a settings folder, and such a folder itself never ' ++ 'counts as a project, even with a package.json; a folder below it with a package.json does. ' ++ 'The managed block is Astryx-owned: it is written, refreshed, and removed whatever ignore rules ' ++ 'or generated markers say, and the text around it is never changed. It then ' +"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, at the project root and in `ctx.cwd`, 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.' +@@ -46,7 +57,7 @@ export const doc = {name: 'options.removeAgents',type: 'boolean',description:- 'Remove the managed agent-docs block instead of installing. With `user`, remove the computer-level agent text instead.',+ 'Remove the managed agent-docs block, at the project root and in `ctx.cwd`, instead of installing. With `user`, remove the computer-level agent text instead.',},{name: 'options.user',@@ -62,7 +73,10 @@ export const doc = {name: 'options.agent',type: 'string',description:- 'Agent preset: claude, cursor, codex, hermes, muse, all. Used only when the agents feature runs. Refused with `user`.',+ 'Agent preset: claude, cursor, codex, hermes, muse, all. `all` writes every existing agent doc except GEMINI.md, ' ++ 'which keeps its one-line import of AGENTS.md. With claude and all, when CLAUDE.md gets the block, a block in ' ++ '.claude/CLAUDE.md is removed, unless the project ignores CLAUDE.md, in which case a .claude/CLAUDE.md the ' ++ 'project commits gets a copy too. Used only when the agents feature runs. Refused with `user`.',},{name: 'options.agentDocsPath',@@ -122,7 +136,7 @@ export const doc = {},{code: 'ERR_PATH_TRAVERSAL',- when: 'the template output path resolves outside cwd (for example through a symlinked src directory), or, with removeAgents, a managed agent-docs file resolves outside cwd through a symlink',+ when: 'the template output path resolves outside cwd (for example through a symlinked src directory), or, with removeAgents, a managed agent-docs file in cwd, or at the project root when run there, resolves outside that folder through a symlink (run below the root, a project-root file is left as it is with a note)',},],examples: [diff --git a/packages/cli/api/init/init.test.mjs b/packages/cli/api/init/init.test.mjsindex f4ddbcd2df..8b9f157e54 100644--- a/packages/cli/api/init/init.test.mjs+++ b/packages/cli/api/init/init.test.mjs@@ -10,6 +10,7 @@import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';import * as fs from 'node:fs';+import * as os from 'node:os';import * as path from 'node:path';import {init, getNextSteps} from './init.mjs';import {logger} from '../logger.mjs';@@ -21,7 +22,8 @@ const MARKER_START = '<!-- ASTRYX:START -->';let tmpDir;beforeEach(() => {- tmpDir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-init-api-'));+ // Outside any package: init writes agent docs at the nearest package.json.+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-init-api-'));});afterEach(() => {@@ -30,6 +32,18 @@ afterEach(() => {/** @param {string} rel */const read = rel => fs.readFileSync(path.join(tmpDir, rel), 'utf8');++/**+ * Make tmpDir a project that declares Astryx: a folder that declares nothing+ * is outside a project, where init prints no getting-started steps (spec+ * AST-081 FR3).+ */+function asProject() {+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({name: 'app', dependencies: {'@astryxdesign/core': '*'}}),+ );+}/** @param {string} rel */const exists = rel => fs.existsSync(path.join(tmpDir, rel));@@ -58,6 +72,7 @@ function writeIntegration() {describe('init() — receipts + side effects', () => {it('default mode installs AGENTS.md and returns an init.run receipt', async () => {+ asProject();const res = await init({}, {cwd: tmpDir});expect(res.type).toBe('init.run');if (res.type !== 'init.run') return;@@ -217,6 +232,7 @@ describe('init() — logger', () => {});it('emits the install line + full next-steps through the shared logger', async () => {+ asProject();/** @type {string[]} */const lines = [];const logSpy = vi.spyOn(console, 'log').mockImplementation((...a) => lines.push(a.join(' ')));@@ -243,7 +259,7 @@ describe('init() — ASCII output', () => {const lines = [];const logSpy = vi.spyOn(console, 'log').mockImplementation((...a) => lines.push(a.join(' ')));const errSpy = vi.spyOn(console, 'error').mockImplementation((...a) => lines.push(a.join(' ')));- const empty = fs.mkdtempSync(path.join(process.cwd(), '.astryx-init-remove-'));+ const empty = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-init-remove-'));logger.setSilent(false);try {await init({}, {cwd: tmpDir});diff --git a/packages/cli/api/init/init.type.mjs b/packages/cli/api/init/init.type.mjsindex 1a28900739..eacf0b26f7 100644--- a/packages/cli/api/init/init.type.mjs+++ b/packages/cli/api/init/init.type.mjs@@ -10,8 +10,8 @@* @typedef {object} InitRunData* @property {'default' | 'features'} mode `default` (no flags) or `features` (--features/--all).* @property {string[]} features Features that were run, in order.- * @property {string[]} docsWritten Agent-doc files written (empty if agents weren't run or install failed).- * @property {{kind: 'path-safety' | 'install-failed', message?: string} | null} docsError Soft agent-docs failure, if any. `path-safety` also implies a non-zero exit.+ * @property {string[]} docsWritten Agent-doc files written, relative to the directory init ran in (empty if agents weren't run or install failed). Without --agent-docs-path they sit at the project root: the nearest folder at or above it whose package.json declares an Astryx package, else the nearest with any package.json, within its repository and never the home folder; with none, the directory init ran in.+ * @property {{kind: 'path-safety' | 'install-failed', message?: string} | null} docsError Soft agent-docs failure, if any. `path-safety` also implies a non-zero exit. `install-failed` carries a message when init wrote no agent docs (the home folder, or a settings folder in it outside a project) or skipped a file that resolves outside the project; docsWritten then lists what was written.* @property {boolean} theme Whether the theme feature ran.* @property {'created' | 'skipped' | 'failed' | null} themeTemplate Outcome of writing the annotated theme template (`skipped` = a file was already there).* @property {string | null} themeTemplatePath Relative output path when `themeTemplate === 'created'`.@@ -70,7 +70,7 @@* @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; with `user`, remove the computer-level agent text.+ * @property {boolean} [removeAgents] Remove the managed agent-docs block, at the project root and in the folder init runs in, 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).diff --git a/packages/cli/api/init/remove/remove.mjs b/packages/cli/api/init/remove/remove.mjsindex 32ef048436..5e7b55bdca 100644--- a/packages/cli/api/init/remove/remove.mjs+++ b/packages/cli/api/init/remove/remove.mjs@@ -4,15 +4,16 @@* @file init.remove leaf — the `--remove-agents` path behind `astryx init`.** `remove(ctx)` deletes the managed agent-docs block from every agent-doc file- * and returns an `init.remove` receipt. The removal engine lives in- * lib/agent-docs; this leaf only wires the cwd.+ * at the project root, where init writes it, and in the working folder, and+ * returns an `init.remove` receipt. The removal engine lives in+ * foundation/agent-docs; this leaf only wires the cwd.** Note: removeAgentDocs() still logs its own per-file lines via humanLog* (shared lib behavior) — so a programmatic remove is not perfectly silent yet.* Threading a logger through agent-docs is a separate cleanup.*/-import {removeAgentDocs} from '../../../foundation/agent-docs/agent-docs.mjs';+import {removeProjectAgentDocs} from '../../../foundation/agent-docs/agent-docs.mjs';import {logger} from '../../logger.mjs';/**@@ -23,7 +24,19 @@ import {logger} from '../../logger.mjs';* @returns {Promise<import('../init.type.mjs').InitRemoveResponse>}*/export async function remove({cwd = process.cwd()} = {}) {- const removedFrom = removeAgentDocs(cwd);+ /** @type {string[]} */+ const skipped = [];+ const removedFrom = removeProjectAgentDocs(cwd, {+ onSkipped: (rel, reason) => skipped.push(`${rel} (${reason})`),+ });+ if (skipped.length > 0) {+ // Below the project root, as install does there (0.7.x touched only the+ // working folder): a root agent file outside the project is left alone.+ logger.warn(+ `Note: Left as ${skipped.length === 1 ? 'it is' : 'they are'}: ${skipped.join('; ')}. ` ++ 'To remove the Astryx block there, delete it by hand.',+ );+ }const removed = removedFrom.length > 0;logger.log(removeddiff --git a/packages/cli/api/init/remove/remove.test.mjs b/packages/cli/api/init/remove/remove.test.mjsindex a0d92dc3b0..7f7a56a956 100644--- a/packages/cli/api/init/remove/remove.test.mjs+++ b/packages/cli/api/init/remove/remove.test.mjs@@ -1,12 +1,124 @@// Copyright (c) Meta Platforms, Inc. and affiliates.import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';-import * as fs from 'node:fs'; import * as path from 'node:path';+import * as fs from 'node:fs'; import * as path from 'node:path'; import * as os from 'node:os';import {init} from '../init.mjs'; import {remove} from './remove.mjs'; import {logger} from '../../logger.mjs';let dir;-beforeEach(() => { dir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-rm-')); fs.writeFileSync(path.join(dir,'package.json'),JSON.stringify({name:'c',version:'1.0.0'})); });+beforeEach(() => { dir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-rm-')); fs.writeFileSync(path.join(dir,'package.json'),JSON.stringify({name:'c',version:'1.0.0'})); });afterEach(() => { fs.rmSync(dir,{recursive:true,force:true}); logger.setSilent(true); });describe('init.remove says whether anything was removed', () => {it('false on clean', async () => { const r=await remove({cwd:dir}); expect(r.type).toBe('init.remove'); expect(r.data.removed).toBe(false); });it('true then false', async () => { await init({features:['agents']},{cwd:dir}); expect(fs.readFileSync(path.join(dir,'AGENTS.md'),'utf8')).toContain('<!-- ASTRYX:START -->'); const a=await remove({cwd:dir}); expect(a.data.removed).toBe(true); const b=await remove({cwd:dir}); expect(b.data.removed).toBe(false); });it('human line', async () => { const l=[]; const s=vi.spyOn(console,'log').mockImplementation((...a)=>l.push(a.join(' '))); logger.setSilent(false); try{await remove({cwd:dir});}finally{logger.setSilent(true);s.mockRestore();} expect(l.join('\n')).toContain('Nothing to remove'); });});++describe('init.remove acts where init writes, the project root, and in the folder it runs in', () => {+ /** @type {string} */+ let project;+ beforeEach(() => {+ project = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-rm-root-'));+ fs.writeFileSync(+ path.join(project, 'package.json'),+ JSON.stringify({name: 'app', dependencies: {'@astryxdesign/core': '1.0.0'}}),+ );+ fs.mkdirSync(path.join(project, 'src', 'app'), {recursive: true});+ });+ afterEach(() => { fs.rmSync(project, {recursive: true, force: true}); });+ const block = '<!-- ASTRYX:START -->\nAstryx v0.7.0 · old\n<!-- ASTRYX:END -->\n';++ it('removes from a subfolder what init wrote at the project root', async () => {+ const sub = path.join(project, 'src', 'app');+ const written = await init({features: ['agents']}, {cwd: sub});+ expect(written.data.docsWritten).toEqual(['../../AGENTS.md', '../../GEMINI.md']);++ const r = await remove({cwd: sub});+ expect(r).toEqual({type: 'init.remove', data: {removed: true}});+ // Both files held only what init wrote, so they are deleted.+ expect(fs.existsSync(path.join(project, 'AGENTS.md'))).toBe(false);+ expect(fs.existsSync(path.join(project, 'GEMINI.md'))).toBe(false);+ expect((await remove({cwd: sub})).data.removed).toBe(false);+ });++ it('removes a block an earlier version left in the subfolder, and keeps the files\' own text', async () => {+ const sub = path.join(project, 'src', 'app');+ fs.writeFileSync(path.join(project, 'AGENTS.md'), `# Agents\n\nRoot rules.\n\n${block}`);+ fs.writeFileSync(path.join(sub, 'AGENTS.md'), `# App\n\nApp rules.\n\n${block}`);++ expect((await remove({cwd: sub})).data.removed).toBe(true);+ expect(fs.readFileSync(path.join(project, 'AGENTS.md'), 'utf8').trimEnd()).toBe('# Agents\n\nRoot rules.');+ expect(fs.readFileSync(path.join(sub, 'AGENTS.md'), 'utf8').trimEnd()).toBe('# App\n\nApp rules.');+ });++ it('run at the project root, leaves a subfolder alone', async () => {+ const sub = path.join(project, 'src', 'app');+ fs.writeFileSync(path.join(project, 'AGENTS.md'), `# Agents\n\n${block}`);+ fs.writeFileSync(path.join(sub, 'AGENTS.md'), `# App\n\n${block}`);++ expect((await remove({cwd: project})).data.removed).toBe(true);+ expect(fs.readFileSync(path.join(sub, 'AGENTS.md'), 'utf8')).toContain('<!-- ASTRYX:START -->');+ });++ it('below the root, leaves a root agent file linked outside the project with a note, and removes the rest (0.7.x exited 0)', async () => {+ // A workspace member whose CLAUDE.md links to the monorepo's.+ const monorepo = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-rm-mono-'));+ try {+ const web = path.join(monorepo, 'apps', 'web');+ const sub = path.join(web, 'src');+ fs.mkdirSync(sub, {recursive: true});+ fs.writeFileSync(+ path.join(web, 'package.json'),+ JSON.stringify({name: 'web', dependencies: {'@astryxdesign/core': '1.0.0'}}),+ );+ fs.writeFileSync(path.join(monorepo, 'CLAUDE.md'), `# Shared\n\n${block}`);+ fs.symlinkSync('../../CLAUDE.md', path.join(web, 'CLAUDE.md'));+ fs.writeFileSync(path.join(web, 'AGENTS.md'), `# Web\n\n${block}`);+ fs.writeFileSync(path.join(sub, 'AGENTS.md'), `# Src\n\n${block}`);+ const warned = [];+ const warn = vi.spyOn(console, 'error').mockImplementation((...a) => warned.push(a.join(' ')));+ logger.setSilent(false);+ let r;+ try {+ r = await remove({cwd: sub});+ } finally {+ logger.setSilent(true);+ warn.mockRestore();+ }+ expect(r).toEqual({type: 'init.remove', data: {removed: true}});+ expect(fs.readFileSync(path.join(web, 'AGENTS.md'), 'utf8').trimEnd()).toBe('# Web');+ expect(fs.readFileSync(path.join(sub, 'AGENTS.md'), 'utf8').trimEnd()).toBe('# Src');+ // The file outside the project keeps its block.+ expect(fs.readFileSync(path.join(monorepo, 'CLAUDE.md'), 'utf8')).toContain('<!-- ASTRYX:START -->');+ expect(warned.join('\n')).toMatch(/Note: Left as it is: \.\.\/CLAUDE\.md \(/u);+ } finally {+ fs.rmSync(monorepo, {recursive: true, force: true});+ }+ });++ it('at the root, a root agent file linked outside the project still refuses the run', async () => {+ const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-rm-outside-'));+ try {+ fs.writeFileSync(path.join(outside, 'CLAUDE.md'), `# Shared\n\n${block}`);+ fs.symlinkSync(path.join(outside, 'CLAUDE.md'), path.join(project, 'CLAUDE.md'));+ fs.writeFileSync(path.join(project, 'AGENTS.md'), `# Agents\n\n${block}`);+ await expect(remove({cwd: project})).rejects.toMatchObject({code: 'ERR_PATH_TRAVERSAL'});+ expect(fs.readFileSync(path.join(project, 'AGENTS.md'), 'utf8')).toContain('<!-- ASTRYX:START -->');+ } finally {+ fs.rmSync(outside, {recursive: true, force: true});+ }+ });++ it('a link in the subfolder that escapes it refuses the run before anything is written', async () => {+ const sub = path.join(project, 'src', 'app');+ const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-rm-outside-'));+ try {+ fs.writeFileSync(path.join(project, 'AGENTS.md'), `# Agents\n\n${block}`);+ fs.writeFileSync(path.join(outside, 'CLAUDE.md'), `# Shared\n\n${block}`);+ fs.symlinkSync(path.join(outside, 'CLAUDE.md'), path.join(sub, 'CLAUDE.md'));++ await expect(remove({cwd: sub})).rejects.toMatchObject({code: 'ERR_PATH_TRAVERSAL'});+ expect(fs.readFileSync(path.join(project, 'AGENTS.md'), 'utf8')).toContain('<!-- ASTRYX:START -->');+ expect(fs.readFileSync(path.join(outside, 'CLAUDE.md'), 'utf8')).toContain('<!-- ASTRYX:START -->');+ } finally {+ fs.rmSync(outside, {recursive: true, force: true});+ }+ });+});diff --git a/packages/cli/api/init/run/run.mjs b/packages/cli/api/init/run/run.mjsindex b3d1cf142a..22ba454a3d 100644--- a/packages/cli/api/init/run/run.mjs+++ b/packages/cli/api/init/run/run.mjs@@ -4,10 +4,12 @@* @file init.run leaf — non-interactive project setup + feature installer.** `run(options, ctx)` is the default / `--features` / `--all` path behind- * `astryx init`. It installs the AGENTS.md/CLAUDE.md agent-docs cheat sheet,- * points at the theme + page-building workflows, and (optionally) scaffolds a- * starter template — with NO prompts, so it behaves identically for humans,- * agents, CI, and piped I/O. It performs the side effects and returns an+ * `astryx init`. It installs the agent-docs cheat sheet at the project root so+ * every agent reads it (AGENTS.md, a copy in the project's Claude Code file, and+ * a GEMINI.md import), points at the theme + page-building workflows, and+ * (optionally) scaffolds a starter template — with NO prompts, so it behaves+ * identically for humans, agents, CI, and piped I/O. It performs the side+ * effects and returns an* `init.run` receipt. Hard errors (unknown feature/template) throw AstryxError* with a stable code. Human output is emitted through the shared `logger`* (silent by default) so the CLI keeps its exact plain output and a@@ -21,8 +23,11 @@ import {PathSafetyError, assertWithin} from '../../../foundation/fs/path-safety.import {getCliInvocation} from '../../../foundation/env/package-manager.mjs';import {isOutsideProject} from '../../../foundation/env/project-scope.mjs';import {+ AgentDocsHomeError,+ assertAgentDocsTarget,installAgentDocs,renderAgentDocsBlock,+ agentDocsTargetDir,} from '../../../foundation/agent-docs/agent-docs.mjs';import {themeTemplate} from '../../theme/template/template.mjs';import {listTemplates} from '../../template/template.mjs';@@ -64,6 +69,24 @@ export function getNextSteps(invocation) {];}+/**+ * Whether two paths name one folder, links resolved.+ * @param {string} a+ * @param {string} b+ * @returns {boolean}+ */+function sameFolder(a, b) {+ /** @param {string} p */+ const real = p => {+ try {+ return fs.realpathSync(p);+ } catch {+ return path.resolve(p);+ }+ };+ return real(a) === real(b);+}+/*** Install the agent-docs block; records the outcome (or soft error) on `data`.* Mirrors the CLI's historical soft-error policy: a PathSafetyError surfaces its@@ -92,14 +115,46 @@ async function applyAgents(cwd, options, invocation, data) {? options.agentDocsPath: [options.agentDocsPath]: undefined;- const renderedBlock = await renderAgentDocsBlock(cwd);- const written = installAgentDocs(cwd, {+ // The docs belong at the project root, not in the subfolder init ran in;+ // with no project above, they go where init ran, as before. Explicit+ // --agent-docs-path entries stay relative to where init ran.+ const root = agentDocsTargetDir(cwd);+ const targetDir = paths ? cwd : root;+ // With explicit paths, installAgentDocs checks each file's own folder.+ if (!paths) assertAgentDocsTarget(targetDir);+ const renderedBlock = await renderAgentDocsBlock(root);+ /** @type {string[]} */+ const skipped = [];+ const files = installAgentDocs(targetDir, {agent: options.agent,paths,renderedBlock,+ onSkipped: (rel, reason) => skipped.push(`${rel} (${reason})`),+ // Below the project root, 0.7.1 wrote in the folder init ran in, so a+ // project-root file that escapes the project is skipped and reported,+ // not refused.+ refuseEscapes: sameFolder(targetDir, cwd),});+ // Each file is reported from where init ran, as before.+ const written =+ path.resolve(targetDir) === path.resolve(cwd)+ ? files+ : files.map(rel =>+ path.relative(cwd, path.join(targetDir, rel)).split(path.sep).join('/'),+ );data.docsWritten = written;logger.log(`[ok] AI agent docs installed -> ${written.join(', ')}`);+ // A file 0.7.1 did not write (GEMINI.md, or a project-root file when init+ // runs below the root) that resolves outside the project is left as it+ // is, reported in docsError with one note; the exit code stays 0. A file+ // 0.7.1 wrote whose path escapes the project still fails the run (below).+ if (skipped.length > 0) {+ const message =+ `Left as ${skipped.length === 1 ? 'it is' : 'they are'}: ${skipped.join('; ')}. ` ++ 'To have init write the Astryx block there, make it a regular file inside the project, or copy the block from AGENTS.md by hand.';+ logger.warn(`Note: ${message}`);+ data.docsError = {kind: 'install-failed', message};+ }} catch (err) {// PathSafetyError carries a precise, user-actionable message — surface it// (and flag exit 1) instead of the generic "could not install" warning so@@ -109,6 +164,14 @@ async function applyAgents(cwd, options, invocation, data) {data.docsError = {kind: 'path-safety', message: err.message};return;}+ // The home folder, and a settings folder in it outside a project, are+ // refused: nothing is written, the reason is printed as a note, and the+ // exit code stays 0.+ if (err instanceof AgentDocsHomeError) {+ logger.warn(`Note: ${err.message}`);+ data.docsError = {kind: 'install-failed', message: err.message};+ return;+ }logger.error(`Could not install agent docs. Try again with \`${invocation} init --features agents\`.`,);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 1a6af44f80..560b5cd74a 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@@ -51,6 +51,7 @@ const PACKED_DIRS = ['clients', 'api', 'assets', 'authoring', 'foundation'];const RUNTIME_DEPS = ['@babel/parser','commander',+ 'ignore','jiti','jscodeshift','zod',diff --git a/packages/cli/api/upgrade/_adapter.mjs b/packages/cli/api/upgrade/_adapter.mjsindex 5a535acdd3..d958f9512c 100644--- a/packages/cli/api/upgrade/_adapter.mjs+++ b/packages/cli/api/upgrade/_adapter.mjs@@ -30,6 +30,8 @@ import {} from '../../assets/codemods/integration-discovery.mjs';import {runIntegrationCodemods} from '../../assets/codemods/integration-runner.mjs';import {+ AgentDocsHomeError,+ assertAgentDocsTarget,installAgentDocs,inspectAgentDocs,renderAgentDocsBlock,@@ -286,6 +288,21 @@ export async function runPostCodemodHooks(hooks, context) {* @property {import('./upgrade.type.mjs').AgentDocsSummary} summary*/+/**+ * Why upgrade leaves the agent docs of a project at the home folder or the+ * top of a settings folder, and what to do instead. init refuses the same+ * folder, so the line never points at it.+ * @param {AgentDocsHomeError} err+ * @param {'stale' | 'missing'} [state] whether a block is there to refresh+ * @returns {string}+ */+function homeRefusalLine(err, state = 'stale') {+ const where = `${err.dir} is the home folder or a settings folder in it, which every project's agents read.`;+ return state === 'missing'+ ? `Agent docs not installed: ${where} To have agent docs, move the project into a folder of its own, or add the Astryx block to its agent file by hand.`+ : `Agent docs not refreshed: ${where} To keep agent docs, move the project into a folder of its own; otherwise update or remove the Astryx block there by hand.`;+}+/*** Compute the expected managed block and report staleness without writing.* Apply-mode callers commit the prepared bytes only after codemods and hooks@@ -312,6 +329,16 @@ export async function prepareAgentDocsRefresh({};if (initial.status === 'missing') {+ // init writes nothing in a project at the home folder or the top of a+ // settings folder, so it is not the remedy there (INV31).+ try {+ assertAgentDocsTarget(cwd);+ } catch (err) {+ if (!(err instanceof AgentDocsHomeError)) throw err;+ summary.action = 'error';+ logger.warn(homeRefusalLine(err, 'missing'));+ return {cwd, renderedBlock: null, summary};+ }summary.action = 'nudge-init';logger.warn(`No Astryx agent-docs block found - AI agents have no component index. Run \`${formatCliCommand('astryx init --features agents')}\` to install it.`,@@ -340,6 +367,18 @@ export async function prepareAgentDocsRefresh({summary.files = inspection.staleFiles;if (inspection.status === 'current') return {cwd, renderedBlock, summary};+ // A project at the home folder or the top of a settings folder is never+ // refreshed (INV31): the dry run says so, as --apply does, rather than+ // offering a refresh that would be refused.+ try {+ assertAgentDocsTarget(cwd);+ } catch (err) {+ if (!(err instanceof AgentDocsHomeError)) throw err;+ summary.action = 'error';+ logger.warn(homeRefusalLine(err));+ return {cwd, renderedBlock: null, summary};+ }+summary.action = 'would-refresh';if (!apply) {logger.warn(@@ -363,6 +402,9 @@ export function applyAgentDocsRefresh(plan) {const written = installAgentDocs(cwd, {onlyReplace: true,renderedBlock,+ // A GEMINI.md that resolves outside the project is left as it is.+ onSkipped: (file, reason) =>+ logger.warn(`Note: ${file} left as it is (${reason}).`),});summary.refreshed = written.length > 0;summary.files = written;@@ -374,12 +416,18 @@ export function applyAgentDocsRefresh(plan) {`Agent docs look stale but couldn't be refreshed. Run \`${formatCliCommand('astryx init --features agents')}\` to reinstall the block.`,);}- } catch {+ } catch (err) {summary.action = 'error';summary.refreshed = false;- logger.warn(- `Could not refresh agent docs. Run \`${formatCliCommand('astryx init --features agents')}\` to update them manually.`,- );+ if (err instanceof AgentDocsHomeError) {+ // init refuses this folder too, so pointing at it would loop: say why,+ // and what to do instead.+ logger.warn(homeRefusalLine(err));+ } else {+ logger.warn(+ `Could not refresh agent docs. Run \`${formatCliCommand('astryx init --features agents')}\` to update them manually.`,+ );+ }}return summary;}diff --git a/packages/cli/api/upgrade/upgrade.test.mjs b/packages/cli/api/upgrade/upgrade.test.mjsindex a1a1a43861..27345d4a76 100644--- a/packages/cli/api/upgrade/upgrade.test.mjs+++ b/packages/cli/api/upgrade/upgrade.test.mjs@@ -246,6 +246,200 @@ describe('upgrade() — receipts', () => {expect(content).not.toMatch(/Astryx v0\.0\.1 ·/);});+ it('leaves the block of a project at the top of a home settings folder, saying why and not pointing at init', async () => {+ const saved = {+ HOME: process.env.HOME,+ USERPROFILE: process.env.USERPROFILE,+ };+ process.env.HOME = tmpDir;+ process.env.USERPROFILE = tmpDir;+ const warned = [];+ const warn = vi+ .spyOn(console, 'error')+ .mockImplementation((...a) => warned.push(a.join(' ')));+ logger.setSilent(false);+ try {+ const project = path.join(tmpDir, '.dotfiles');+ fs.mkdirSync(project, {recursive: true});+ writePkg(project, {'@astryxdesign/core': '0.0.15'});+ writeInstalledCore(project, '0.0.15');+ writeAgentBlock(project, 'AGENTS.md', '0.0.1');++ const res = await upgrade({from: '0.0.15', apply: true}, {cwd: project});++ expect(res.data.agentDocs.action).toBe('error');+ expect(res.data.agentDocs.refreshed).toBe(false);+ expect(fs.readFileSync(path.join(project, 'AGENTS.md'), 'utf-8')).toMatch(+ /Astryx v0\.0\.1 ·/,+ );+ const text = warned.join('\n');+ expect(text).toContain(+ `Agent docs not refreshed: ${fs.realpathSync(project)} is the home folder or a settings folder in it, which every project's agents read. To keep agent docs, move the project into a folder of its own; otherwise update or remove the Astryx block there by hand.`,+ );+ expect(text).not.toContain('init --features agents');+ } finally {+ logger.setSilent(true);+ warn.mockRestore();+ for (const [key, value] of Object.entries(saved)) {+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ }+ }+ });++ it('with no block, in a project at the top of a home settings folder, says why instead of pointing at init', async () => {+ const saved = {+ HOME: process.env.HOME,+ USERPROFILE: process.env.USERPROFILE,+ };+ process.env.HOME = tmpDir;+ process.env.USERPROFILE = tmpDir;+ const warned = [];+ const warn = vi+ .spyOn(console, 'error')+ .mockImplementation((...a) => warned.push(a.join(' ')));+ logger.setSilent(false);+ try {+ const project = path.join(tmpDir, '.dotfiles');+ fs.mkdirSync(project, {recursive: true});+ writePkg(project, {'@astryxdesign/core': '0.0.15'});+ writeInstalledCore(project, '0.0.15');++ const res = await upgrade({from: '0.0.15'}, {cwd: project});++ expect(res.data.agentDocs.action).toBe('error');+ const text = warned.join('\n');+ expect(text).toContain(+ `Agent docs not installed: ${fs.realpathSync(project)} is the home folder or a settings folder in it, which every project's agents read. To have agent docs, move the project into a folder of its own, or add the Astryx block to its agent file by hand.`,+ );+ expect(text).not.toContain('init --features agents');+ } finally {+ logger.setSilent(true);+ warn.mockRestore();+ for (const [key, value] of Object.entries(saved)) {+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ }+ }+ });++ it('a dry run in a project at the top of a home settings folder reports the refusal, not a refresh to apply', async () => {+ const saved = {+ HOME: process.env.HOME,+ USERPROFILE: process.env.USERPROFILE,+ };+ process.env.HOME = tmpDir;+ process.env.USERPROFILE = tmpDir;+ const warned = [];+ const warn = vi+ .spyOn(console, 'error')+ .mockImplementation((...a) => warned.push(a.join(' ')));+ logger.setSilent(false);+ try {+ const project = path.join(tmpDir, '.dotfiles');+ fs.mkdirSync(project, {recursive: true});+ writePkg(project, {'@astryxdesign/core': '0.0.15'});+ writeInstalledCore(project, '0.0.15');+ writeAgentBlock(project, 'AGENTS.md', '0.0.1');++ const res = await upgrade({from: '0.0.15'}, {cwd: project});++ expect(res.data.agentDocs.action).toBe('error');+ expect(res.data.agentDocs.refreshed).toBe(false);+ const text = warned.join('\n');+ expect(text).toContain(+ `Agent docs not refreshed: ${fs.realpathSync(project)} is the home folder or a settings folder in it`,+ );+ expect(text).not.toContain('--apply to refresh');+ expect(text).not.toContain('init --features agents');+ } finally {+ logger.setSilent(true);+ warn.mockRestore();+ for (const [key, value] of Object.entries(saved)) {+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ }+ }+ });++ it('refreshes the agent docs of a project in an agent worktree inside a home settings folder', async () => {+ const saved = {+ HOME: process.env.HOME,+ USERPROFILE: process.env.USERPROFILE,+ };+ process.env.HOME = tmpDir;+ process.env.USERPROFILE = tmpDir;+ try {+ const project = path.join(tmpDir, '.codex', 'worktrees', 'a1b2c3', 'web');+ fs.mkdirSync(project, {recursive: true});+ writePkg(project, {'@astryxdesign/core': '0.0.15'});+ writeInstalledCore(project, '0.0.15');+ writeAgentBlock(project, 'AGENTS.md', '0.0.1');++ const res = await upgrade({from: '0.0.15', apply: true}, {cwd: project});++ expect(res.data.agentDocs.action).toBe('refreshed');+ expect(fs.readFileSync(path.join(project, 'AGENTS.md'), 'utf-8')).toMatch(+ /Astryx v0\.0\.15 ·/,+ );+ } finally {+ for (const [key, value] of Object.entries(saved)) {+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ }+ }+ });++ it('refreshes the managed block in an ignored .claude/CLAUDE.md and keeps the text around it (INV31)', async () => {+ writePkg(tmpDir);+ writeInstalledCore(tmpDir, '0.0.15');+ writeAgentBlock(tmpDir, 'AGENTS.md', '0.0.1');+ fs.mkdirSync(path.join(tmpDir, '.claude'));+ writeAgentBlock(tmpDir, '.claude/CLAUDE.md', '0.0.1');+ const claude = path.join(tmpDir, '.claude', 'CLAUDE.md');+ fs.writeFileSync(+ claude,+ `# Team notes\n\n${fs.readFileSync(claude, 'utf-8')}\nMore notes.\n`,+ );+ fs.writeFileSync(path.join(tmpDir, '.gitignore'), '.claude/\n');++ const res = await upgrade({from: '0.0.15', apply: true}, {cwd: tmpDir});++ expect(res.data.agentDocs.action).toBe('refreshed');+ expect(res.data.agentDocs.files).toEqual([+ 'AGENTS.md',+ '.claude/CLAUDE.md',+ ]);+ expect(res.data.agentDocs).not.toHaveProperty('protectedFiles');+ const content = fs.readFileSync(claude, 'utf-8');+ expect(content).toMatch(/^# Team notes\n/u);+ expect(content).toMatch(/Astryx v0\.0\.15 ·/u);+ expect(content).toMatch(/More notes\.\n$/u);+ });++ it('refreshes a committed .claude/CLAUDE.md that imports AGENTS.md and keeps a copy beside an ignored root CLAUDE.md', async () => {+ writePkg(tmpDir);+ writeInstalledCore(tmpDir, '0.0.15');+ writeAgentBlock(tmpDir, 'AGENTS.md', '0.0.1');+ writeAgentBlock(tmpDir, 'CLAUDE.md', '0.0.1');+ fs.writeFileSync(path.join(tmpDir, '.gitignore'), '/CLAUDE.md\n');+ fs.mkdirSync(path.join(tmpDir, '.claude'));+ const copy = path.join(tmpDir, '.claude', 'CLAUDE.md');+ fs.writeFileSync(+ copy,+ `@../AGENTS.md\n\n${generateCompressedIndex('0.0.1')}\n`,+ );++ for (let round = 0; round < 2; round++) {+ await upgrade({from: '0.0.15', apply: true}, {cwd: tmpDir});+ const content = fs.readFileSync(copy, 'utf-8');+ expect(content, `round ${round}`).toMatch(/^@\.\.\/AGENTS\.md\n/u);+ expect(content, `round ${round}`).toMatch(/Astryx v0\.0\.15 ·/u);+ }+ const dry = await upgrade({from: '0.0.15'}, {cwd: tmpDir});+ expect(dry.data.agentDocs.status).toBe('current');+ });+it('reports would-refresh on a dry run without writing (honors cwd)', async () => {writePkg(tmpDir);writeInstalledCore(tmpDir, '0.0.15');diff --git a/packages/cli/assets/docs/working-with-ai.doc.mjs b/packages/cli/assets/docs/working-with-ai.doc.mjsindex 1b27b2c98a..213a6ddad4 100644--- a/packages/cli/assets/docs/working-with-ai.doc.mjs+++ b/packages/cli/assets/docs/working-with-ai.doc.mjs@@ -44,7 +44,7 @@ export const docs = {},{type: 'prose',- text: "By default this creates `AGENTS.md` (the tool-agnostic standard most agents read). To target a specific tool's file instead:",+ text: "By default this writes the instructions to `AGENTS.md` (the tool-agnostic standard most agents read), in the project root: the nearest folder whose `package.json` declares an Astryx package, else the nearest with any `package.json`. The search stops at the repository root. In the home folder, or in a settings folder in it outside a project, init writes no agent docs: every folder of the home folder whose name starts with a dot (`~/.claude`, `~/.gemini`, `~/.codex`) is a settings folder, and such a folder itself never counts as a project, even with a `package.json`; a project below it with its own `package.json`, such as an agent worktree, is set up normally. Claude Code skips `AGENTS.md` when the project has a `CLAUDE.md` or `.claude/CLAUDE.md`, so init also writes them to that file, even when it imports `AGENTS.md`: Claude Code does not follow that import in a session started in a subfolder. When both files exist, root `CLAUDE.md` gets the copy and a copy in `.claude/CLAUDE.md` is removed, unless the project ignores `CLAUDE.md`, in which case a `.claude/CLAUDE.md` the project commits keeps a copy. Gemini CLI reads only `GEMINI.md`, so init adds a one-line import of `AGENTS.md` there, unless `GEMINI.md` already imports it. `upgrade` keeps the copies in sync. The block between the Astryx markers belongs to Astryx: init and `upgrade` write, refresh, and remove it whatever the project's ignore rules or generated markers say, and never change the text around it. To target a specific tool's file instead:",},{type: 'code',@@ -55,7 +55,11 @@ astryx init --features agents --agent cursor # .cursorrules if present, elseastryx 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.mdastryx 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`,+astryx init --features agents --agent all # every agent file present except GEMINI.md, else AGENTS.md and .claude/CLAUDE.md`,+ },+ {+ type: 'prose',+ text: 'With `--agent all`, `GEMINI.md` keeps its one-line import of `AGENTS.md`. With `--agent claude` or `--agent all`, as by default, when `CLAUDE.md` gets the instructions, `.claude/CLAUDE.md` gets none and a copy already there is removed, unless the project ignores `CLAUDE.md`: a fresh clone does not have it, so a `.claude/CLAUDE.md` the project commits gets a copy too, with `--agent claude` and `--agent all` alike. `init --remove-agents` removes them at the project root and in the folder it runs in.',},{type: 'prose',diff --git a/packages/cli/clients/cli/commands/doctor.test.mjs b/packages/cli/clients/cli/commands/doctor.test.mjsindex 6d7d795972..68ea55652c 100644--- a/packages/cli/clients/cli/commands/doctor.test.mjs+++ b/packages/cli/clients/cli/commands/doctor.test.mjs@@ -191,6 +191,31 @@ describe('doctor — individual checks', () => {expect(res.fix).toContain('`npx astryx init --features agents`');});+ it('agent-docs: at the top of a home settings folder, the fix moves the project or edits by hand, never init', () => {+ const saved = {HOME: process.env.HOME, USERPROFILE: process.env.USERPROFILE};+ process.env.HOME = tmpDir;+ process.env.USERPROFILE = tmpDir;+ try {+ const project = path.join(tmpDir, '.dotfiles');+ fs.mkdirSync(project);+ fs.writeFileSync(path.join(project, 'package.json'), '{"name":"dots"}');+ for (const content of [null, '# Agents\nno markers here\n']) {+ if (content != null) fs.writeFileSync(path.join(project, 'AGENTS.md'), content);+ const res = checkAgentDocs({cwd: project});+ expect(res.fix).toContain('Agent docs are not written into the home folder');+ expect(res.fix).toContain(+ 'Move the project into a folder of its own, or edit the Astryx block in its agent file by hand.',+ );+ expect(res.fix).not.toContain('init --features agents');+ }+ } finally {+ for (const [key, value] of Object.entries(saved)) {+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ }+ }+ });+it('agent-docs: WARN when docs exist without XDS markers', () => {fs.writeFileSync(path.join(tmpDir, 'AGENTS.md'), '# AGENTS\nno markers here');const res = checkAgentDocs({cwd: tmpDir});@@ -221,6 +246,25 @@ describe('doctor — individual checks', () => {);});+ it('agent-docs: PASS from a nested package, reading the root that declares Astryx', () => {+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({dependencies: {'@astryxdesign/core': '0.7.0'}}),+ );+ fs.writeFileSync(+ path.join(tmpDir, 'AGENTS.md'),+ '<!-- ASTRYX:START -->\nstuff\n<!-- ASTRYX:END -->\n',+ );+ const functions = path.join(tmpDir, 'functions');+ fs.mkdirSync(path.join(functions, 'src'), {recursive: true});+ fs.writeFileSync(path.join(functions, 'package.json'), '{"name":"functions"}');++ expect(checkAgentDocs({cwd: path.join(functions, 'src')})).toMatchObject({+ status: 'pass',+ message: `Astryx agent docs section present in ${path.join('..', '..', 'AGENTS.md')}.`,+ });+ });+it('agent-docs: reads every file init can write, Hermes included', () => {fs.writeFileSync(path.join(tmpDir, 'HERMES.md'),@@ -232,6 +276,27 @@ describe('doctor — individual checks', () => {});});+ it('agent-docs: FAIL when GEMINI.md imports an AGENTS.md that holds no block', () => {+ const geminiImport = '<!-- ASTRYX:START -->\n@./AGENTS.md\n<!-- ASTRYX:END -->\n';+ fs.writeFileSync(path.join(tmpDir, 'GEMINI.md'), geminiImport);+ expect(checkAgentDocs({cwd: tmpDir})).toMatchObject({+ status: 'fail',+ message: expect.stringMatching(/^GEMINI\.md imports AGENTS\.md, which holds no Astryx block/),+ fix: expect.stringMatching(/init --features agents/),+ });++ // A copy elsewhere does not mend it: Codex and Gemini CLI still get none.+ fs.writeFileSync(path.join(tmpDir, 'CLAUDE.md'), '<!-- ASTRYX:START -->\nstuff\n<!-- ASTRYX:END -->\n');+ fs.writeFileSync(path.join(tmpDir, 'AGENTS.md'), '# Agents\n');+ expect(checkAgentDocs({cwd: tmpDir}).status).toBe('fail');++ fs.writeFileSync(path.join(tmpDir, 'AGENTS.md'), '<!-- ASTRYX:START -->\nstuff\n<!-- ASTRYX:END -->\n');+ expect(checkAgentDocs({cwd: tmpDir})).toMatchObject({+ status: 'pass',+ message: 'Astryx agent docs section present in AGENTS.md, CLAUDE.md.',+ });+ });+it('agent-docs: INFO names what it looked for and where', () => {const res = checkAgentDocs({cwd: tmpDir});expect(res.status).toBe('info');diff --git a/packages/cli/clients/cli/commands/init.behavior.test.mjs b/packages/cli/clients/cli/commands/init.behavior.test.mjsindex 65302545e7..be29c8d79a 100644--- a/packages/cli/clients/cli/commands/init.behavior.test.mjs+++ b/packages/cli/clients/cli/commands/init.behavior.test.mjs@@ -70,10 +70,12 @@ describe('astryx init — default (no flags)', () => {});describe('astryx init --features', () => {- it('--features agents writes AGENTS.md only', async () => {+ it('--features agents writes AGENTS.md and the GEMINI.md import of it', async () => {const {status} = await runCli(['init', '--features', 'agents'], {cwd: tmpDir});expect(status).toBe(0);expect(exists('AGENTS.md')).toBe(true);+ expect(read('GEMINI.md')).toBe(`${MARKER_START}\n@./AGENTS.md\n<!-- ASTRYX:END -->\n`);+ expect(exists('theme.template.ts')).toBe(false);});it('--features theme writes the annotated theme template', async () => {@@ -126,7 +128,234 @@ describe('astryx init --agent <preset>', () => {});});+describe('astryx init from a subfolder', () => {+ /** @param {string} dir */+ const astryxProject = dir =>+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ JSON.stringify({name: 'app', dependencies: {'@astryxdesign/core': '0.7.0'}}),+ );++ it('writes the agent docs at the project root and reports them from where it ran', async () => {+ astryxProject(tmpDir);+ const sub = path.join(tmpDir, 'src', 'app');+ fs.mkdirSync(sub, {recursive: true});++ const json = await runCli(['init', '--json'], {cwd: sub});+ expect(json.status).toBe(0);+ expect(JSON.parse(json.stdout).data.docsWritten).toEqual([+ '../../AGENTS.md',+ '../../GEMINI.md',+ ]);+ expect(read('AGENTS.md')).toContain(MARKER_START);+ expect(fs.readdirSync(sub)).toEqual([]);+ });++ it('keeps --agent-docs-path relative to where it ran', async () => {+ astryxProject(tmpDir);+ const sub = path.join(tmpDir, 'docs');+ fs.mkdirSync(sub);++ const json = await runCli(['init', '--agent-docs-path', 'AI.md', '--json'], {cwd: sub});+ expect(JSON.parse(json.stdout).data.docsWritten).toEqual(['AI.md']);+ expect(fs.readFileSync(path.join(sub, 'AI.md'), 'utf8')).toContain(MARKER_START);+ expect(exists('AGENTS.md')).toBe(false);+ });+});++describe('astryx init in the home folder', () => {+ const saved = {HOME: process.env.HOME, USERPROFILE: process.env.USERPROFILE};+ const personal = '# My notes\n\nAlways use tabs.\n';++ beforeEach(() => {+ process.env.HOME = tmpDir;+ process.env.USERPROFILE = tmpDir;+ fs.mkdirSync(path.join(tmpDir, '.claude'), {recursive: true});+ fs.writeFileSync(path.join(tmpDir, '.claude', 'CLAUDE.md'), personal);+ });+ afterEach(() => {+ for (const [key, value] of Object.entries(saved)) {+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ }+ });++ it('writes no agent docs, says why, and keeps the soft-failure exit code', async () => {+ const json = await runCli(['init', '--json'], {cwd: tmpDir});+ expect(json.status).toBe(0);+ const env = JSON.parse(json.stdout);+ expect(env.data.docsWritten).toEqual([]);+ expect(env.data.docsError).toEqual({+ kind: 'install-failed',+ message: expect.stringMatching(/not written into the home folder/),+ });++ const text = await runCli(['init'], {cwd: tmpDir});+ expect(text.status).toBe(0);+ expect(text.stderr).toMatch(/not written into the home folder/);+ expect(text.stderr).not.toMatch(/Error:/);++ expect(read('.claude/CLAUDE.md')).toBe(personal);+ expect(fs.readdirSync(tmpDir)).toEqual(['.claude']);+ });++ it('does not let a package.json in the home folder pull the docs there', async () => {+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({dependencies: {'@astryxdesign/core': '0.7.0'}}),+ );+ const scratch = path.join(tmpDir, 'scratch');+ fs.mkdirSync(scratch);++ const json = await runCli(['init', '--json'], {cwd: scratch});+ expect(json.status).toBe(0);+ expect(JSON.parse(json.stdout).data.docsWritten).toEqual(['AGENTS.md', 'GEMINI.md']);+ expect(fs.existsSync(path.join(scratch, 'AGENTS.md'))).toBe(true);+ expect(exists('AGENTS.md')).toBe(false);+ expect(read('.claude/CLAUDE.md')).toBe(personal);+ });++ it('--remove-agents in a folder in home never reaches the home folder', async () => {+ fs.writeFileSync(+ path.join(tmpDir, '.claude', 'CLAUDE.md'),+ `${personal}\n<!-- ASTRYX:START -->\nAstryx v0.7.0\n<!-- ASTRYX:END -->\n`,+ );+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({dependencies: {'@astryxdesign/core': '0.7.0'}}),+ );+ const scratch = path.join(tmpDir, 'scratch');+ fs.mkdirSync(scratch);++ const json = await runCli(['init', '--remove-agents', '--json'], {cwd: scratch});+ expect(JSON.parse(json.stdout).data.removed).toBe(false);+ expect(read('.claude/CLAUDE.md')).toContain('<!-- ASTRYX:START -->');++ // Run in the home folder itself, it still removes the block there.+ const home = await runCli(['init', '--remove-agents', '--json'], {cwd: tmpDir});+ expect(JSON.parse(home.stdout).data.removed).toBe(true);+ expect(read('.claude/CLAUDE.md')).toBe(personal);+ });++ it.each(['.gemini', '.claude'])('refuses the settings folder ~/%s', async folder => {+ const dir = path.join(tmpDir, folder);+ fs.mkdirSync(dir, {recursive: true});+ const before = fs.readdirSync(dir);++ const json = await runCli(['init', '--json'], {cwd: dir});+ expect(json.status).toBe(0);+ const env = JSON.parse(json.stdout);+ expect(env.data.docsWritten).toEqual([]);+ expect(env.data.docsError.message).toMatch(/settings folder in it outside a project/);+ expect(fs.readdirSync(dir)).toEqual(before);+ expect(read('.claude/CLAUDE.md')).toBe(personal);+ });+});++describe('astryx init in an agent worktree inside a home settings folder', () => {+ const saved = {HOME: process.env.HOME, USERPROFILE: process.env.USERPROFILE};++ beforeEach(() => {+ process.env.HOME = tmpDir;+ process.env.USERPROFILE = tmpDir;+ });+ afterEach(() => {+ for (const [key, value] of Object.entries(saved)) {+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ }+ });++ it.each([+ ['Codex', path.join('.codex', 'worktrees', 'a1b2c3', 'web')],+ ['Cursor', path.join('.cursor', 'worktrees', 'web', 'x9y8')],+ ])('writes at the project root of a %s worktree', async (_tool, rel) => {+ const project = path.join(tmpDir, rel);+ fs.mkdirSync(path.join(project, 'src'), {recursive: true});+ fs.writeFileSync(path.join(project, '.git'), 'gitdir: /elsewhere/.git/worktrees/web\n');+ fs.writeFileSync(+ path.join(project, 'package.json'),+ JSON.stringify({name: 'web', dependencies: {'@astryxdesign/core': '0.7.0'}}),+ );++ const json = await runCli(['init', '--json'], {cwd: path.join(project, 'src')});+ expect(json.status).toBe(0);+ const env = JSON.parse(json.stdout);+ expect(env.data.docsWritten).toEqual(['../AGENTS.md', '../GEMINI.md']);+ expect(env.data.docsError).toBeNull();++ const explicit = await runCli(['init', '--agent-docs-path', 'AI.md', '--json'], {+ cwd: path.join(project, 'src'),+ });+ expect(JSON.parse(explicit.stdout).data.docsWritten).toEqual(['AI.md']);++ // Nothing reaches the settings folder itself.+ const settings = path.join(tmpDir, rel.split(path.sep)[0]);+ expect(fs.readdirSync(settings)).toEqual(['worktrees']);+ });+});++describe('astryx init and the project root', () => {+ it('writes where it runs when no folder above has a package.json, as before', async () => {+ const notes = path.join(tmpDir, 'notes');+ fs.mkdirSync(notes);++ const json = await runCli(['init', '--json'], {cwd: notes});+ expect(json.status).toBe(0);+ const env = JSON.parse(json.stdout);+ expect(env.data.docsWritten).toEqual(['AGENTS.md', 'GEMINI.md']);+ expect(env.data.docsError).toBeNull();+ expect(fs.readdirSync(notes).sort()).toEqual(['AGENTS.md', 'GEMINI.md']);+ expect(fs.readdirSync(tmpDir)).toEqual(['notes']);+ });++ it('writes at the project root that declares Astryx, past a nested package that does not', async () => {+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({name: 'app', dependencies: {'@astryxdesign/core': '0.7.0'}}),+ );+ const functions = path.join(tmpDir, 'functions');+ fs.mkdirSync(path.join(functions, 'src'), {recursive: true});+ fs.writeFileSync(path.join(functions, 'package.json'), '{"name":"functions"}\n');++ const json = await runCli(['init', '--json'], {cwd: path.join(functions, 'src')});+ expect(JSON.parse(json.stdout).data.docsWritten).toEqual([+ '../../AGENTS.md',+ '../../GEMINI.md',+ ]);+ expect(fs.readdirSync(functions).sort()).toEqual(['package.json', 'src']);+ });+});+describe('astryx init --remove-agents', () => {+ it('run in a subfolder, removes what init wrote at the project root, with the same JSON shape', async () => {+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({name: 'app', dependencies: {'@astryxdesign/core': '0.7.0'}}),+ );+ const sub = path.join(tmpDir, 'src', 'app');+ fs.mkdirSync(sub, {recursive: true});+ await runCli(['init'], {cwd: sub});+ expect(exists('AGENTS.md')).toBe(true);++ const text = await runCli(['init', '--remove-agents'], {cwd: sub});+ expect(text.status).toBe(0);+ expect(text.stdout).toMatch(/Removed empty \.\.\/\.\.\/AGENTS\.md/);+ expect(exists('AGENTS.md')).toBe(false);+ expect(exists('GEMINI.md')).toBe(false);++ await runCli(['init'], {cwd: sub});+ const json = await runCli(['init', '--remove-agents', '--json'], {cwd: sub});+ expect(json.status).toBe(0);+ // meta.answeredBy names the release that answered (spec AST-081).+ expect(JSON.parse(json.stdout)).toEqual({+ apiVersion: 1,+ type: 'init.remove',+ data: {removed: true},+ meta: {answeredBy: expect.any(Object)},+ });+ });+it('removes the Astryx section it previously installed', async () => {await runCli(['init', '--features', 'agents'], {cwd: tmpDir});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 62d104fea8..e5ff4d76f9 100644--- a/packages/cli/clients/cli/commands/init.doc.mjs+++ b/packages/cli/clients/cli/commands/init.doc.mjs@@ -16,10 +16,24 @@ export const doc = {summary: 'Initialize the design system in your project',description:'Non-interactive project setup (no prompts, so it behaves the same for humans, ' +- '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. ' ++ 'agents, and CI). By default it writes the agent-docs block, including guidance ' ++ 'from configured integrations, to AGENTS.md and to the Claude Code file the project ' ++ 'has (CLAUDE.md, else .claude/CLAUDE.md; when CLAUDE.md exists, a block in ' ++ '.claude/CLAUDE.md is removed, unless the project ignores CLAUDE.md, in which case a .claude/CLAUDE.md the ' ++ 'project commits keeps a copy), and a one-line import of AGENTS.md to GEMINI.md ' ++ 'unless GEMINI.md already imports it. It then prints getting-started steps. Agent ' ++ 'docs go to the project root: the nearest folder at or above this one whose ' ++ 'package.json declares an @astryxdesign package, else the nearest with any ' ++ 'package.json, else this folder. The search stops at a repository root and never ' ++ 'counts the home folder. In the home folder, or in a settings folder in it ' ++ 'such as ~/.gemini outside a project, no agent docs are written. Every folder of the ' ++ 'home folder whose name starts with a dot is a settings folder, and such a folder ' ++ 'itself never counts as a project, even with a package.json; a project inside one, ' ++ 'such as an agent worktree with its own package.json, works. The managed block is ' ++ 'written whatever ignore rules or generated markers say; the text around it is never changed. ' ++ '--features and --all print only ' ++ "the chosen features' " ++ 'guidance (no 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. ' +@@ -44,8 +58,10 @@ export const doc = {flag: '--remove-agents',param: 'options.removeAgents',description:- 'Remove the managed block from AGENTS.md, CLAUDE.md, .claude/CLAUDE.md, .cursorrules, .hermes.md and HERMES.md ' +- "(deleting AGENTS.md or .claude/CLAUDE.md when only init's heading is left) and do nothing else. " ++ 'Remove the managed block from AGENTS.md, CLAUDE.md, .claude/CLAUDE.md, GEMINI.md, .cursorrules, .hermes.md and HERMES.md, ' ++ 'at the project root (where init writes them) and in this folder ' ++ "(deleting AGENTS.md or .claude/CLAUDE.md when only init's heading is left, and GEMINI.md when nothing is left) and do nothing else. " ++ 'Below the project root, a project-root agent file whose block resolves outside the project is left as it is, with a note. ' +'--features, --all, --agent and --agent-docs-path are refused; a file written with --agent-docs-path keeps its block',},{@@ -66,7 +82,9 @@ export const doc = {choices: ['claude', 'cursor', 'codex', 'hermes', 'muse', 'all'],description:'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). ' ++ 'codex and muse (AGENTS.md), hermes (.hermes.md or HERMES.md if present, else AGENTS.md), all (every existing agent doc except GEMINI.md, which keeps its ' ++ 'one-line import of AGENTS.md, else AGENTS.md and .claude/CLAUDE.md). With claude and all, when CLAUDE.md gets the block, .claude/CLAUDE.md gets none and ' ++ 'a block already there is removed, unless the project ignores CLAUDE.md: then a .claude/CLAUDE.md the project commits gets a copy too, with claude and all alike. ' +'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.',},@@ -76,6 +94,7 @@ export const doc = {description:'Explicit file path(s) for agent docs, inside the project; takes precedence over --agent. ' +'If any path is outside the project, no agent docs are written and the command exits 1. ' ++ 'A path in the home folder itself, or in a settings folder in it outside a project (such as ~/.claude or ~/.claude/hooks), is refused with a note (exit 0), and nothing is written. ' +'Used only when agent docs are installed',},],@@ -90,11 +109,11 @@ export const doc = {exitCodes: [{code: 0,- when: 'success, including agent docs that could not be written for a reason other than a path escape (reported as docsError)',+ when: "success, including agent docs left unwritten in five soft cases, each reported as docsError with one note: running in the home folder, or in a settings folder in it outside a project; a GEMINI.md that resolves outside the project; when init runs below the project root, a project-root agent file that resolves outside the project; the project's Claude Code file (root CLAUDE.md, or .claude/CLAUDE.md when there is no root one) when it resolves outside the project and is a block-less import of an existing AGENTS.md, which 0.7.1 left alone; and a .claude/CLAUDE.md that resolves outside the project and that 0.7.1 did not write: beside a CLAUDE.md the project ignores, the one --agent claude adds or a block-less import of an existing AGENTS.md; with --agent claude beside a CLAUDE.md, one whose block it would remove",},{code: 1,- 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)',+ 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); or, when init runs at the project root, an agent file 0.7.1 also wrote there that resolves outside the project (ERR_PATH_TRAVERSAL, docsError path-safety, nothing written)',},],related: ['doctor', 'upgrade', 'build', 'theme'],diff --git a/packages/cli/clients/cli/commands/init.flag-help.test.mjs b/packages/cli/clients/cli/commands/init.flag-help.test.mjsindex 9a68567fb9..377d3aeece 100644--- a/packages/cli/clients/cli/commands/init.flag-help.test.mjs+++ b/packages/cli/clients/cli/commands/init.flag-help.test.mjs@@ -67,6 +67,7 @@ describe('astryx init flag interactions', () => {expect(help).toContain(file);}expect(help).toMatch(/--agent-docs-path are refused/);+ expect(help).toMatch(/at the project root \(where init writes them\) and in this folder/);await initJson(['--agent-docs-path', 'docs/AI.md']);await initJson([]);diff --git a/packages/cli/clients/cli/commands/init.mjs b/packages/cli/clients/cli/commands/init.mjsindex b6c5f18034..a8bcbf78a5 100644--- a/packages/cli/clients/cli/commands/init.mjs+++ b/packages/cli/clients/cli/commands/init.mjs@@ -3,8 +3,8 @@/*** @file init command — thin wrapper around the init API.*- * `astryx init` is non-interactive by default: it installs the AGENTS.md/- * CLAUDE.md cheat sheet with NO prompts, so it behaves identically for humans,+ * `astryx init` is non-interactive by default: it installs the agent-docs+ * cheat sheet with NO prompts, so it behaves identically for humans,* AI agents, CI, and piped I/O — it never hangs or errors on a missing TTY.* Non-interactive feature install: `astryx init --features agents,theme,template`* Re-runnable: safe to run multiple times, idempotent.diff --git a/packages/cli/clients/cli/commands/outside-project.test.mjs b/packages/cli/clients/cli/commands/outside-project.test.mjsindex ca7e4fc30d..650f688375 100644--- a/packages/cli/clients/cli/commands/outside-project.test.mjs+++ b/packages/cli/clients/cli/commands/outside-project.test.mjs@@ -541,7 +541,8 @@ describe('init outside a project (own)', () => {const dir = tmpDir('init');const json = await answer(['--json', 'init'], dir);expect(json.status).toBe(0);- expect(json.written).toEqual(['AGENTS.md']);+ // GEMINI.md gets its one-line import of AGENTS.md (spec cli-surface INV31).+ expect(json.written).toEqual(['AGENTS.md', 'GEMINI.md']);expect(json.envelope.data.nextSteps).toBe(false);const text = await runCli(['init'], tmpDir('init-text'));expect(text.stdout).not.toContain('Next steps');diff --git a/packages/cli/clients/cli/commands/setup-nudge.test.mjs b/packages/cli/clients/cli/commands/setup-nudge.test.mjsindex 4a301fea07..4ae71e16c1 100644--- a/packages/cli/clients/cli/commands/setup-nudge.test.mjs+++ b/packages/cli/clients/cli/commands/setup-nudge.test.mjs@@ -121,6 +121,25 @@ describe('enforcement layer 3 — per-command setup nudge', () => {expect(r.stderr).toMatch(NUDGE);});+ it.each([+ ['in the home folder', ''],+ ['at the top of a settings folder in it', '.dotfiles'],+ ])('stays quiet %s, where init writes no agent docs', async (_label, rel) => {+ const saved = {HOME: process.env.HOME, USERPROFILE: process.env.USERPROFILE};+ process.env.HOME = tmp;+ process.env.USERPROFILE = tmp;+ try {+ write(path.join(rel, 'package.json'), '{"name":"t"}');+ const r = await runCli(['docs', 'tokens'], path.join(tmp, rel));+ expect(r.stderr).not.toMatch(NUDGE);+ } finally {+ for (const [key, value] of Object.entries(saved)) {+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ }+ }+ });+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',@@ -167,6 +186,48 @@ describe('enforcement layer 3 — per-command setup nudge', () => {expect((await runCli(['docs', 'tokens'], tmp)).stderr).not.toMatch(NUDGE);});+ it('is quiet in a nested package once init has written the docs at the project root', async () => {+ // init run in functions/ writes at the root that declares Astryx.+ write('package.json', JSON.stringify({name: 'app', dependencies: {'@astryxdesign/core': '0.7.0'}}));+ write('AGENTS.md', MARKER);+ write('functions/package.json', '{"name":"functions"}');+ const r = await runCli(['docs', 'tokens'], path.join(tmp, 'functions'));+ expect(r.stderr).not.toMatch(NUDGE);+ });++ it('nudges in a nested package while the project root has no docs', async () => {+ write('package.json', JSON.stringify({name: 'app', dependencies: {'@astryxdesign/core': '0.7.0'}}));+ write('functions/package.json', '{"name":"functions"}');+ const r = await runCli(['docs', 'tokens'], path.join(tmp, 'functions'));+ expect(r.stderr).toMatch(NUDGE);+ });++ // Inside a git repository the project-root check above adds nothing to the+ // walk up to the repository root: the same outcomes as without it.+ it('inside a repository, is quiet in a nested package once init has written the docs at the project root', async () => {+ fs.mkdirSync(path.join(tmp, '.git'));+ write('package.json', JSON.stringify({name: 'app', dependencies: {'@astryxdesign/core': '0.7.0'}}));+ write('AGENTS.md', MARKER);+ write('functions/package.json', '{"name":"functions"}');+ const r = await runCli(['docs', 'tokens'], path.join(tmp, 'functions'));+ expect(r.stderr).not.toMatch(NUDGE);+ });++ it('inside a repository, still nudges when the only docs lie above the repository root', async () => {+ write('package.json', JSON.stringify({name: 'outer', dependencies: {'@astryxdesign/core': '0.7.0'}}));+ write('AGENTS.md', MARKER);+ fs.mkdirSync(path.join(tmp, 'repo', '.git'), {recursive: true});+ write('repo/package.json', '{"name":"repo"}');+ // It declares Astryx: a folder that declares nothing is outside a+ // project, where no reminder prints (spec AST-081 FR3).+ write(+ 'repo/functions/package.json',+ JSON.stringify({name: 'functions', dependencies: {'@astryxdesign/core': '0.7.0'}}),+ );+ const r = await runCli(['docs', 'tokens'], path.join(tmp, 'repo', 'functions'));+ expect(r.stderr).toMatch(NUDGE);+ });+it('does not nudge for the installer command itself', async () => {asProject();expect((await runCli(['init'], tmp)).stderr).not.toMatch(NUDGE);diff --git a/packages/cli/clients/cli/index.mjs b/packages/cli/clients/cli/index.mjsindex a3c42f2a6f..5d9de5ac43 100644--- a/packages/cli/clients/cli/index.mjs+++ b/packages/cli/clients/cli/index.mjs@@ -32,7 +32,12 @@ import {levenshteinDistance} from '../../foundation/text/string-utils.mjs';import {installJsonShim} from './lib/json-shim.mjs';import {addDocHelp, markReportsResult} from './lib/define-command.mjs';import {doc as manifestDoc} from './commands/manifest.doc.mjs';-import {isAstryxInitialized, isAstryxPromptInReach} from '../../foundation/agent-docs/agent-docs.mjs';+import {+ agentDocsTargetDir,+ assertAgentDocsTarget,+ 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';@@ -635,6 +640,19 @@ export async function createProgram() {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+ // Where init writes the docs, by init's own rule: the project root, which+ // can sit above a nested package such as functions/. Inside a git+ // repository the walk above already reaches it (the root never lies+ // above the repository root), so this changes nothing there; outside a+ // repository the walk checks only cwd, and this finds the root.+ if (isAstryxInitialized(agentDocsTargetDir(cwd))) return;+ // In the home folder, or at the top of a settings folder in it, init+ // writes no agent docs, so naming it would repeat on every command.+ try {+ assertAgentDocsTarget(agentDocsTargetDir(cwd));+ } catch {+ return;+ }// 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 —diff --git a/packages/cli/foundation/agent-docs/agent-doc-state.mjs b/packages/cli/foundation/agent-docs/agent-doc-state.mjsindex 007cdbf7fb..d9b6d38b80 100644--- a/packages/cli/foundation/agent-docs/agent-doc-state.mjs+++ b/packages/cli/foundation/agent-docs/agent-doc-state.mjs@@ -29,6 +29,7 @@ import * as path from 'node:path';export const AGENTS_MD = 'AGENTS.md';export const CLAUDE_MD = 'CLAUDE.md';export const CLAUDE_DIR_MD = '.claude/CLAUDE.md'; // cross-platform literal+export const GEMINI_MD = 'GEMINI.md';export const CURSOR_RULES = '.cursorrules';export const HERMES_DOT_MD = '.hermes.md';export const HERMES_MD = 'HERMES.md';@@ -41,15 +42,18 @@ export const LEGACY_MARKER_END = '<!-- XDS:END -->';/*** The canonical set of EVERY location an --agent preset (or the default) can- * write the Astryx block. SINGLE SOURCE OF TRUTH: discovery, removal, and the- * `isAstryxInitialized` predicate all derive from this list, so "where init- * writes" and "where we look" can never drift. (Explicit --agent-docs-path- * targets are user-chosen and not enumerable here.)+ * write a managed Astryx block — the full block, or the one-line import of+ * AGENTS.md that the default writes to GEMINI.md. SINGLE+ * SOURCE OF TRUTH: discovery, removal, and the `isAstryxInitialized` predicate+ * all derive from this list, so "where init writes" and "where we look" can+ * never drift. (Explicit --agent-docs-path targets are user-chosen and not+ * enumerable here.)*/export const AGENT_DOC_PATHS = [AGENTS_MD, // Codex / ChatGPT / Muse / genericCLAUDE_MD, // Claude Code (root)CLAUDE_DIR_MD, // Claude Code (.claude/CLAUDE.md)+ GEMINI_MD, // Gemini CLICURSOR_RULES, // CursorHERMES_DOT_MD, // HermesHERMES_MD, // Hermes@@ -64,7 +68,7 @@ export const INIT_MARKERS = [MARKER_START, LEGACY_MARKER_START];/*** Find all existing agent doc files in a directory, across EVERY location any* preset can write (see {@link AGENT_DOC_PATHS}: AGENTS.md, CLAUDE.md,- * .claude/CLAUDE.md, .cursorrules, .hermes.md, HERMES.md).+ * .claude/CLAUDE.md, GEMINI.md, .cursorrules, .hermes.md, HERMES.md).* @param {string} targetDir* @returns {string[]} Relative paths of existing agent doc files*/@@ -72,10 +76,33 @@ export function discoverAgentDocs(targetDir) {return AGENT_DOC_PATHS.filter(p => fs.existsSync(path.join(targetDir, p)));}+/**+ * Whether `content` holds an Astryx block. A managed block that only imports+ * another file (the one-line `@./AGENTS.md` that init writes to GEMINI.md) does+ * not count: it holds nothing once that file has lost its block. A malformed+ * block still counts, so a half-written file reads as set up.+ *+ * @param {string} content+ * @returns {boolean}+ */+export function holdsAstryxBlock(content) {+ for (const marker of INIT_MARKERS) {+ let at = content.indexOf(marker);+ while (at !== -1) {+ const from = at + marker.length;+ const end = content.indexOf('<!--', from);+ const inner = (end === -1 ? content.slice(from) : content.slice(from, end)).trim();+ if (!/^@\S+$/.test(inner)) return true;+ at = content.indexOf(marker, from);+ }+ }+ return false;+}+/*** Single source of truth for "is Astryx set up in this project?" — true when any- * agent-doc file already carries the Astryx marker, i.e. `init` / `agent-docs`- * has run. Reused by the init & upgrade commands, the per-command setup nudge+ * agent-doc file already holds an Astryx block, i.e. `init` / `agent-docs` has+ * run. Reused by the init & upgrade commands, the per-command setup nudge* (enforcement layer 3), and the cli postinstall nudge (layer 2). Core's* postinstall (separate package, layer 1) mirrors the same marker contract.*@@ -86,7 +113,7 @@ export function isAstryxInitialized(targetDir = process.cwd()) {for (const rel of discoverAgentDocs(targetDir)) {try {const content = fs.readFileSync(path.join(targetDir, rel), 'utf-8');- if (INIT_MARKERS.some(m => content.includes(m))) {+ if (holdsAstryxBlock(content)) {return true;}} catch {diff --git a/packages/cli/foundation/agent-docs/agent-docs.mjs b/packages/cli/foundation/agent-docs/agent-docs.mjsindex e75beccc70..ca5c40622a 100644--- a/packages/cli/foundation/agent-docs/agent-docs.mjs+++ b/packages/cli/foundation/agent-docs/agent-docs.mjs@@ -3,26 +3,39 @@/*** @file agent-docs — Install/update agent docs for AI coding tools*- * Generates a CLI cheat sheet from actual command metadata and injects- * it into agent doc files. Supports multiple tools with auto-detection:+ * Generates a CLI cheat sheet from actual command metadata and writes it, as+ * one managed block, into the files AI coding tools read.*- * - Claude Code: CLAUDE.md (root) or .claude/CLAUDE.md- * - Cursor: .cursorrules- * - Codex/generic: AGENTS.md- * - Muse: AGENTS.md- * - Hermes Agent: .hermes.md or HERMES.md (existing), else AGENTS.md+ * Default (no --agent or --agent-docs-path): every agent reads the block, in a+ * file the project commits.*- * Auto-detect: discovers existing files and updates them in place.- * Default (no existing files): creates AGENTS.md (the tool-agnostic standard).+ * - AGENTS.md holds the block. Most agents read it; Claude Code reads it when+ * the folder has no CLAUDE.md or .claude/CLAUDE.md.+ * - The Claude Code file the project already has holds a copy: root CLAUDE.md,+ * else .claude/CLAUDE.md, even when it imports AGENTS.md, because Claude Code+ * does not follow that import from a subfolder. Init creates no Claude file.+ * - Gemini CLI reads only GEMINI.md: it gets a managed import, `@./AGENTS.md`,+ * created when missing, unless GEMINI.md already imports AGENTS.md. Project+ * settings that point Gemini at AGENTS.md don't replace it: Gemini loads them+ * only when it starts at the project root.+ * - Existing Cursor (.cursorrules) and Hermes (.hermes.md, HERMES.md) files+ * keep a full block.+ *+ * No mode writes into the home folder, or into a settings folder in it outside a+ * project: agents read the files there in every project. A project inside a+ * settings folder, such as an agent worktree, is written normally.** --agent <tool>: target a specific tool preset (claude, cursor, codex, hermes, muse, all)* --agent-docs-path <path>: explicit file path(s)*/+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 {findCoreDir, CLI_ROOT} from '../fs/paths.mjs';import {assertWithin, PathSafetyError} from '../fs/path-safety.mjs';+import {createFileProtectionResolver} from '../fs/file-protection.mjs';import {getCliInvocation} from '../env/package-manager.mjs';import {discoverComponents} from '../discovery/component-discovery.mjs';import {Project} from '../config/project.mjs';@@ -31,9 +44,11 @@ import {humanLog} from '../response/json.mjs';import {ERROR_CODES} from '../response/error-codes.mjs';import {AGENTS_MD,+ AGENT_DOC_PATHS,CLAUDE_MD,CLAUDE_DIR_MD,CURSOR_RULES,+ GEMINI_MD,HERMES_DOT_MD,HERMES_MD,MARKER_START,@@ -80,27 +95,26 @@ function validateIntegrationLabel(value) {}/**- * Find tool-specific files that import another detected agent doc.- *- * Claude's `@path` directive is a real include, so injecting the full managed- * block beside it duplicates the same instructions. Only an import whose- * normalized target is another known agent doc counts; prose mentions and- * standalone files keep the normal initialization behavior. Import cycles have- * no canonical owner, so their members also stay standalone.+ * The `@path` imports of other agent docs in each agent doc. Only an import+ * whose normalized target is another known agent doc counts; prose mentions do+ * not. Lines inside the managed block are Astryx's own (the default writes an+ * import of AGENTS.md there), so they never count as the project's import.** @param {string} targetDir* @param {string[]} agentDocs- * @returns {Set<string>}+ * @param {string[]} [extraTargets] Import targets that count even though they+ * do not exist yet (the default always writes AGENTS.md).+ * @returns {Map<string, Set<string>>} each importing doc and the docs it imports.*/-function discoverAgentDocWrappers(targetDir, agentDocs) {- const known = new Set(agentDocs.map(p => path.normalize(p)));+function readAgentDocImports(targetDir, agentDocs, extraTargets = []) {+ const known = new Set([...agentDocs, ...extraTargets].map(p => path.normalize(p)));/** @type {Map<string, Set<string>>} */const imports = new Map();for (const rel of agentDocs) {let content;try {- content = fs.readFileSync(path.join(targetDir, rel), 'utf-8');+ content = withoutManagedBlock(fs.readFileSync(path.join(targetDir, rel), 'utf-8'));} catch {continue;}@@ -116,7 +130,21 @@ function discoverAgentDocWrappers(targetDir, agentDocs) {}if (targets.size > 0) imports.set(rel, targets);}+ return imports;+}+/**+ * Find tool-specific files that import another detected agent doc.+ *+ * Claude's `@path` directive is a real include, so injecting the full managed+ * block beside it duplicates the same instructions. Standalone files keep the+ * normal initialization behavior. Import cycles have no canonical owner, so+ * their members also stay standalone.+ *+ * @param {Map<string, Set<string>>} imports From {@link readAgentDocImports}.+ * @returns {Map<string, Set<string>>} each wrapper and the agent docs it imports.+ */+function findAgentDocWrappers(imports) {/** @param {string} start */const isCyclic = start => {/**@@ -135,7 +163,7 @@ function discoverAgentDocWrappers(targetDir, agentDocs) {return visit(start, new Set([start]));};- return new Set([...imports.keys()].filter(rel => !isCyclic(rel)));+ return new Map([...imports].filter(([rel]) => !isCyclic(rel)));}/**@@ -177,6 +205,295 @@ function findManagedBlock(content) {return null;}+/**+ * `content` with its managed block cut out. A malformed block is left in+ * place; the writers refuse it later.+ * @param {string} content+ * @returns {string}+ */+function withoutManagedBlock(content) {+ try {+ const block = findManagedBlock(content);+ return block ? content.slice(0, block.start) + content.slice(block.end) : content;+ } catch {+ return content;+ }+}++/**+ * The managed one-line import of AGENTS.md that the default writes, keyed by+ * file. Gemini CLI reads only GEMINI.md, and expands `@./AGENTS.md` there.+ *+ * @type {Readonly<Record<string, string>>}+ */+const AGENTS_IMPORTS = Object.freeze({+ [GEMINI_MD]: '@./AGENTS.md',+});++/**+ * Agent docs 0.7.0 already wrote. A path-safety refusal on one of them stays an+ * error, as it was; a file only the current layout writes is skipped instead.+ */+const LEGACY_DOC_PATHS = AGENT_DOC_PATHS.filter(p => p !== GEMINI_MD);++/**+ * The managed block holding the import of AGENTS.md for `rel`.+ * @param {string} rel A key of {@link AGENTS_IMPORTS}.+ * @returns {string}+ */+function renderAgentsImportBlock(rel) {+ return `${MARKER_START}\n${AGENTS_IMPORTS[rel]}\n${MARKER_END}`;+}++/**+ * Whether the managed block in `content` holds only an import of the root+ * AGENTS.md, resolved from the folder of `rel`. Such a block names no version,+ * so it stays current while it points at AGENTS.md.+ * @param {string} rel Project-relative path of the file `content` came from.+ * @param {string} content+ * @returns {boolean}+ */+function isAgentsImportBlock(rel, content) {+ let block;+ try {+ block = findManagedBlock(content);+ } catch {+ return false;+ }+ if (block == null) return false;+ const text = content.slice(block.start, block.end);+ const inner = text.slice(text.indexOf('-->') + 3, text.lastIndexOf('<!--')).trim();+ const match = /^@(\S+)$/.exec(inner);+ if (match == null || path.isAbsolute(match[1])) return false;+ return path.normalize(path.join(path.dirname(rel), match[1])) === AGENTS_MD;+}++/**+ * The paths Gemini CLI imports from `content`, in order. Gemini reads `@path`+ * where the `@` starts the text or follows whitespace, and the path runs to the+ * next whitespace and starts with `.`, `/` or a letter. An `@` inside backticks+ * (inline code or a fenced block) is not an import.+ * @param {string} content+ * @returns {string[]}+ */+function findGeminiImports(content) {+ /** @type {Array<[number, number]>} */+ const code = [];+ for (const match of content.matchAll(/(`+)[\s\S]*?\1/g)) {+ code.push([match.index, match.index + match[0].length]);+ }+ /** @type {string[]} */+ const found = [];+ for (const match of content.matchAll(/(?<=^|[ \t\r\n])@([^ \t\r\n]+)/g)) {+ if (!/^[./A-Za-z]/.test(match[1])) continue;+ if (code.some(([start, end]) => match.index >= start && match.index < end)) {+ continue;+ }+ found.push(match[1]);+ }+ return found;+}++/**+ * Whether GEMINI.md, outside Astryx's managed block, already has Gemini CLI+ * import AGENTS.md, on a line of its own or inline in a sentence.+ * @param {string} targetDir+ * @returns {boolean}+ */+function geminiImportsAgentsMd(targetDir) {+ let content;+ try {+ content = fs.readFileSync(path.join(targetDir, GEMINI_MD), 'utf-8');+ } catch {+ return false;+ }+ const agents = path.resolve(targetDir, AGENTS_MD);+ return findGeminiImports(withoutManagedBlock(content)).some(+ rel => path.resolve(targetDir, rel) === agents,+ );+}++/**+ * Thrown when agent docs would be written into the home folder, or into a+ * settings folder in it such as `~/.gemini` outside a project. Agents read the+ * files there (for example `~/.claude/CLAUDE.md` or `~/.gemini/GEMINI.md`) in+ * every project, so a project's version-pinned block never goes there. Removal+ * stays allowed.+ */+export class AgentDocsHomeError extends Error {+ /** @param {string} dir */+ constructor(dir) {+ super(+ `Agent docs are not written into the home folder, or into a settings folder in it outside a project (${dir}): agents read the files there in every project. Run init inside a project folder.`,+ );+ this.name = 'AgentDocsHomeError';+ /** The refused folder. */+ this.dir = dir;+ }+}++/**+ * `p` resolved, through symlinks when it exists.+ * @param {string} p+ * @returns {string}+ */+function realDir(p) {+ try {+ return fs.realpathSync(path.resolve(p));+ } catch {+ return path.resolve(p);+ }+}++/**+ * `dir` relative to the home folder, compared without symlinks (and without+ * case on Windows). null when there is no home folder.+ * @param {string} dir+ * @returns {string | null}+ */+function relativeToHome(dir) {+ let home;+ try {+ home = os.homedir();+ } catch {+ return null;+ }+ if (!home) return null;+ /** @param {string} p */+ const fold = p => (process.platform === 'win32' ? p.toLowerCase() : p);+ return path.relative(fold(realDir(home)), fold(realDir(dir)));+}++/**+ * Whether `dir` is the home folder.+ * @param {string} dir+ * @returns {boolean}+ */+function isHomeFolder(dir) {+ return relativeToHome(dir) === '';+}++/**+ * Whether agent docs stay out of `dir`: the home folder, or a folder in a+ * settings folder of it (a folder of the home folder whose name starts with a+ * dot, such as `~/.gemini` or `~/.claude`) that belongs to no project there.+ * Agents read the files at the top of a settings folder in every project, so+ * the settings folder itself is never a project, even with a package.json. A+ * folder below it with a package.json at or above it is a project, such as an+ * agent worktree in `~/.codex/worktrees/<id>/<repo>`.+ * @param {string} dir+ * @returns {boolean}+ */+function isHomeOrSettingsFolder(dir) {+ const rel = relativeToHome(dir);+ if (rel == null) return false;+ if (rel === '') return true;+ if (rel === '..' || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel)) {+ return false;+ }+ const parts = rel.split(path.sep);+ if (!parts[0].startsWith('.')) return false;+ // Look for a package.json from `dir` up to, not including, the settings folder.+ let current = realDir(dir);+ for (let depth = parts.length; depth > 1; depth--) {+ if (fs.existsSync(path.join(current, 'package.json'))) return false;+ current = path.dirname(current);+ }+ return true;+}++/**+ * Throw {@link AgentDocsHomeError} when `targetDir` is the home folder, or a+ * settings folder in it outside a project.+ * @param {string} targetDir+ */+export function assertAgentDocsTarget(targetDir) {+ if (isHomeOrSettingsFolder(targetDir)) throw new AgentDocsHomeError(realDir(targetDir));+}++/** Folders that mark a repository root; the project search stops there. */+const REPOSITORY_MARKERS = ['.git', '.hg', '.sl'];++/** Dependency fields where a project declares the Astryx packages it uses. */+const DEPENDENCY_FIELDS = [+ 'dependencies',+ 'devDependencies',+ 'peerDependencies',+ 'optionalDependencies',+];++/**+ * The package.json in `dir`: its parsed content, `null` when it exists but+ * does not parse, or `undefined` when there is none.+ * @param {string} dir+ * @returns {Record<string, unknown> | null | undefined}+ */+function readPackageJson(dir) {+ const file = path.join(dir, 'package.json');+ if (!fs.existsSync(file)) return undefined;+ try {+ const parsed = JSON.parse(fs.readFileSync(file, 'utf-8'));+ return parsed && typeof parsed === 'object' ? parsed : null;+ } catch {+ return null;+ }+}++/**+ * Whether a parsed package.json declares an `@astryxdesign` package.+ * @param {Record<string, unknown> | null} manifest+ * @returns {boolean}+ */+function declaresAstryx(manifest) {+ return DEPENDENCY_FIELDS.some(field => {+ const deps = manifest?.[field];+ return (+ deps != null &&+ typeof deps === 'object' &&+ Object.keys(deps).some(name => name.startsWith('@astryxdesign/'))+ );+ });+}++/**+ * The folder a run started in `cwd` writes agent docs to: the nearest folder at+ * or above it whose package.json declares an `@astryxdesign` package, else the+ * nearest folder with any package.json. The search stops at a repository root+ * and never reaches the home folder, so a stray `~/package.json` cannot pull+ * the docs there.+ * @param {string} cwd+ * @returns {string | null} null when no folder it searches has a package.json;+ * init then writes where it runs, as before.+ */+export function resolveAgentDocsRoot(cwd) {+ let dir = path.resolve(cwd);+ /** @type {string | null} */+ let nearest = null;+ for (let i = 0; i < 50 && !isHomeFolder(dir); i++) {+ const manifest = readPackageJson(dir);+ if (manifest !== undefined) {+ if (declaresAstryx(manifest)) return dir;+ nearest ??= dir;+ }+ if (REPOSITORY_MARKERS.some(marker => fs.existsSync(path.join(dir, marker)))) break;+ const parent = path.dirname(dir);+ if (parent === dir) break;+ dir = parent;+ }+ return nearest;+}++/**+ * The folder `init` run in `cwd` writes the agent docs to: the project root+ * {@link resolveAgentDocsRoot} finds, else `cwd` itself. The one definition+ * that init, its removal, and the per-command setup nudge all use.+ * @param {string} cwd+ * @returns {string}+ */+export function agentDocsTargetDir(cwd) {+ return resolveAgentDocsRoot(cwd) ?? cwd;+}+/*** Agent tool presets — maps tool names to their file search paths.* Order matters: first existing file wins, last entry is the default (created if none exist).@@ -215,6 +532,8 @@ export function parseBlockVersion(content) {* - `current` — every managed block already matches the installed version.* And the project is `missing` when no managed block exists anywhere (the repo* has agent-doc files without our markers, or none at all — i.e. never `init`ed).+ * A managed import of AGENTS.md is not a block here: it names no version and+ * stays current while AGENTS.md holds the block.** @param {string} targetDir* @param {string} [installedVersion] Defaults to the installed core version.@@ -244,6 +563,8 @@ export function inspectAgentDocs(targetDir, installedVersion, expectedBlock) {const hasNew = content.includes(MARKER_START);const hasLegacy = content.includes(LEGACY_MARKER_START);if (!hasNew && !hasLegacy) continue; // Not a block we manage.+ // An import of AGENTS.md names no version and never needs a refresh.+ if (isAgentsImportBlock(rel, content)) continue;const legacy = !hasNew && hasLegacy;const blockVersion = parseBlockVersion(content);@@ -291,8 +612,11 @@ export function inspectAgentDocs(targetDir, installedVersion, expectedBlock) {*/export function resolveAgentPaths(targetDir, agent) {if (agent === 'all') {- // Inject into all existing files, create defaults for each tool- const existing = discoverAgentDocs(targetDir);+ // Every existing agent doc gets the block, except GEMINI.md, which keeps+ // the one-line import of AGENTS.md the default writes. When CLAUDE.md is+ // among them, installAgentDocs then removes the block from+ // .claude/CLAUDE.md, unless the project ignores CLAUDE.md (INV31).+ const existing = discoverAgentDocs(targetDir).filter(p => p !== GEMINI_MD);if (existing.length > 0) {return {inject: existing, create: []};}@@ -700,14 +1024,16 @@ export function injectClaudeMd(targetDir, version) {}/**- * Remove Astryx section from a file.- * If the file becomes empty (only boilerplate header remains), deletes it.+ * Remove the Astryx-managed block, between its markers, from a file, leaving+ * every other line as it is. With `deleteIfEmpty`, the file is deleted when+ * nothing is left but whitespace or the exact heading init writes into a file+ * it creates; with `deleteIfBlank`, only when nothing but whitespace is left.** @param {string} filePath- * @param {{deleteIfEmpty?: boolean}} [options]+ * @param {{deleteIfEmpty?: boolean, deleteIfBlank?: boolean}} [options]* @returns {boolean} Whether the Astryx section was found and removed*/-export function removeXdsBlock(filePath, {deleteIfEmpty = false} = {}) {+export function removeXdsBlock(filePath, {deleteIfEmpty = false, deleteIfBlank = false} = {}) {if (!fs.existsSync(filePath)) return false;let content = fs.readFileSync(filePath, 'utf-8');@@ -719,18 +1045,198 @@ export function removeXdsBlock(filePath, {deleteIfEmpty = false} = {}) {const after = content.slice(block.end).trimStart();content = before + (after ? '\n\n' + after : '') + '\n';- if (deleteIfEmpty) {- const stripped = content.replace(/^#.*\n+.*guidance.*\n*/m, '').trim();- if (!stripped) {- fs.unlinkSync(filePath);- return true;- }+ const rest = content.trim();+ if (+ (deleteIfBlank && rest === '') ||+ (deleteIfEmpty && (rest === '' || CREATED_HEADING.test(rest)))+ ) {+ fs.unlinkSync(filePath);+ return true;}fs.writeFileSync(filePath, content);return true;}+/**+ * The whole of a file init created, once its block is gone: the heading init+ * writes, `# <name>` and its one line, and nothing else.+ */+const CREATED_HEADING =+ /^# [^\n]+\n\nProject-specific guidance for AI coding agents\.$/u;++/**+ * Whether the project's ignore rules exclude root CLAUDE.md, read with the+ * working-tree ignore reader upgrade uses, from the repository root down to+ * the project root. It decides only where the copy+ * goes (a fresh clone lacks an ignored file); the managed block is written+ * whatever the ignore rules say (INV31). An ignore file that cannot be read+ * counts as excluding root CLAUDE.md, so the copy in .claude/CLAUDE.md stays.+ * @param {string} targetDir+ * @returns {boolean}+ */+function rootClaudeIgnored(targetDir) {+ return uncommittedHere(targetDir, CLAUDE_MD, true);+}++/**+ * Whether a fresh clone lacks `rel` in `targetDir`: it is untracked and+ * ignored. Inside a repository the repository answers, with every ignore+ * source it reads (its ignore files, its local exclude file and configured+ * excludes), and a tracked file is committed whatever they say, as git and+ * Mercurial ignore only untracked files. Outside one, the project's ignore+ * files answer. `unreadable` is the answer when the repository, or an ignore+ * file, cannot answer.+ * @param {string} targetDir+ * @param {string} rel+ * @param {boolean} unreadable+ * @returns {boolean}+ */+function uncommittedHere(targetDir, rel, unreadable) {+ const root = repositoryRootOf(targetDir);+ if (!root) return ignoredHere(targetDir, rel, unreadable);+ return untrackedIgnored(root, targetDir, rel) ?? unreadable;+}++/**+ * How each repository kind lists `rel` when it is untracked and ignored:+ * `git check-ignore` exits 0 for such a file and 1 otherwise (it never+ * reports a tracked file); `status -i -n` prints it, or nothing.+ */+const IGNORED_QUERIES = [+ {marker: '.git', command: 'git', args: ['check-ignore', '-q', '--'], by: 'exit'},+ {marker: '.sl', command: 'sl', args: ['status', '-i', '-n', '--'], by: 'output'},+ {marker: '.hg', command: 'hg', args: ['status', '-i', '-n', '--'], by: 'output'},+];++/**+ * Whether the repository at `root` holds `rel` in `targetDir` as untracked+ * and ignored; null, which keeps the copy, when it cannot answer: its tool is+ * not installed or cannot start, runs past the time limit, or exits with a+ * code other than its documented answers.+ * @param {string} root+ * @param {string} targetDir+ * @param {string} rel+ * @returns {boolean | null}+ */+function untrackedIgnored(root, targetDir, rel) {+ const query = IGNORED_QUERIES.find(q => fs.existsSync(path.join(root, q.marker)));+ if (!query) return null;+ const result = spawnSync(query.command, [...query.args, rel], {+ cwd: targetDir,+ encoding: 'utf-8',+ stdio: ['ignore', 'pipe', 'ignore'],+ timeout: 10_000,+ windowsHide: true,+ shell: false,+ });+ if (result.error) return null;+ if (query.by === 'exit') {+ if (result.status === 0) return true;+ if (result.status === 1) return false;+ return null;+ }+ if (result.status !== 0) return null;+ return result.stdout.trim() !== '';+}++/**+ * Whether the ignore files in `targetDir` exclude `rel`, read with the+ * working-tree ignore reader upgrade uses; for a folder outside any+ * repository. `unreadable` when an ignore file cannot be read.+ * @param {string} targetDir+ * @param {string} rel+ * @param {boolean} unreadable+ * @returns {boolean}+ */+function ignoredHere(targetDir, rel, unreadable) {+ try {+ return createFileProtectionResolver(targetDir)+ .classify(path.join(targetDir, rel))+ .some(item => item.reason === 'ignored');+ } catch {+ return unreadable;+ }+}++/**+ * The repository root at or above `dir`: the nearest folder holding `.git`,+ * `.hg`, or `.sl`. Null outside a repository.+ * @param {string} dir+ * @returns {string | null}+ */+function repositoryRootOf(dir) {+ for (let current = path.resolve(dir); ; ) {+ if (REPOSITORY_MARKERS.some(marker => fs.existsSync(path.join(current, marker)))) {+ return current;+ }+ const parent = path.dirname(current);+ if (parent === current) return null;+ current = parent;+ }+}++/**+ * Whether .claude/CLAUDE.md keeps a copy beside root CLAUDE.md (INV31): while+ * a fresh clone lacks root CLAUDE.md (the project ignores it and does not+ * track it), a .claude/CLAUDE.md the project commits (tracked, or not+ * ignored) gets the copy too (DEC-2: an extra copy beats none). One the+ * project ignores and does not track follows the usual rule: its block goes+ * once root CLAUDE.md holds one. An ignore file, or tracking, that cannot be+ * read keeps the copy.+ * @param {string} targetDir+ * @returns {boolean}+ */+function claudeDirKeepsCopy(targetDir) {+ if (!rootClaudeIgnored(targetDir)) return false;+ return !uncommittedHere(targetDir, CLAUDE_DIR_MD, false);+}++/**+ * `rels` without the files that resolve outside `targetDir`, each reported+ * through `onSkipped`.+ * @param {string} targetDir+ * @param {readonly string[]} rels+ * @param {((rel: string, reason: string) => void) | undefined} onSkipped+ * @returns {Set<string>} the files skipped+ */+function skipEscaping(targetDir, rels, onSkipped) {+ /** @type {Set<string>} */+ const skipped = new Set();+ for (const p of rels) {+ try {+ assertWithin(p, targetDir, {label: 'agent docs path'});+ } catch (err) {+ if (!(err instanceof PathSafetyError)) throw err;+ skipped.add(p);+ onSkipped?.(p, err.message);+ }+ }+ return skipped;+}++/**+ * Whether root CLAUDE.md holds `block` as its managed block, so a copy in+ * .claude/CLAUDE.md may go.+ * @param {string} targetDir+ * @param {string} block+ * @returns {boolean}+ */+function rootClaudeHolds(targetDir, block) {+ // A root CLAUDE.md the project ignores is not in a fresh clone, so it never+ // stands in for a committed copy in .claude/CLAUDE.md (an extra copy beats+ // none, DEC-2). An ignored .claude/CLAUDE.md is not in one either, so the+ // usual rule holds for it.+ if (claudeDirKeepsCopy(targetDir)) return false;+ try {+ const content = fs.readFileSync(path.join(targetDir, CLAUDE_MD), 'utf-8');+ const found = findManagedBlock(content);+ return found != null && content.slice(found.start, found.end) === block.trim();+ } catch {+ return false;+ }+}+/*** Whether an agent-doc file already carries a managed-block marker.* @param {string} filePath@@ -773,24 +1279,40 @@ function assertTargetsWithin(targetDir, relPaths) {}/**- * Remove Astryx section from all known agent doc files.+ * Throw `ERR_PATH_TRAVERSAL` when an agent doc in `targetDir` that holds a+ * managed block resolves outside `targetDir`.* @param {string} targetDir- * @returns {string[]} the project-relative files a block was removed from.- * @throws {PathSafetyError} `ERR_PATH_TRAVERSAL` when a file it would change- * resolves outside `targetDir`; nothing is changed.*/-export function removeAgentDocs(targetDir) {+function assertRemovableWithin(targetDir, skip = new Set()) {const allPaths = discoverAgentDocs(targetDir);try {assertTargetsWithin(targetDir,- allPaths.filter(p => hasRemovableBlock(path.join(targetDir, p))),+ allPaths.filter(+ p => !skip.has(p) && hasRemovableBlock(path.join(targetDir, p)),+ ),);} catch (err) {// The code reaches the error envelope as is, so it must be registered.if (!(err instanceof PathSafetyError)) throw err;throw new PathSafetyError(err.message, ERROR_CODES.ERR_PATH_TRAVERSAL);}+}++/**+ * Remove Astryx section from all known agent doc files.+ * @param {string} targetDir+ * @param {object} [options]+ * @param {string} [options.shownFrom] - Folder the logged paths are shown+ * relative to; defaults to `targetDir`.+ * @param {Set<string>} [options.skip] - Files left as they are.+ * @returns {string[]} the project-relative files a block was removed from.+ * @throws {PathSafetyError} `ERR_PATH_TRAVERSAL` when a file it would change+ * resolves outside `targetDir`; nothing is changed.+ */+export function removeAgentDocs(targetDir, {shownFrom = targetDir, skip = new Set()} = {}) {+ assertRemovableWithin(targetDir, skip);+ const allPaths = discoverAgentDocs(targetDir).filter(p => !skip.has(p));/** @type {string[]} */const removedFrom = [];@@ -799,27 +1321,374 @@ export function removeAgentDocs(targetDir) {// Delete if empty for files we created (AGENTS.md, .claude/CLAUDE.md)const deleteIfEmpty = p === AGENTS_MD || p === CLAUDE_DIR_MD;if (removeXdsBlock(filePath, {deleteIfEmpty})) {+ // The default creates GEMINI.md holding only the import of AGENTS.md.+ if (p === GEMINI_MD && fs.readFileSync(filePath, 'utf-8').trim() === '') {+ fs.unlinkSync(filePath);+ }removedFrom.push(p);+ const shown = path.relative(shownFrom, filePath).split(path.sep).join('/') || p;if (!fs.existsSync(filePath)) {- humanLog(`[ok] Removed empty ${p}`);+ humanLog(`[ok] Removed empty ${shown}`);} else {- humanLog(`[ok] Removed design system section from ${p}`);+ humanLog(`[ok] Removed design system section from ${shown}`);}}}return removedFrom;}+/**+ * Remove the managed block where init writes it, the project root (see+ * {@link resolveAgentDocsRoot}), and in `cwd`, so a block an earlier version+ * wrote in that folder goes too. Each folder is checked before anything is+ * changed. Run below the project root, a project-root agent file holding a+ * block that resolves outside the project is left as it is and reported to+ * `onSkipped`, as install does there; 0.7.x touched only `cwd`. A file in+ * `cwd`, or at the root when run there, that resolves outside refuses the run.+ *+ * @param {string} cwd+ * @param {{onSkipped?: (rel: string, reason: string) => void}} [options]+ * @returns {string[]} the files a block was removed from, relative to `cwd`+ * @throws {PathSafetyError} `ERR_PATH_TRAVERSAL`; nothing is changed+ */+export function removeProjectAgentDocs(cwd, {onSkipped} = {}) {+ const root = agentDocsTargetDir(cwd);+ const below = realDir(root) !== realDir(cwd);+ /** @type {Set<string>} */+ const rootSkip = below+ ? skipEscaping(+ root,+ discoverAgentDocs(root).filter(p => hasRemovableBlock(path.join(root, p))),+ (rel, reason) =>+ onSkipped?.(path.relative(cwd, path.join(root, rel)).split(path.sep).join('/'), reason),+ )+ : new Set();+ const dirs = below ? [root, cwd] : [cwd];+ for (const dir of dirs) assertRemovableWithin(dir, dir === root ? rootSkip : undefined);+ return dirs.flatMap(dir =>+ removeAgentDocs(dir, {shownFrom: cwd, skip: dir === root ? rootSkip : undefined}).map(rel =>+ path.relative(cwd, path.join(dir, rel)).split(path.sep).join('/'),+ ),+ );+}++/**+ * Write the block into each standalone agent doc and remove a managed block+ * from each import wrapper. A refresh (`onlyReplace`) skips files without a+ * block and leaves a managed import of AGENTS.md as it is.+ *+ * @param {string} targetDir+ * @param {string[]} existing+ * @param {Map<string, Set<string>>} givenWrappers+ * @param {string} compressedIndex+ * @param {boolean} onlyReplace+ * @param {((rel: string, reason: string) => void) | undefined} onSkipped+ * @param {boolean} [refuseEscapes] whether a file 0.7.1 wrote that escapes+ * `targetDir` refuses the run+ * @returns {string[]} files written+ */+function writeEachAgentDoc(targetDir, existing, givenWrappers, compressedIndex, onlyReplace, onSkipped, refuseEscapes = true) {+ /** @param {string} p */+ const marked = p => hasManagedMarker(path.join(targetDir, p));+ // A committed .claude/CLAUDE.md beside an ignored root CLAUDE.md keeps a+ // copy (INV31): one that already holds a block is refreshed where it is,+ // even when it imports another agent file, rather than left stale.+ const keptCopy =+ givenWrappers.has(CLAUDE_DIR_MD) && marked(CLAUDE_DIR_MD) && claudeDirKeepsCopy(targetDir);+ const wrappers = new Map(givenWrappers);+ if (keptCopy) wrappers.delete(CLAUDE_DIR_MD);+ /** @param {string} p */+ const isImport = p => {+ try {+ return isAgentsImportBlock(p, fs.readFileSync(path.join(targetDir, p), 'utf-8'));+ } catch {+ return false;+ }+ };+ // Every agent file that imports no other agent file holds a copy, GEMINI.md+ // included (INV31); a managed import of AGENTS.md is left as it is.+ const targets = existing.filter(p => !wrappers.has(p) && !isImport(p));+ const writes = targets.filter(p => !onlyReplace || marked(p));+ const strips = [...wrappers.keys()].filter(marked);+ // A file 0.7.1 did not write here (GEMINI.md, or any file when init runs+ // below the project root) that resolves outside the project is skipped and+ // reported, as in the default layout, and the rest is written. A path of a+ // file 0.7.1 wrote that escapes the project refuses the run, as in 0.7.1.+ const skipped = skipEscaping(+ targetDir,+ // A kept copy here already holds a block, which 0.7.x wrote, so its+ // escape refuses the run like any file 0.7.x wrote.+ [...writes, ...strips].filter(p => !refuseEscapes || p === GEMINI_MD),+ onSkipped,+ );+ assertTargetsWithin(+ targetDir,+ [...writes, ...strips].filter(p => !skipped.has(p)),+ );+ // A refresh skips unmarked files and a wrapper is only written when it+ // carries a block, so only the files this run writes are checked.+ /** @type {string[]} */+ const written = [];+ for (const p of targets) {+ if (skipped.has(p)) continue;+ const didWrite = injectXdsBlock(path.join(targetDir, p), compressedIndex, {onlyReplace});+ if (didWrite) written.push(p);+ }+ for (const p of wrappers.keys()) {+ if (skipped.has(p)) continue;+ // The copy in .claude/CLAUDE.md goes only once root CLAUDE.md holds it.+ if (+ p === CLAUDE_DIR_MD &&+ (skipped.has(CLAUDE_MD) || !rootClaudeHolds(targetDir, compressedIndex))+ ) {+ continue;+ }+ if (stripManagedBlock(path.join(targetDir, p), compressedIndex)) written.push(p);+ }+ return written;+}++/**+ * The Claude Code file that holds the copy of the block: root CLAUDE.md, which+ * projects commit even when they ignore .claude/, else .claude/CLAUDE.md. It+ * holds the copy even when it imports AGENTS.md: Claude Code does not follow an+ * import of a file above the folder it starts in, so a session started in a+ * subfolder reads only the copy.+ *+ * @param {Set<string>} present Existing agent docs that are not AGENTS.md under+ * another name.+ * @param {Set<string>} aliases Files that are AGENTS.md under another name.+ * @returns {string | null} null when the project has no Claude file, or when+ * root CLAUDE.md is AGENTS.md under another name and so holds the block.+ */+function claudeCopyFile(present, aliases) {+ if (aliases.has(CLAUDE_MD)) return null;+ return [CLAUDE_MD, CLAUDE_DIR_MD].find(p => present.has(p)) ?? null;+}++/**+ * Plan the default layout. AGENTS.md holds the block. The Claude Code file the+ * project already has holds a copy (see {@link claudeCopyFile}), so the block+ * sits in a file the project commits; init creates no Claude file. GEMINI.md+ * imports AGENTS.md unless it already does. Every other wrapper here imports+ * AGENTS.md, so it already reaches the block.+ *+ * @param {string} targetDir+ * @param {string[]} existing+ * @param {Map<string, Set<string>>} wrappers+ * @param {Set<string>} aliases Files that are AGENTS.md under another name;+ * they are never written.+ * @returns {Map<string, 'block' | 'import' | 'strip'>}+ */+function planDefaultAgentDocs(targetDir, existing, wrappers, aliases) {+ const present = new Set(existing.filter(p => !aliases.has(p)));+ /** @type {Map<string, 'block' | 'import' | 'strip'>} */+ const plan = new Map([[AGENTS_MD, 'block']]);++ // Claude Code reads CLAUDE.md and .claude/CLAUDE.md, and skips AGENTS.md+ // when either exists. One Claude file holds the copy, so Claude Code reads+ // it once in a subfolder and at most twice at the root, where it also+ // follows that file's import of AGENTS.md.+ const claudeCopy = claudeCopyFile(present, aliases);+ for (const p of [CLAUDE_MD, CLAUDE_DIR_MD]) {+ if (present.has(p)) plan.set(p, p === claudeCopy ? 'block' : 'strip');+ }++ // Gemini CLI reads GEMINI.md. Project settings can point it at AGENTS.md+ // too, but Gemini loads them only when it starts at the project root, so the+ // import is written anyway: two copies at the root beat none in a subfolder.+ // An import GEMINI.md already has, even inline, is enough.+ if (!aliases.has(GEMINI_MD)) {+ if (geminiImportsAgentsMd(targetDir)) {+ if (present.has(GEMINI_MD)) plan.set(GEMINI_MD, 'strip');+ } else {+ plan.set(GEMINI_MD, 'import');+ }+ }++ // Every other file: a full block when standalone, none in a wrapper.+ for (const p of present) {+ if (!plan.has(p)) plan.set(p, wrappers.has(p) ? 'strip' : 'block');+ }+ return plan;+}++/**+ * Write the default layout (see {@link planDefaultAgentDocs}).+ *+ * Path safety follows 0.7.0: an agent doc it would have written that resolves+ * outside `targetDir` refuses the whole run before any write. A file only this+ * layout writes, such as GEMINI.md, is skipped instead, reported through+ * `onSkipped`, and the rest is written.+ *+ * @param {string} targetDir+ * @param {string[]} existing+ * @param {Map<string, Set<string>>} wrappers+ * @param {Set<string>} aliases+ * @param {string} compressedIndex+ * @param {((rel: string, reason: string) => void) | undefined} onSkipped+ * @param {boolean} [refuseEscapes] whether a file 0.7.1 wrote that escapes+ * `targetDir` refuses the run+ * @returns {string[]} files written, in {@link AGENT_DOC_PATHS} order+ */+function writeDefaultAgentDocs(targetDir, existing, wrappers, aliases, compressedIndex, onSkipped, refuseEscapes = true) {+ const plan = planDefaultAgentDocs(targetDir, existing, wrappers, aliases);+ // While root CLAUDE.md is one the project ignores, .claude/CLAUDE.md gets+ // the copy too, first run included: a fresh clone has only that file.+ if (plan.get(CLAUDE_DIR_MD) === 'strip' && claudeDirKeepsCopy(targetDir)) {+ plan.set(CLAUDE_DIR_MD, 'block');+ }+ // 0.7.x left a block-less import of an existing AGENTS.md alone, so a Claude+ // file of that shape that now gets the copy and resolves outside the project+ // is skipped and reported. Any other agent file 0.7.x wrote, so its escape+ // still refuses the run.+ /** @param {string} p */+ const leftAlone = p =>+ existing.includes(AGENTS_MD) &&+ wrappers.get(p)?.has(AGENTS_MD) === true &&+ !hasManagedMarker(path.join(targetDir, p));+ const foundLegacy = existing.filter(p => LEGACY_DOC_PATHS.includes(p));+ /** @param {string} p */+ const legacy = p =>+ !leftAlone(p) &&+ (foundLegacy.includes(p) || (p === AGENTS_MD && foundLegacy.length === 0));++ /** @type {Set<string>} */+ const escaped = new Set();+ for (const [p, action] of [...plan]) {+ // A strip writes only a file that carries a block.+ if (action === 'strip' && !hasManagedMarker(path.join(targetDir, p))) {+ plan.delete(p);+ continue;+ }+ try {+ assertWithin(p, targetDir, {label: 'agent docs path'});+ } catch (err) {+ if (!(err instanceof PathSafetyError) || (refuseEscapes && legacy(p))) throw err;+ plan.delete(p);+ escaped.add(p);+ onSkipped?.(p, err.message);+ }+ }+ // An import of an AGENTS.md left as it is would point at no block, so the+ // GEMINI.md import is not written either.+ if (escaped.has(AGENTS_MD) && plan.get(GEMINI_MD) === 'import') {+ plan.delete(GEMINI_MD);+ onSkipped?.(GEMINI_MD, 'its import of AGENTS.md would point at a file left as it is');+ }++ /** @type {string[]} */+ const written = [];+ for (const p of AGENT_DOC_PATHS) {+ const action = plan.get(p);+ if (action == null) continue;+ const filePath = path.join(targetDir, p);+ if (action === 'strip') {+ // The copy in .claude/CLAUDE.md goes only once root CLAUDE.md holds it.+ if (+ p === CLAUDE_DIR_MD &&+ (escaped.has(CLAUDE_MD) || !rootClaudeHolds(targetDir, compressedIndex))+ ) {+ continue;+ }+ if (stripManagedBlock(filePath, compressedIndex)) written.push(p);+ continue;+ }+ fs.mkdirSync(path.dirname(filePath), {recursive: true});+ injectXdsBlock(+ filePath,+ action === 'block' ? compressedIndex : renderAgentsImportBlock(p),+ {createIfMissing: true, header: CREATED_HEADERS[p] ?? ''},+ );+ written.push(p);+ }+ return written;+}++/**+ * Heading of the AGENTS.md the default creates; the same text the presets+ * write, so `--remove-agents` recognizes and deletes it.+ * @type {Readonly<Record<string, string>>}+ */+const CREATED_HEADERS = Object.freeze({+ [AGENTS_MD]: '# AGENTS.md\n\nProject-specific guidance for AI coding agents.',+});++/**+ * Agent docs that are one file under several names (symlinks), resolved inside+ * or outside the project.+ * @param {string} targetDir+ * @param {string[]} existing+ * @returns {{agentsAliases: Set<string>, otherShared: boolean}} the files that+ * are AGENTS.md under another name, and whether any other two docs share a+ * file.+ */+function findSharedAgentDocs(targetDir, existing) {+ /** @type {Map<string, string[]>} */+ const byFile = new Map();+ for (const p of existing) {+ let real;+ try {+ real = fs.realpathSync(path.join(targetDir, p));+ } catch {+ real = path.resolve(targetDir, p);+ }+ byFile.set(real, [...(byFile.get(real) ?? []), p]);+ }+ /** @type {Set<string>} */+ const agentsAliases = new Set();+ let otherShared = false;+ for (const names of byFile.values()) {+ if (names.length < 2) continue;+ if (!names.includes(AGENTS_MD)) {+ otherShared = true;+ continue;+ }+ for (const name of names) if (name !== AGENTS_MD) agentsAliases.add(name);+ }+ return {agentsAliases, otherShared};+}++/**+ * Remove the managed block from a file that should not carry one, leaving the+ * rest of the file as it is. A malformed block is refused (throws) rather than+ * guessed at. `.claude/CLAUDE.md` is deleted when nothing but whitespace is+ * left.+ * @param {string} filePath+ * @param {string} compressedIndex+ * @returns {boolean} whether the file changed+ */+function stripManagedBlock(filePath, compressedIndex) {+ const deleteIfBlank =+ path.basename(filePath) === path.basename(CLAUDE_DIR_MD) &&+ path.basename(path.dirname(filePath)) === path.dirname(CLAUDE_DIR_MD);+ if (removeXdsBlock(filePath, {deleteIfBlank})) return true;+ if (hasManagedMarker(filePath)) {+ // Preserve the existing fail-closed behavior for malformed blocks.+ injectXdsBlock(filePath, compressedIndex, {onlyReplace: true});+ }+ return false;+}+/*** Programmatic entry point for installing agent docs.* Used by the init command, upgrade command, and agent-docs command.*- * Strategy (when no agent/paths specified):- * - Discover all existing agent doc files.- * - Leave `@path` import wrappers untouched; if an older run expanded a block- * into one, remove that duplicate block.- * - Initialize or refresh every standalone file.- * - If nothing exists, create AGENTS.md as the tool-agnostic default.+ * Default strategy (no agent/paths specified), so every agent reads the block:+ * - Write the block to AGENTS.md (created when missing).+ * - Write the block to the project's Claude Code file: root CLAUDE.md when it+ * exists, else an existing .claude/CLAUDE.md, even when it imports AGENTS.md.+ * Remove a block from the other one. Create no Claude file.+ * - Write a managed import of AGENTS.md to GEMINI.md (created when missing),+ * unless GEMINI.md already imports AGENTS.md.+ * - Keep a full block in every other existing standalone file.+ * - Leave every other `@path` import wrapper untouched; if an older run+ * expanded a block into one, remove that duplicate block. When a wrapper+ * imports a file other than AGENTS.md, the project keeps its own layout:+ * every standalone file gets the block.+ * A refresh (`onlyReplace`) rewrites existing blocks in place, the Claude+ * file's copy included, leaves imports of AGENTS.md as they are, and creates+ * nothing.** @param {string} targetDir* @param {object} [options]@@ -833,9 +1702,19 @@ export function removeAgentDocs(targetDir) {* so an integration's topics reach the agent.* @param {string} [options.renderedBlock] - Fully rendered expected block. Init* and upgrade pass one shared block to every target.+ * @param {(rel: string, reason: string) => void} [options.onSkipped] - Called+ * for each file skipped because it resolves outside `targetDir` and 0.7.1+ * never wrote it: GEMINI.md, or any file when `refuseEscapes` is false.+ * @param {boolean} [options.refuseEscapes] - Whether a file 0.7.1 wrote that+ * resolves outside `targetDir` refuses the run (default). Init passes false+ * when it runs below the project root, where 0.7.1 wrote in the folder it+ * ran in instead.* @returns {string[]} List of files written* @throws {import('../fs/path-safety.mjs').PathSafetyError} when a file it would* write resolves outside `targetDir`; nothing is written.+ * @throws {AgentDocsHomeError} when `targetDir` is the home folder, or a settings+ * folder in it outside a project, or, with `paths`, when a file's own folder+ * is; nothing is written.*/export function installAgentDocs(targetDir,@@ -847,8 +1726,14 @@ export function installAgentDocs(onlyReplace = false,topics,renderedBlock,+ onSkipped,+ refuseEscapes = true,} = {},) {+ const explicit = paths != null && paths.length > 0;+ // Explicit paths are checked file by file below: each file's own folder+ // is what agents would read in every project.+ if (!explicit) assertAgentDocsTarget(targetDir);const coreDir = findCoreDir(targetDir);const version = getXdsVersion(coreDir);const invocation = getCliInvocation(targetDir);@@ -867,13 +1752,20 @@ export function installAgentDocs(const written = [];// Explicit paths override everything- if (paths && paths.length > 0) {+ if (explicit) {// Path-safety: each --agent-docs-path entry must resolve inside the// target directory. Reject absolute paths (silent re-rooting via// path.join hides intent) and `..` traversal.for (const p of paths) {assertWithin(p, targetDir, {label: 'agent docs path'});}+ // A file directly in the home folder, or at the top of a settings folder+ // in it, is refused, as 0.7.x never wrote there unasked; a file in a+ // plain folder of the home folder, such as ~/notes/AI.md, is written.+ // Every path is checked before anything is written.+ for (const p of paths) {+ assertAgentDocsTarget(path.dirname(path.join(targetDir, p)));+ }for (const p of paths) {const filePath = path.join(targetDir, p);const dir = path.dirname(filePath);@@ -892,12 +1784,43 @@ export function installAgentDocs(// Agent presetif (agent) {const {inject, create} = resolveAgentPaths(targetDir, agent);- assertTargetsWithin(targetDir, [...inject, ...create]);- for (const p of inject) {+ // Claude Code reads CLAUDE.md and .claude/CLAUDE.md together: when the+ // block goes in CLAUDE.md, .claude/CLAUDE.md gets none, and a block there+ // is removed.+ const claudeRoot = inject.includes(CLAUDE_MD);+ // While root CLAUDE.md is ignored, a committed .claude/CLAUDE.md holds a+ // copy too, with `claude` and `all` alike (INV31), first run included.+ const keepDirCopy = claudeRoot && claudeDirKeepsCopy(targetDir);+ const injectAll = !claudeRoot+ ? inject+ : keepDirCopy+ ? [...new Set([...inject, CLAUDE_DIR_MD])].filter(p =>+ p !== CLAUDE_DIR_MD || fs.existsSync(path.join(targetDir, CLAUDE_DIR_MD)),+ )+ : inject.filter(p => p !== CLAUDE_DIR_MD);+ const dirHasBlock = hasManagedMarker(path.join(targetDir, CLAUDE_DIR_MD));+ const strip = claudeRoot && !keepDirCopy && dirHasBlock ? [CLAUDE_DIR_MD] : [];+ // A path that escapes the project refuses the run, as in 0.7.0; below the+ // project root, where 0.7.1 wrote nothing, it is skipped and reported. A+ // .claude/CLAUDE.md the preset adds beside an ignored root, which 0.7.1+ // did not write, is skipped and reported wherever init runs.+ // So is removing a block from .claude/CLAUDE.md with `claude`, whose+ // 0.7.1 preset wrote only root CLAUDE.md there; `all` wrote both, so its+ // escape still refuses.+ const added = injectAll.filter(p => !inject.includes(p));+ const unrefused = agent === 'claude' ? [...added, ...strip] : added;+ const escaping = refuseEscapes+ ? skipEscaping(targetDir, unrefused, onSkipped)+ : skipEscaping(targetDir, [...injectAll, ...create, ...strip], onSkipped);+ const injectHere = injectAll.filter(p => !escaping.has(p));+ const createHere = create.filter(p => !escaping.has(p));+ const stripHere = escaping.has(CLAUDE_MD) ? [] : strip.filter(p => !escaping.has(p));+ assertTargetsWithin(targetDir, [...injectHere, ...createHere, ...stripHere]);+ for (const p of injectHere) {injectXdsBlock(path.join(targetDir, p), compressedIndex);written.push(p);}- for (const p of create) {+ for (const p of createHere) {const filePath = path.join(targetDir, p);const dir = path.dirname(filePath);if (dir !== targetDir) {@@ -909,57 +1832,45 @@ export function installAgentDocs(});written.push(p);}+ for (const p of stripHere) {+ if (!rootClaudeHolds(targetDir, compressedIndex)) continue;+ if (stripManagedBlock(path.join(targetDir, p), compressedIndex)) written.push(p);+ }return written;}- // Auto-detect: initialize standalone files, but do not expand the managed- // block beside an `@path` import of another agent doc. Remove a block from a- // wrapper if an older run already duplicated it there.+ // Auto-detect. A refresh rewrites each existing block where it is.const existing = discoverAgentDocs(targetDir);-- if (existing.length > 0) {- const wrappers = discoverAgentDocWrappers(targetDir, existing);- const targets = existing.filter(p => !wrappers.has(p));- // A refresh skips unmarked files and a wrapper is only written when it- // carries a block, so only the files this run writes are checked.- /** @param {string} p */- const marked = p => hasManagedMarker(path.join(targetDir, p));- assertTargetsWithin(targetDir, [- ...targets.filter(p => !onlyReplace || marked(p)),- ...[...wrappers].filter(marked),- ]);-- for (const p of targets) {- const didWrite = injectXdsBlock(path.join(targetDir, p), compressedIndex, {onlyReplace});- if (didWrite) written.push(p);- }- for (const p of wrappers) {- const filePath = path.join(targetDir, p);- if (removeXdsBlock(filePath)) {- written.push(p);- } else {- const content = fs.readFileSync(filePath, 'utf-8');- if (content.includes(MARKER_START) || content.includes(LEGACY_MARKER_START)) {- // Preserve the existing fail-closed behavior for malformed blocks.- injectXdsBlock(filePath, compressedIndex, {onlyReplace: true});- }- }- }- return written;+ if (onlyReplace) {+ const wrappers = findAgentDocWrappers(readAgentDocImports(targetDir, existing));+ // The Claude file keeps its copy even when it imports AGENTS.md, so a+ // refresh rewrites that block rather than removing it.+ const {agentsAliases} = findSharedAgentDocs(targetDir, existing);+ const claudeCopy = claudeCopyFile(+ new Set(existing.filter(p => !agentsAliases.has(p))),+ agentsAliases,+ );+ if (claudeCopy != null) wrappers.delete(claudeCopy);+ // A committed .claude/CLAUDE.md kept beside an ignored root CLAUDE.md is+ // refreshed even when it imports AGENTS.md (writeEachAgentDoc).+ return writeEachAgentDoc(targetDir, existing, wrappers, compressedIndex, true, onSkipped, refuseEscapes);}-- // Nothing exists — create root AGENTS.md as the default (skip if onlyReplace).- // AGENTS.md is the tool-agnostic standard (Codex/Copilot, Cursor, Muse, and- // most agents read it), so it's the safe default. Claude-specific output is- // opt-in via `--agent claude` (→ .claude/CLAUDE.md); `--agent all` writes both.- if (onlyReplace) return written;-- const defaultPath = AGENTS_MD;- assertTargetsWithin(targetDir, [defaultPath]);- injectXdsBlock(path.join(targetDir, defaultPath), compressedIndex, {- createIfMissing: true,- header: `# AGENTS.md\n\nProject-specific guidance for AI coding agents.`,- });- written.push(defaultPath);- return written;+ // A wrapper that imports something other than AGENTS.md, or two agent docs+ // that are one file, mean the project chose its own layout: keep the+ // per-file layout then. AGENTS.md under another name is fine.+ const wrappers = findAgentDocWrappers(readAgentDocImports(targetDir, existing, [AGENTS_MD]));+ const {agentsAliases, otherShared} = findSharedAgentDocs(targetDir, existing);+ if (otherShared || [...wrappers.values()].some(targets => !targets.has(AGENTS_MD))) {+ const ownWrappers = findAgentDocWrappers(readAgentDocImports(targetDir, existing));+ return writeEachAgentDoc(targetDir, existing, ownWrappers, compressedIndex, false, onSkipped, refuseEscapes);+ }+ return writeDefaultAgentDocs(+ targetDir,+ existing,+ wrappers,+ agentsAliases,+ compressedIndex,+ onSkipped,+ refuseEscapes,+ );}diff --git a/packages/cli/foundation/agent-docs/agent-docs.path-safety.test.mjs b/packages/cli/foundation/agent-docs/agent-docs.path-safety.test.mjsindex 53fe0a2d2a..86cf546ddb 100644--- a/packages/cli/foundation/agent-docs/agent-docs.path-safety.test.mjs+++ b/packages/cli/foundation/agent-docs/agent-docs.path-safety.test.mjs@@ -10,7 +10,9 @@** Auto-detected and preset files were never checked at all, so a `CLAUDE.md`* or `.claude/` symlinked out of the project had the block written through- * it. Every case now throws PathSafetyError before any file is touched.+ * it. Every case now throws PathSafetyError before any file is touched. A file+ * only the current layout writes (GEMINI.md) that links outside is skipped and+ * reported instead, and the rest is written, so init keeps 0.7.0's exit code.** `removeAgentDocs` (`init --remove-agents`) stripped or deleted a block* through the same kind of link and reported success. It now refuses with@@ -21,9 +23,15 @@ import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';import * as fs from 'node:fs';import * as path from 'node:path';import * as os from 'node:os';-import {installAgentDocs, removeAgentDocs} from './agent-docs.mjs';+import {spawnSync} from 'node:child_process';+import {+ installAgentDocs,+ removeAgentDocs,+ removeXdsBlock,+} from './agent-docs.mjs';import {PathSafetyError} from '../fs/path-safety.mjs';import {runCli} from '../../test-utils/run-cli.mjs';+import {doc as initDoc} from '../../clients/cli/commands/init.doc.mjs';const BLOCK = '<!-- ASTRYX:START -->\nmanaged\n<!-- ASTRYX:END -->';@@ -64,9 +72,9 @@ describe('installAgentDocs path safety', () => {fs.mkdirSync(target, {recursive: true});fs.mkdirSync(outside, {recursive: true});- expect(() =>- installAgentDocs(target, {paths: ['../OUT.md']}),- ).toThrow(PathSafetyError);+ expect(() => installAgentDocs(target, {paths: ['../OUT.md']})).toThrow(+ PathSafetyError,+ );expect(fs.existsSync(path.join(tmpDir, 'OUT.md'))).toBe(false);expect(fs.readdirSync(outside)).toEqual([]);@@ -77,9 +85,9 @@ describe('installAgentDocs path safety', () => {fs.mkdirSync(target, {recursive: true});const absPath = path.join(tmpDir, 'absolute.md');- expect(() =>- installAgentDocs(target, {paths: [absPath]}),- ).toThrow(/absolute paths are not allowed/i);+ expect(() => installAgentDocs(target, {paths: [absPath]})).toThrow(+ /absolute paths are not allowed/i,+ );expect(fs.existsSync(absPath)).toBe(false);});@@ -107,6 +115,51 @@ describe('installAgentDocs never writes through a symlink out of the project', (/outside the project root/,);expect(fs.readFileSync(shared, 'utf-8')).toBe('# Shared\n');+ expect(fs.readdirSync(project)).toEqual(['CLAUDE.md']);+ });++ it('skips a GEMINI.md that links outside, reports it, and writes the rest', () => {+ const {project, outside} = layout();+ const shared = path.join(outside, 'GEMINI.md');+ fs.writeFileSync(shared, '# Shared\n');+ fs.symlinkSync(shared, path.join(project, 'GEMINI.md'));+ /** @type {Array<[string, string]>} */+ const skipped = [];++ expect(+ installAgentDocs(project, {+ renderedBlock: BLOCK,+ onSkipped: (rel, reason) => skipped.push([rel, reason]),+ }),+ ).toEqual(['AGENTS.md']);+ expect(skipped).toEqual([+ ['GEMINI.md', expect.stringMatching(/outside the project root/)],+ ]);+ expect(fs.readFileSync(shared, 'utf-8')).toBe('# Shared\n');+ });++ it('leaves a .claude folder that links outside alone when root CLAUDE.md holds the copy', () => {+ const {project, outside} = layout();+ fs.writeFileSync(path.join(project, 'CLAUDE.md'), '# Claude\n');+ fs.symlinkSync(outside, path.join(project, '.claude'));++ expect(installAgentDocs(project, {renderedBlock: BLOCK})).toEqual([+ 'AGENTS.md',+ 'CLAUDE.md',+ 'GEMINI.md',+ ]);+ expect(fs.readdirSync(outside)).toEqual([]);++ // A CLAUDE.md in the linked folder with no block is not written either.+ fs.writeFileSync(path.join(outside, 'CLAUDE.md'), '# Shared\n');+ expect(installAgentDocs(project, {renderedBlock: BLOCK})).toEqual([+ 'AGENTS.md',+ 'CLAUDE.md',+ 'GEMINI.md',+ ]);+ expect(fs.readFileSync(path.join(outside, 'CLAUDE.md'), 'utf-8')).toBe(+ '# Shared\n',+ );});it('refuses a preset file reached through a symlinked directory', () => {@@ -150,7 +203,10 @@ describe('installAgentDocs never writes through a symlink out of the project', (it('refuses to refresh a managed block that lives outside', () => {const {project, outside} = layout();const shared = path.join(outside, 'CLAUDE.md');- fs.writeFileSync(shared, `# Shared\n\n${BLOCK.replace('managed', 'old')}\n`);+ fs.writeFileSync(+ shared,+ `# Shared\n\n${BLOCK.replace('managed', 'old')}\n`,+ );const before = fs.readFileSync(shared, 'utf-8');fs.symlinkSync(shared, path.join(project, 'CLAUDE.md'));@@ -197,9 +253,10 @@ describe('installAgentDocs never writes through a symlink out of the project', (fs.writeFileSync(path.join(project, 'AGENTS.md'), '# Agents\n');fs.symlinkSync('AGENTS.md', path.join(project, 'CLAUDE.md'));+ // CLAUDE.md is AGENTS.md under another name, so it already has the block.expect(installAgentDocs(project, {renderedBlock: BLOCK})).toEqual(['AGENTS.md',- 'CLAUDE.md',+ 'GEMINI.md',]);const content = fs.readFileSync(path.join(project, 'AGENTS.md'), 'utf-8');expect(content.split('<!-- ASTRYX:START -->')).toHaveLength(2);@@ -217,7 +274,10 @@ describe('init --features agents with an agent doc linked outside the project',fs.writeFileSync(shared, '# Shared\n');fs.symlinkSync(shared, path.join(project, 'CLAUDE.md'));- const json = await runCli(['init', '--features', 'agents', '--json'], project);+ const json = await runCli(+ ['init', '--features', 'agents', '--json'],+ project,+ );expect(json.status).toBe(1);const env = JSON.parse(json.stdout);expect(env.type).toBe('init.run');@@ -228,6 +288,38 @@ describe('init --features agents with an agent doc linked outside the project',expect(fs.readFileSync(shared, 'utf-8')).toBe('# Shared\n');}, 30_000);++ it('a GEMINI.md linked outside is skipped and reported, and init exits 0', async () => {+ const project = path.join(tmpDir, 'project');+ const outside = path.join(tmpDir, 'outside');+ fs.mkdirSync(project, {recursive: true});+ fs.mkdirSync(outside, {recursive: true});+ fs.writeFileSync(path.join(project, 'package.json'), '{"name":"app"}\n');+ const shared = path.join(outside, 'GEMINI.md');+ fs.writeFileSync(shared, '# Shared\n');+ fs.symlinkSync(shared, path.join(project, 'GEMINI.md'));++ const json = await runCli(+ ['init', '--features', 'agents', '--json'],+ project,+ );+ expect(json.status).toBe(0);+ const env = JSON.parse(json.stdout);+ expect(env.data.docsWritten).toEqual(['AGENTS.md']);+ expect(env.data.docsError).toEqual({+ kind: 'install-failed',+ message: expect.stringMatching(+ /^Left as it is: GEMINI\.md \(.*outside the project root/,+ ),+ });++ const text = await runCli(['init', '--features', 'agents'], project);+ expect(text.status).toBe(0);+ expect(text.stderr).toMatch(/^Note: Left as it is: GEMINI\.md/m);+ expect(text.stderr).not.toMatch(/Error:/);++ expect(fs.readFileSync(shared, 'utf-8')).toBe('# Shared\n');+ }, 30_000);});describe('removeAgentDocs never changes a file out of the project', () => {@@ -271,14 +363,21 @@ describe('removeAgentDocs never changes a file out of the project', () => {fs.writeFileSync(shared, `# Shared\n\n${BLOCK}\n`);fs.symlinkSync(shared, path.join(project, 'CLAUDE.md'));- expect(thrownBy(() => removeAgentDocs(project))).toBeInstanceOf(PathSafetyError);- expect(fs.readFileSync(path.join(project, 'AGENTS.md'), 'utf-8')).toBe(agents);+ expect(thrownBy(() => removeAgentDocs(project))).toBeInstanceOf(+ PathSafetyError,+ );+ expect(fs.readFileSync(path.join(project, 'AGENTS.md'), 'utf-8')).toBe(+ agents,+ );expect(fs.readFileSync(shared, 'utf-8')).toBe(`# Shared\n\n${BLOCK}\n`);});it('still strips in-project blocks beside an unmarked outside link it skips', () => {const {project, outside} = layout();- fs.writeFileSync(path.join(project, 'AGENTS.md'), `# Agents\n\nkeep\n\n${BLOCK}\n`);+ fs.writeFileSync(+ path.join(project, 'AGENTS.md'),+ `# Agents\n\nkeep\n\n${BLOCK}\n`,+ );const shared = path.join(outside, 'rules');fs.writeFileSync(shared, 'rules\n');fs.symlinkSync(shared, path.join(project, '.cursorrules'));@@ -292,7 +391,10 @@ describe('removeAgentDocs never changes a file out of the project', () => {it('strips through a symlink that stays inside the project', () => {const {project} = layout();- fs.writeFileSync(path.join(project, 'AGENTS.md'), `# Agents\n\nkeep\n\n${BLOCK}\n`);+ fs.writeFileSync(+ path.join(project, 'AGENTS.md'),+ `# Agents\n\nkeep\n\n${BLOCK}\n`,+ );fs.symlinkSync('AGENTS.md', path.join(project, 'CLAUDE.md'));removeAgentDocs(project);@@ -315,14 +417,1134 @@ describe('init --remove-agents with an agent doc linked outside the project', ()expect(json.status).toBe(1);const env = JSON.parse(json.stdout);expect(env).toMatchObject({apiVersion: 1, code: 'ERR_PATH_TRAVERSAL'});- expect(env.error).toMatch(/"CLAUDE\.md": resolves outside the project root/);+ expect(env.error).toMatch(+ /"CLAUDE\.md": resolves outside the project root/,+ );expect(env).not.toHaveProperty('data');const text = await runCli(['init', '--remove-agents'], project);expect(text.status).toBe(1);- expect(text.stderr).toMatch(/^Error: .*"CLAUDE\.md": resolves outside the project root/m);+ expect(text.stderr).toMatch(+ /^Error: .*"CLAUDE\.md": resolves outside the project root/m,+ );expect(text.stdout).not.toMatch(/removed/i);expect(fs.readFileSync(shared, 'utf-8')).toBe(content);}, 30_000);});++describe('the managed block is written whatever ignore rules or generated markers say (INV31)', () => {+ /** @param {string} project @param {object} [options] */+ const run = (project, options = {}) => {+ /** @type {Array<[string, string]>} */+ const skipped = [];+ const written = installAgentDocs(project, {+ renderedBlock: BLOCK,+ onSkipped: (rel, reason) => skipped.push([rel, reason]),+ ...options,+ });+ return {written, skipped};+ };+ const OLD_BLOCK = '<!-- ASTRYX:START -->\nold\n<!-- ASTRYX:END -->';++ it('creates AGENTS.md and the GEMINI.md import even when ignore rules cover them', () => {+ const {project} = layout();+ fs.writeFileSync(+ path.join(project, '.gitignore'),+ 'AGENTS.md\nGEMINI.md\n',+ );++ const {written, skipped} = run(project);++ expect(written).toEqual(['AGENTS.md', 'GEMINI.md']);+ expect(skipped).toEqual([]);+ expect(fs.readFileSync(path.join(project, 'GEMINI.md'), 'utf-8')).toContain(+ '@./AGENTS.md',+ );+ });++ it('adds the import to an ignored GEMINI.md and keeps its text', () => {+ const {project} = layout();+ fs.writeFileSync(path.join(project, '.gitignore'), 'GEMINI.md\n');+ fs.writeFileSync(path.join(project, 'GEMINI.md'), '# My Gemini notes\n');++ const {written, skipped} = run(project);++ expect(written).toEqual(['AGENTS.md', 'GEMINI.md']);+ expect(skipped).toEqual([]);+ const gemini = fs.readFileSync(path.join(project, 'GEMINI.md'), 'utf-8');+ expect(gemini).toMatch(/^# My Gemini notes\n/u);+ expect(gemini).toContain('@./AGENTS.md');+ });++ it('adds the import to a GEMINI.md marked generated and keeps the marker', () => {+ const {project} = layout();+ fs.writeFileSync(+ path.join(project, 'GEMINI.md'),+ '<!-- @generated by tool -->\n# Gemini\n',+ );++ const {written} = run(project);++ expect(written).toEqual(['AGENTS.md', 'GEMINI.md']);+ const gemini = fs.readFileSync(path.join(project, 'GEMINI.md'), 'utf-8');+ expect(gemini).toMatch(/^<!-- @generated by tool -->\n# Gemini\n/u);+ expect(gemini).toContain('@./AGENTS.md');+ });++ it("writes the copy into an ignored .claude/CLAUDE.md beside the user's text", () => {+ const {project} = layout();+ fs.writeFileSync(path.join(project, '.gitignore'), '.claude/\n');+ fs.mkdirSync(path.join(project, '.claude'));+ const claude = path.join(project, '.claude', 'CLAUDE.md');+ fs.writeFileSync(claude, `# Mine\n\n${OLD_BLOCK}\n\nMore.\n`);++ const {written, skipped} = run(project);++ expect(written).toEqual(['AGENTS.md', '.claude/CLAUDE.md', 'GEMINI.md']);+ expect(skipped).toEqual([]);+ expect(fs.readFileSync(claude, 'utf-8')).toBe(+ `# Mine\n\n${BLOCK}\n\nMore.\n`,+ );+ expect(fs.readdirSync(path.join(project, '.claude'))).toEqual([+ 'CLAUDE.md',+ ]);+ });++ it('still refuses a .claude/CLAUDE.md linked outside the project (INV10)', () => {+ const {project, outside} = layout();+ const shared = path.join(outside, 'CLAUDE.md');+ fs.writeFileSync(shared, `${OLD_BLOCK}\n`);+ fs.mkdirSync(path.join(project, '.claude'));+ fs.symlinkSync(shared, path.join(project, '.claude', 'CLAUDE.md'));++ expect(() => run(project)).toThrow(/outside the project root/u);+ expect(fs.readFileSync(shared, 'utf-8')).toBe(`${OLD_BLOCK}\n`);+ });++ it('--agent claude creates .claude/CLAUDE.md as its option says, even in an ignored .claude', () => {+ const {project} = layout();+ fs.writeFileSync(path.join(project, '.gitignore'), '.claude/\n');++ const {written, skipped} = run(project, {agent: 'claude'});++ expect(written).toEqual(['.claude/CLAUDE.md']);+ expect(skipped).toEqual([]);+ expect(+ fs.readFileSync(path.join(project, '.claude', 'CLAUDE.md'), 'utf-8'),+ ).toContain(BLOCK);+ });++ it('creates the .claude folder for --agent claude in a plain project', () => {+ const {project} = layout();++ expect(+ installAgentDocs(project, {agent: 'claude', renderedBlock: BLOCK}),+ ).toEqual(['.claude/CLAUDE.md']);+ expect(fs.existsSync(path.join(project, '.claude', 'CLAUDE.md'))).toBe(+ true,+ );+ });+});++describe('a project with its own layout (INV31)', () => {+ it('gives a standalone GEMINI.md that imports no agent file a copy', () => {+ const {project} = layout();+ // AGENTS.md imports CLAUDE.md, so the project keeps its own layout.+ fs.writeFileSync(path.join(project, 'AGENTS.md'), '@CLAUDE.md\n');+ fs.writeFileSync(path.join(project, 'CLAUDE.md'), '# Claude\n');+ fs.writeFileSync(path.join(project, 'GEMINI.md'), '# Gemini\n');++ const written = installAgentDocs(project, {renderedBlock: BLOCK});++ expect(written).toContain('GEMINI.md');+ expect(fs.readFileSync(path.join(project, 'GEMINI.md'), 'utf-8')).toContain(+ BLOCK,+ );+ expect(fs.readFileSync(path.join(project, 'AGENTS.md'), 'utf-8')).toBe(+ '@CLAUDE.md\n',+ );+ });+});++describe('a GEMINI.md linked outside in its own layout, and an ignored root CLAUDE.md', () => {+ it('skips a GEMINI.md linked outside in a project with its own layout, and writes the rest', async () => {+ const {project, outside} = layout();+ fs.writeFileSync(path.join(project, 'package.json'), '{"name":"app"}\n');+ // AGENTS.md imports CLAUDE.md, so the project keeps its own layout.+ fs.writeFileSync(path.join(project, 'AGENTS.md'), '@CLAUDE.md\n');+ fs.writeFileSync(path.join(project, 'CLAUDE.md'), '# Claude\n');+ const shared = path.join(outside, 'GEMINI.md');+ fs.writeFileSync(shared, '# Shared\n');+ fs.symlinkSync(shared, path.join(project, 'GEMINI.md'));++ /** @type {Array<[string, string]>} */+ const skipped = [];+ const written = installAgentDocs(project, {+ renderedBlock: BLOCK,+ onSkipped: (rel, reason) => skipped.push([rel, reason]),+ });+ expect(written).toEqual(['CLAUDE.md']);+ expect(skipped).toEqual([+ ['GEMINI.md', expect.stringMatching(/outside the project root/u)],+ ]);+ expect(fs.readFileSync(shared, 'utf-8')).toBe('# Shared\n');++ const text = await runCli(['init', '--features', 'agents'], project);+ expect(text.status).toBe(0);+ expect(text.stderr).toMatch(/^Note: Left as it is: GEMINI\.md/mu);+ expect(text.stderr).not.toMatch(/Error:/u);+ expect(fs.readFileSync(shared, 'utf-8')).toBe('# Shared\n');+ }, 30_000);++ it('keeps, and refreshes, the committed .claude/CLAUDE.md copy while root CLAUDE.md is ignored', () => {+ const {project} = layout();+ fs.writeFileSync(path.join(project, '.gitignore'), '/CLAUDE.md\n');+ fs.writeFileSync(+ path.join(project, 'CLAUDE.md'),+ '# CLAUDE\n\nProject-specific guidance for AI coding agents.\n\n<!-- ASTRYX:START -->\nold\n<!-- ASTRYX:END -->\n',+ );+ fs.mkdirSync(path.join(project, '.claude'));+ const copy = path.join(project, '.claude', 'CLAUDE.md');+ fs.writeFileSync(+ copy,+ '# Team\n\n<!-- ASTRYX:START -->\nold\n<!-- ASTRYX:END -->\n',+ );++ const written = installAgentDocs(project, {renderedBlock: BLOCK});++ expect(written).toEqual([+ 'AGENTS.md',+ 'CLAUDE.md',+ '.claude/CLAUDE.md',+ 'GEMINI.md',+ ]);+ expect(fs.readFileSync(copy, 'utf-8')).toBe(`# Team\n\n${BLOCK}\n`);+ expect(fs.readFileSync(path.join(project, 'CLAUDE.md'), 'utf-8')).toContain(+ BLOCK,+ );++ // The same with the user's own text in the ignored root CLAUDE.md.+ fs.writeFileSync(path.join(project, 'CLAUDE.md'), '# Mine\n');+ installAgentDocs(project, {renderedBlock: BLOCK});+ expect(fs.readFileSync(path.join(project, 'CLAUDE.md'), 'utf-8')).toBe(+ `# Mine\n\n${BLOCK}\n`,+ );+ expect(fs.readFileSync(copy, 'utf-8')).toBe(`# Team\n\n${BLOCK}\n`);++ // --agent claude keeps it too.+ installAgentDocs(project, {agent: 'claude', renderedBlock: BLOCK});+ expect(fs.readFileSync(copy, 'utf-8')).toContain(BLOCK);+ });+});++describe('third astracat round: first-run copy beside an ignored root, escapes below the root', () => {+ it('puts the copy in a committed .claude/CLAUDE.md on the first run while root CLAUDE.md is ignored', () => {+ const {project} = layout();+ fs.writeFileSync(path.join(project, '.gitignore'), '/CLAUDE.md\n');+ fs.writeFileSync(path.join(project, 'CLAUDE.md'), '# Mine\n');+ fs.mkdirSync(path.join(project, '.claude'));+ const copy = path.join(project, '.claude', 'CLAUDE.md');+ fs.writeFileSync(copy, '# Team\n');++ const written = installAgentDocs(project, {renderedBlock: BLOCK});++ expect(written).toEqual([+ 'AGENTS.md',+ 'CLAUDE.md',+ '.claude/CLAUDE.md',+ 'GEMINI.md',+ ]);+ expect(fs.readFileSync(copy, 'utf-8')).toBe(`# Team\n\n${BLOCK}\n`);+ });++ it('gives .claude/CLAUDE.md no copy on the first run when it is ignored too', () => {+ const {project} = layout();+ fs.writeFileSync(+ path.join(project, '.gitignore'),+ '/CLAUDE.md\n.claude/\n',+ );+ fs.writeFileSync(path.join(project, 'CLAUDE.md'), '# Mine\n');+ fs.mkdirSync(path.join(project, '.claude'));+ const copy = path.join(project, '.claude', 'CLAUDE.md');+ fs.writeFileSync(copy, '# Team\n');++ expect(installAgentDocs(project, {renderedBlock: BLOCK})).toEqual([+ 'AGENTS.md',+ 'CLAUDE.md',+ 'GEMINI.md',+ ]);+ expect(fs.readFileSync(copy, 'utf-8')).toBe('# Team\n');+ });++ it('--agent all writes .claude/CLAUDE.md beside an ignored root CLAUDE.md', () => {+ const {project} = layout();+ fs.writeFileSync(path.join(project, '.gitignore'), '/CLAUDE.md\n');+ fs.writeFileSync(path.join(project, 'CLAUDE.md'), '# Mine\n');+ fs.mkdirSync(path.join(project, '.claude'));+ const copy = path.join(project, '.claude', 'CLAUDE.md');+ fs.writeFileSync(copy, '# Team\n');++ const written = installAgentDocs(project, {+ agent: 'all',+ renderedBlock: BLOCK,+ });++ expect(written).toEqual(+ expect.arrayContaining(['CLAUDE.md', '.claude/CLAUDE.md']),+ );+ expect(fs.readFileSync(copy, 'utf-8')).toBe(`# Team\n\n${BLOCK}\n`);+ });++ it('run from a subfolder, skips a root CLAUDE.md linked outside with a note and exits 0', async () => {+ const {project, outside} = layout();+ fs.writeFileSync(path.join(project, 'package.json'), '{"name":"app"}\n');+ const shared = path.join(outside, 'CLAUDE.md');+ fs.writeFileSync(shared, '# Shared\n');+ fs.symlinkSync(shared, path.join(project, 'CLAUDE.md'));+ const sub = path.join(project, 'src');+ fs.mkdirSync(sub);++ const json = await runCli(['init', '--features', 'agents', '--json'], sub);+ expect(json.status).toBe(0);+ const {data} = JSON.parse(json.stdout);+ expect(data.docsWritten).toEqual(['../AGENTS.md', '../GEMINI.md']);+ expect(data.docsError).toEqual({+ kind: 'install-failed',+ message: expect.stringMatching(+ /^Left as it is: CLAUDE\.md \(.*outside the project root/u,+ ),+ });++ const text = await runCli(['init', '--features', 'agents'], sub);+ expect(text.status).toBe(0);+ expect(text.stderr).toMatch(/^Note: Left as it is: CLAUDE\.md/mu);+ expect(text.stderr).not.toMatch(/Error:/u);+ expect(fs.readFileSync(shared, 'utf-8')).toBe('# Shared\n');++ // Run at the root, where 0.7.1 wrote it too, the escape still exits 1.+ const atRoot = await runCli(['init', '--features', 'agents'], project);+ expect(atRoot.status).toBe(1);+ expect(fs.readFileSync(shared, 'utf-8')).toBe('# Shared\n');+ }, 60_000);+});++describe('a monorepo package whose CLAUDE.md the repository root ignores', () => {+ it.skipIf(spawnSync('git', ['--version']).status !== 0)(+ 'keeps and refreshes the committed .claude/CLAUDE.md copy',+ () => {+ const repo = path.join(tmpDir, 'repo');+ const project = path.join(repo, 'apps', 'web');+ fs.mkdirSync(repo, {recursive: true});+ spawnSync('git', ['init', '-q'], {cwd: repo});+ fs.mkdirSync(path.join(project, '.claude'), {recursive: true});+ fs.writeFileSync(path.join(repo, '.gitignore'), 'apps/web/CLAUDE.md\n');+ fs.writeFileSync(path.join(project, 'package.json'), '{"name":"web"}\n');+ fs.writeFileSync(path.join(project, 'CLAUDE.md'), '# Mine\n');+ const copy = path.join(project, '.claude', 'CLAUDE.md');+ fs.writeFileSync(+ copy,+ '# Team\n\n<!-- ASTRYX:START -->\nold\n<!-- ASTRYX:END -->\n',+ );++ const written = installAgentDocs(project, {renderedBlock: BLOCK});++ expect(written).toEqual([+ 'AGENTS.md',+ 'CLAUDE.md',+ '.claude/CLAUDE.md',+ 'GEMINI.md',+ ]);+ expect(fs.readFileSync(copy, 'utf-8')).toBe(`# Team\n\n${BLOCK}\n`);++ // Without the repository-root rule, the copy moves to root CLAUDE.md.+ fs.writeFileSync(path.join(repo, '.gitignore'), '');+ installAgentDocs(project, {renderedBlock: BLOCK});+ expect(fs.readFileSync(copy, 'utf-8')).toBe('# Team\n');+ },+ );+});++describe('a Mercurial monorepo whose root .hgignore excludes the package CLAUDE.md', () => {+ for (const [label, rules] of [+ ['glob syntax', 'syntax: glob\napps/web/CLAUDE.md\n'],+ ['regexp syntax', '^apps/web/CLAUDE\\.md$\n'],+ ]) {+ it(`keeps the committed .claude/CLAUDE.md copy (${label})`, () => {+ const repo = path.join(tmpDir, 'hgrepo');+ const project = path.join(repo, 'apps', 'web');+ fs.mkdirSync(path.join(repo, '.hg'), {recursive: true});+ fs.mkdirSync(path.join(project, '.claude'), {recursive: true});+ fs.writeFileSync(path.join(repo, '.hgignore'), rules);+ fs.writeFileSync(path.join(project, 'package.json'), '{"name":"web"}\n');+ fs.writeFileSync(path.join(project, 'CLAUDE.md'), '# Mine\n');+ const copy = path.join(project, '.claude', 'CLAUDE.md');+ fs.writeFileSync(copy, '# Team\n');++ const written = installAgentDocs(project, {renderedBlock: BLOCK});++ expect(written).toEqual([+ 'AGENTS.md',+ 'CLAUDE.md',+ '.claude/CLAUDE.md',+ 'GEMINI.md',+ ]);+ expect(fs.readFileSync(copy, 'utf-8')).toBe(`# Team\n\n${BLOCK}\n`);+ });+ }++ /**+ * Run `fn` with a search path holding only `tools`: name to the shell+ * script body that stands in for it, or null for a real command found on+ * the current search path. A tool left out cannot be found.+ * @param {Record<string, string | null>} tools+ * @param {() => void} fn+ */+ function withTools(tools, fn) {+ const bin = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-tools-'));+ const saved = process.env.PATH;+ try {+ for (const [name, body] of Object.entries(tools)) {+ const file = path.join(bin, name);+ if (body == null) {+ const real = spawnSync('sh', ['-c', `command -v ${name}`], {+ encoding: 'utf-8',+ }).stdout.trim();+ fs.symlinkSync(real, file);+ } else {+ fs.writeFileSync(file, `#!/bin/sh\n${body}\n`, {mode: 0o755});+ }+ }+ process.env.PATH = bin;+ fn();+ } finally {+ process.env.PATH = saved;+ fs.rmSync(bin, {recursive: true, force: true});+ }+ }++ /** A Mercurial monorepo whose package keeps a committed .claude copy. */+ function hgProject() {+ const repo = fs.mkdtempSync(path.join(tmpDir, 'hgrepo-'));+ const project = path.join(repo, 'apps', 'web');+ fs.mkdirSync(path.join(repo, '.hg'), {recursive: true});+ fs.mkdirSync(path.join(project, '.claude'), {recursive: true});+ fs.writeFileSync(+ path.join(repo, '.hgignore'),+ 'syntax: glob\napps/web/CLAUDE.md\n',+ );+ fs.writeFileSync(path.join(project, 'package.json'), '{"name":"web"}\n');+ fs.writeFileSync(path.join(project, 'CLAUDE.md'), '# Mine\n');+ const copy = path.join(project, '.claude', 'CLAUDE.md');+ fs.writeFileSync(+ copy,+ '# Team\n\n<!-- ASTRYX:START -->\nold\n<!-- ASTRYX:END -->\n',+ );+ return {project, copy};+ }++ it.skipIf(process.platform === 'win32').each([+ ['hg is not installed', {}],+ ['hg fails', {hg: 'exit 255'}],+ ['hg exits with a code it does not document', {hg: 'exit 2'}],+ ])(+ 'keeps the copy when the repository cannot answer: %s (fails closed)',+ (_label, tools) => {+ const {project, copy} = hgProject();+ withTools(tools, () => installAgentDocs(project, {renderedBlock: BLOCK}));+ expect(fs.readFileSync(copy, 'utf-8')).toBe(`# Team\n\n${BLOCK}\n`);+ },+ );++ it.skipIf(process.platform === 'win32')(+ 'follows the repository when it answers: a root CLAUDE.md it does not list as ignored moves the copy',+ () => {+ const {project, copy} = hgProject();+ // hg answers, and lists nothing as untracked and ignored.+ withTools({hg: 'exit 0'}, () =>+ installAgentDocs(project, {renderedBlock: BLOCK}),+ );+ expect(fs.readFileSync(copy, 'utf-8').trimEnd()).toBe('# Team');+ },+ );+});++describe('below the project root, an AGENTS.md left as it is', () => {+ it('skips the GEMINI.md import of it too (no import for doctor to fail on) and names both in one note', async () => {+ const {project, outside} = layout();+ fs.writeFileSync(path.join(project, 'package.json'), '{"name":"app"}\n');+ const shared = path.join(outside, 'AGENTS.md');+ fs.writeFileSync(shared, '# Shared\n');+ fs.symlinkSync(shared, path.join(project, 'AGENTS.md'));+ const sub = path.join(project, 'src');+ fs.mkdirSync(sub);++ const json = await runCli(['init', '--features', 'agents', '--json'], sub);+ expect(json.status).toBe(0);+ const {data} = JSON.parse(json.stdout);+ expect(data.docsWritten).toEqual([]);+ expect(data.docsError.message).toMatch(+ /^Left as they are: AGENTS\.md \(.*outside the project root.*\); GEMINI\.md \(its import of AGENTS\.md/u,+ );+ expect(fs.existsSync(path.join(project, 'GEMINI.md'))).toBe(false);++ const text = await runCli(['init', '--features', 'agents'], sub);+ expect(text.status).toBe(0);+ expect(text.stderr.split('\n').filter(Boolean)).toEqual([+ expect.stringMatching(+ /^Note: Left as they are: AGENTS\.md .*; GEMINI\.md /u,+ ),+ ]);+ expect(fs.readFileSync(shared, 'utf-8')).toBe('# Shared\n');+ }, 60_000);+});++describe('round 6: an ignored .claude/CLAUDE.md follows the usual rule; --agent claude refreshes a kept copy', () => {+ const OLD = '<!-- ASTRYX:START -->\nold\n<!-- ASTRYX:END -->';++ it('strips the block from an ignored .claude/CLAUDE.md once the ignored root CLAUDE.md holds it', () => {+ const {project} = layout();+ fs.writeFileSync(+ path.join(project, '.gitignore'),+ '/CLAUDE.md\n.claude/\n',+ );+ fs.writeFileSync(path.join(project, 'CLAUDE.md'), '# Mine\n');+ fs.mkdirSync(path.join(project, '.claude'));+ const copy = path.join(project, '.claude', 'CLAUDE.md');+ fs.writeFileSync(copy, `# Team\n\n${OLD}\n`);++ const written = installAgentDocs(project, {renderedBlock: BLOCK});++ expect(written).toEqual([+ 'AGENTS.md',+ 'CLAUDE.md',+ '.claude/CLAUDE.md',+ 'GEMINI.md',+ ]);+ expect(fs.readFileSync(copy, 'utf-8').trimEnd()).toBe('# Team');+ expect(fs.readFileSync(path.join(project, 'CLAUDE.md'), 'utf-8')).toContain(+ BLOCK,+ );++ // --agent claude follows the same rule.+ fs.writeFileSync(copy, `# Team\n\n${OLD}\n`);+ installAgentDocs(project, {agent: 'claude', renderedBlock: BLOCK});+ expect(fs.readFileSync(copy, 'utf-8').trimEnd()).toBe('# Team');+ });++ it('keeps and refreshes a committed .claude/CLAUDE.md block with --agent claude beside an ignored root', () => {+ const {project} = layout();+ fs.writeFileSync(path.join(project, '.gitignore'), '/CLAUDE.md\n');+ fs.writeFileSync(path.join(project, 'CLAUDE.md'), '# Mine\n');+ fs.mkdirSync(path.join(project, '.claude'));+ const copy = path.join(project, '.claude', 'CLAUDE.md');+ fs.writeFileSync(copy, `# Team\n\n${OLD}\n`);++ const written = installAgentDocs(project, {+ agent: 'claude',+ renderedBlock: BLOCK,+ });++ expect(written).toEqual(['CLAUDE.md', '.claude/CLAUDE.md']);+ expect(fs.readFileSync(copy, 'utf-8')).toBe(`# Team\n\n${BLOCK}\n`);+ expect(fs.readFileSync(path.join(project, 'CLAUDE.md'), 'utf-8')).toBe(+ `# Mine\n\n${BLOCK}\n`,+ );+ });++ it('--agent claude writes the committed .claude/CLAUDE.md copy on a first run beside an ignored root', () => {+ const {project} = layout();+ fs.writeFileSync(path.join(project, '.gitignore'), '/CLAUDE.md\n');+ fs.writeFileSync(path.join(project, 'CLAUDE.md'), '# Mine\n');+ fs.mkdirSync(path.join(project, '.claude'));+ const copy = path.join(project, '.claude', 'CLAUDE.md');+ fs.writeFileSync(copy, '# Team\n');++ const written = installAgentDocs(project, {+ agent: 'claude',+ renderedBlock: BLOCK,+ });++ expect(written).toEqual(['CLAUDE.md', '.claude/CLAUDE.md']);+ expect(fs.readFileSync(copy, 'utf-8')).toBe(`# Team\n\n${BLOCK}\n`);+ });++ it('--agent claude creates no .claude/CLAUDE.md beside an ignored root when there is none', () => {+ const {project} = layout();+ fs.writeFileSync(path.join(project, '.gitignore'), '/CLAUDE.md\n');+ fs.writeFileSync(path.join(project, 'CLAUDE.md'), '# Mine\n');++ expect(+ installAgentDocs(project, {agent: 'claude', renderedBlock: BLOCK}),+ ).toEqual(['CLAUDE.md']);+ expect(fs.existsSync(path.join(project, '.claude'))).toBe(false);+ });+});++describe('round 8: refreshing a committed .claude copy that imports AGENTS.md; a linked .claude with --agent claude', () => {+ it('refreshes a committed .claude/CLAUDE.md that imports AGENTS.md beside an ignored root', () => {+ const {project} = layout();+ fs.writeFileSync(path.join(project, '.gitignore'), '/CLAUDE.md\n');+ fs.writeFileSync(path.join(project, 'CLAUDE.md'), '# Mine\n');+ fs.mkdirSync(path.join(project, '.claude'));+ const copy = path.join(project, '.claude', 'CLAUDE.md');+ fs.writeFileSync(copy, '@../AGENTS.md\n');+ const OLD = '<!-- ASTRYX:START -->\nold\n<!-- ASTRYX:END -->';++ installAgentDocs(project, {renderedBlock: OLD});+ expect(fs.readFileSync(copy, 'utf-8')).toBe(`@../AGENTS.md\n\n${OLD}\n`);++ // An upgrade's refresh, twice: the copy follows the installed release.+ for (let round = 0; round < 2; round++) {+ const written = installAgentDocs(project, {+ onlyReplace: true,+ renderedBlock: BLOCK,+ });+ if (round === 0) expect(written).toContain('.claude/CLAUDE.md');+ expect(fs.readFileSync(copy, 'utf-8')).toBe(+ `@../AGENTS.md\n\n${BLOCK}\n`,+ );+ }+ });++ it('refreshes a kept .claude/CLAUDE.md copy in a project with its own layout', () => {+ const {project} = layout();+ fs.writeFileSync(path.join(project, '.gitignore'), '/CLAUDE.md\n');+ // AGENTS.md imports CLAUDE.md, so the project keeps its own layout.+ fs.writeFileSync(path.join(project, 'AGENTS.md'), '@CLAUDE.md\n');+ fs.writeFileSync(path.join(project, 'CLAUDE.md'), '# Mine\n');+ fs.mkdirSync(path.join(project, '.claude'));+ const copy = path.join(project, '.claude', 'CLAUDE.md');+ fs.writeFileSync(+ copy,+ '@../CLAUDE.md\n\n<!-- ASTRYX:START -->\nold\n<!-- ASTRYX:END -->\n',+ );++ installAgentDocs(project, {renderedBlock: BLOCK});+ expect(fs.readFileSync(copy, 'utf-8')).toBe(`@../CLAUDE.md\n\n${BLOCK}\n`);+ });++ it('skips a linked-outside block-less import of an existing AGENTS.md (the shape 0.7.x left alone), with a note, exit 0', async () => {+ const {project, outside} = layout();+ fs.writeFileSync(path.join(project, 'package.json'), '{"name":"app"}\n');+ fs.writeFileSync(path.join(project, '.gitignore'), '/CLAUDE.md\n');+ fs.writeFileSync(path.join(project, 'AGENTS.md'), '# Agents\n');+ fs.writeFileSync(path.join(project, 'CLAUDE.md'), '# Mine\n');+ fs.writeFileSync(path.join(outside, 'CLAUDE.md'), '@../AGENTS.md\n');+ fs.symlinkSync(outside, path.join(project, '.claude'), 'dir');++ /** @type {Array<[string, string]>} */+ const skipped = [];+ const written = installAgentDocs(project, {+ renderedBlock: BLOCK,+ onSkipped: (rel, reason) => skipped.push([rel, reason]),+ });+ expect(written).toEqual(['AGENTS.md', 'CLAUDE.md', 'GEMINI.md']);+ expect(skipped).toEqual([+ ['.claude/CLAUDE.md', expect.stringMatching(/outside the project root/u)],+ ]);+ expect(fs.readFileSync(path.join(outside, 'CLAUDE.md'), 'utf-8')).toBe(+ '@../AGENTS.md\n',+ );++ const text = await runCli(['init', '--features', 'agents'], project);+ expect(text.status).toBe(0);+ expect(text.stderr).toMatch(/^Note: Left as it is: \.claude\/CLAUDE\.md/mu);+ expect(fs.readFileSync(path.join(outside, 'CLAUDE.md'), 'utf-8')).toBe(+ '@../AGENTS.md\n',+ );+ }, 30_000);++ for (const [label, contents, withAgents] of [+ ['plain text', '# Shared\n', true],+ ['a block', '<!-- ASTRYX:START -->\nold\n<!-- ASTRYX:END -->\n', true],+ ['an import made before AGENTS.md exists', '@../AGENTS.md\n', false],+ ]) {+ it(`still refuses a linked-outside .claude/CLAUDE.md that 0.7.x wrote (${label}): exit 1, nothing written`, async () => {+ const {project, outside} = layout();+ fs.writeFileSync(path.join(project, 'package.json'), '{"name":"app"}\n');+ fs.writeFileSync(path.join(project, '.gitignore'), '/CLAUDE.md\n');+ if (withAgents)+ fs.writeFileSync(path.join(project, 'AGENTS.md'), '# Agents\n');+ fs.writeFileSync(path.join(project, 'CLAUDE.md'), '# Mine\n');+ fs.writeFileSync(path.join(outside, 'CLAUDE.md'), contents);+ fs.symlinkSync(outside, path.join(project, '.claude'), 'dir');+ const before = fs.readdirSync(project).sort();++ const r = await runCli(+ ['init', '--features', 'agents', '--json'],+ project,+ );+ expect(r.status).toBe(1);+ expect(JSON.parse(r.stdout).data.docsError.kind).toBe('path-safety');+ expect(fs.readFileSync(path.join(outside, 'CLAUDE.md'), 'utf-8')).toBe(+ contents,+ );+ expect(fs.readFileSync(path.join(project, 'CLAUDE.md'), 'utf-8')).toBe(+ '# Mine\n',+ );+ expect(fs.readdirSync(project).sort()).toEqual(before);+ }, 30_000);+ }++ it('--agent claude skips a .claude linked outside beside an ignored root, with a note, and writes CLAUDE.md', async () => {+ const {project, outside} = layout();+ fs.writeFileSync(path.join(project, 'package.json'), '{"name":"app"}\n');+ fs.writeFileSync(path.join(project, '.gitignore'), '/CLAUDE.md\n');+ fs.writeFileSync(path.join(project, 'CLAUDE.md'), '# Mine\n');+ fs.writeFileSync(path.join(outside, 'CLAUDE.md'), '# Shared\n');+ fs.symlinkSync(outside, path.join(project, '.claude'), 'dir');++ /** @type {Array<[string, string]>} */+ const skipped = [];+ const written = installAgentDocs(project, {+ agent: 'claude',+ renderedBlock: BLOCK,+ onSkipped: (rel, reason) => skipped.push([rel, reason]),+ });+ expect(written).toEqual(['CLAUDE.md']);+ expect(skipped).toEqual([+ ['.claude/CLAUDE.md', expect.stringMatching(/outside the project root/u)],+ ]);+ expect(fs.readFileSync(path.join(outside, 'CLAUDE.md'), 'utf-8')).toBe(+ '# Shared\n',+ );++ const text = await runCli(+ ['init', '--features', 'agents', '--agent', 'claude'],+ project,+ );+ expect(text.status).toBe(0);+ expect(text.stderr).toMatch(/^Note: Left as it is: \.claude\/CLAUDE\.md/mu);+ expect(fs.readFileSync(path.join(outside, 'CLAUDE.md'), 'utf-8')).toBe(+ '# Shared\n',+ );+ }, 30_000);+});++describe('--agent claude beside a committed CLAUDE.md, with .claude linked outside and holding a block', () => {+ it('writes CLAUDE.md, skips the .claude/CLAUDE.md block removal with a note, and exits 0, as 0.7.1 did', async () => {+ const {project, outside} = layout();+ fs.writeFileSync(path.join(project, 'package.json'), '{"name":"app"}\n');+ fs.writeFileSync(path.join(project, 'CLAUDE.md'), '# Mine\n');+ const body = '# Team\n\n<!-- ASTRYX:START -->\nold\n<!-- ASTRYX:END -->\n';+ fs.writeFileSync(path.join(outside, 'CLAUDE.md'), body);+ fs.symlinkSync(outside, path.join(project, '.claude'), 'dir');++ const r = await runCli(+ ['init', '--features', 'agents', '--agent', 'claude', '--json'],+ project,+ );+ expect(r.status).toBe(0);+ const {data} = JSON.parse(r.stdout);+ expect(data.docsWritten).toEqual(['CLAUDE.md']);+ expect(data.docsError.message).toMatch(+ /^Left as it is: \.claude\/CLAUDE\.md \(.*outside the project root/u,+ );+ expect(fs.readFileSync(path.join(project, 'CLAUDE.md'), 'utf-8')).toContain(+ BLOCK.split('\n')[0],+ );+ expect(fs.readFileSync(path.join(outside, 'CLAUDE.md'), 'utf-8')).toBe(+ body,+ );+ }, 30_000);+});++describe('a .claude folder linked outside the project: exit parity with 0.7.1 at the project root', () => {+ // Each row: preset, root CLAUDE.md (none, committed, or ignored), what the+ // linked .claude/CLAUDE.md holds (plain text, a block, or a block-less import+ // of AGENTS.md), and the exit (1 = the run refused, nothing written). Each+ // matches 0.7.1, checked across every preset, layout, root state, linked+ // .claude, AGENTS.md and GEMINI.md combination, except the three rows marked+ // `0.7.1: 1`: there 0.7.1 wrote the linked .claude/CLAUDE.md and refused,+ // while root CLAUDE.md now holds the copy and .claude/CLAUDE.md gets none, so+ // nothing is written outside and nothing is refused.+ const OLD = '<!-- ASTRYX:START -->\nold\n<!-- ASTRYX:END -->';+ const BODY = {+ plain: '# Team\n',+ block: `# Team\n\n${OLD}\n`,+ import: '@../AGENTS.md\n',+ };+ for (const [preset, root, dir, exit] of /** @type {const} */ ([+ ['default', 'none', 'plain', 1],+ ['default', 'none', 'block', 1],+ ['default', 'none', 'import', 0],+ ['default', 'committed', 'plain', 0] /* 0.7.1: 1 */,+ ['default', 'committed', 'block', 1],+ ['default', 'committed', 'import', 0],+ ['default', 'ignored', 'plain', 1],+ ['default', 'ignored', 'block', 1],+ ['default', 'ignored', 'import', 0],+ ['claude', 'none', 'plain', 1],+ ['claude', 'none', 'block', 1],+ ['claude', 'none', 'import', 1],+ ['claude', 'committed', 'plain', 0],+ ['claude', 'committed', 'block', 0],+ ['claude', 'committed', 'import', 0],+ ['claude', 'ignored', 'plain', 0],+ ['claude', 'ignored', 'block', 0],+ ['claude', 'ignored', 'import', 0],+ ['all', 'none', 'plain', 1],+ ['all', 'none', 'block', 1],+ ['all', 'none', 'import', 1],+ ['all', 'committed', 'plain', 0] /* 0.7.1: 1 */,+ ['all', 'committed', 'block', 1],+ ['all', 'committed', 'import', 0] /* 0.7.1: 1 */,+ ['all', 'ignored', 'plain', 1],+ ['all', 'ignored', 'block', 1],+ ['all', 'ignored', 'import', 1],+ ])) {+ it(`${preset}, root ${root}, .claude holds ${dir}: exit ${exit}`, () => {+ const {project, outside} = layout();+ fs.writeFileSync(path.join(project, 'AGENTS.md'), '# Agents\n');+ if (root !== 'none')+ fs.writeFileSync(path.join(project, 'CLAUDE.md'), '# Mine\n');+ if (root === 'ignored')+ fs.writeFileSync(path.join(project, '.gitignore'), '/CLAUDE.md\n');+ fs.writeFileSync(path.join(outside, 'CLAUDE.md'), BODY[dir]);+ fs.symlinkSync(outside, path.join(project, '.claude'), 'dir');++ const run = () =>+ installAgentDocs(project, {+ agent: preset === 'default' ? undefined : preset,+ renderedBlock: BLOCK,+ onSkipped: () => {},+ });+ if (exit === 1) {+ expect(run).toThrow(PathSafetyError);+ expect(fs.readFileSync(path.join(project, 'AGENTS.md'), 'utf-8')).toBe(+ '# Agents\n',+ );+ } else {+ expect(run).not.toThrow();+ }+ expect(fs.readFileSync(path.join(outside, 'CLAUDE.md'), 'utf-8')).toBe(+ BODY[dir],+ );+ });+ }+});++describe('a root CLAUDE.md linked outside the project that only imports AGENTS.md (0.7.1 left it alone)', () => {+ it('is skipped with a note and init exits 0 at the project root; the rest is written', async () => {+ const {project, outside} = layout();+ fs.writeFileSync(path.join(project, 'package.json'), '{"name":"app"}\n');+ fs.writeFileSync(path.join(project, 'AGENTS.md'), '# Agents\n');+ fs.writeFileSync(path.join(outside, 'CLAUDE.md'), '@AGENTS.md\n');+ fs.symlinkSync(+ path.join(outside, 'CLAUDE.md'),+ path.join(project, 'CLAUDE.md'),+ );++ const r = await runCli(['init', '--features', 'agents', '--json'], project);+ expect(r.status).toBe(0);+ const {data} = JSON.parse(r.stdout);+ expect(data.docsWritten).toEqual(['AGENTS.md', 'GEMINI.md']);+ expect(data.docsError.message).toMatch(+ /^Left as it is: CLAUDE\.md \(.*outside the project root/u,+ );+ expect(fs.readFileSync(path.join(outside, 'CLAUDE.md'), 'utf-8')).toBe(+ '@AGENTS.md\n',+ );+ }, 30_000);+});++describe('a tracked .claude/CLAUDE.md is committed, whatever the ignore files say (INV31)', () => {+ /** @param {string} cwd @param {...string} args */+ const git = (cwd, ...args) => {+ const r = spawnSync(+ 'git',+ ['-c', 'user.name=t', '-c', 'user.email=t@e', ...args],+ {+ cwd,+ encoding: 'utf-8',+ },+ );+ if (r.status !== 0) throw new Error(`git ${args.join(' ')}: ${r.stderr}`);+ };++ it.skipIf(spawnSync('git', ['--version']).status !== 0)(+ 'keeps the copy in a tracked .claude/CLAUDE.md when an unanchored CLAUDE.md rule ignores both',+ () => {+ const {project} = layout();+ git(project, 'init', '-q');+ fs.writeFileSync(path.join(project, '.gitignore'), 'CLAUDE.md\n');+ fs.writeFileSync(path.join(project, 'CLAUDE.md'), '# Mine\n');+ fs.mkdirSync(path.join(project, '.claude'));+ const copy = path.join(project, '.claude', 'CLAUDE.md');+ fs.writeFileSync(copy, '# Team\n');+ // Tracked despite the rule, as `git add -f` leaves it.+ git(project, 'add', '-f', '.gitignore', '.claude/CLAUDE.md');+ git(project, 'commit', '-q', '-m', 'team claude file');++ expect(installAgentDocs(project, {renderedBlock: BLOCK})).toEqual([+ 'AGENTS.md',+ 'CLAUDE.md',+ '.claude/CLAUDE.md',+ 'GEMINI.md',+ ]);+ expect(fs.readFileSync(copy, 'utf-8')).toBe(`# Team\n\n${BLOCK}\n`);+ // --agent claude keeps it too.+ installAgentDocs(project, {agent: 'claude', renderedBlock: BLOCK});+ expect(fs.readFileSync(copy, 'utf-8')).toContain(BLOCK);+ },+ );++ it.skipIf(spawnSync('git', ['--version']).status !== 0)(+ 'strips the block from an untracked .claude/CLAUDE.md the same rule ignores',+ () => {+ const {project} = layout();+ git(project, 'init', '-q');+ fs.writeFileSync(path.join(project, '.gitignore'), 'CLAUDE.md\n');+ fs.writeFileSync(path.join(project, 'CLAUDE.md'), '# Mine\n');+ fs.mkdirSync(path.join(project, '.claude'));+ const copy = path.join(project, '.claude', 'CLAUDE.md');+ fs.writeFileSync(+ copy,+ '# Team\n\n<!-- ASTRYX:START -->\nold\n<!-- ASTRYX:END -->\n',+ );++ installAgentDocs(project, {renderedBlock: BLOCK});+ expect(fs.readFileSync(copy, 'utf-8').trimEnd()).toBe('# Team');+ },+ );++ for (const [label, setUp] of [+ [+ "the repository's local exclude file",+ (/** @type {string} */ project) =>+ fs.appendFileSync(+ path.join(project, '.git', 'info', 'exclude'),+ '/CLAUDE.md\n',+ ),+ ],+ [+ 'a configured excludes file',+ (/** @type {string} */ project) => {+ const excludes = path.join(project, '..', 'global-excludes');+ fs.writeFileSync(excludes, 'CLAUDE.md\n');+ git(project, 'config', 'core.excludesFile', excludes);+ },+ ],+ ]) {+ it.skipIf(spawnSync('git', ['--version']).status !== 0)(+ `keeps the copy in a tracked .claude/CLAUDE.md while ${label} ignores an untracked root CLAUDE.md`,+ () => {+ const {project} = layout();+ git(project, 'init', '-q');+ setUp(project);+ fs.writeFileSync(path.join(project, 'CLAUDE.md'), '# Mine\n');+ fs.mkdirSync(path.join(project, '.claude'));+ const copy = path.join(project, '.claude', 'CLAUDE.md');+ fs.writeFileSync(copy, '# Team\n');+ git(project, 'add', '-f', '.claude/CLAUDE.md');+ git(project, 'commit', '-q', '-m', 'team claude file');++ expect(installAgentDocs(project, {renderedBlock: BLOCK})).toEqual([+ 'AGENTS.md',+ 'CLAUDE.md',+ '.claude/CLAUDE.md',+ 'GEMINI.md',+ ]);+ expect(fs.readFileSync(copy, 'utf-8')).toBe(`# Team\n\n${BLOCK}\n`);+ },+ );+ }++ it('keeps the copy when the repository cannot say what it ignores or tracks (fails closed)', () => {+ const {project} = layout();+ // A .git that git cannot read.+ fs.writeFileSync(path.join(project, '.git'), 'gitdir: /nowhere/.git\n');+ fs.writeFileSync(path.join(project, '.gitignore'), 'CLAUDE.md\n');+ fs.writeFileSync(path.join(project, 'CLAUDE.md'), '# Mine\n');+ fs.mkdirSync(path.join(project, '.claude'));+ const copy = path.join(project, '.claude', 'CLAUDE.md');+ fs.writeFileSync(copy, '# Team\n');++ installAgentDocs(project, {renderedBlock: BLOCK});+ expect(fs.readFileSync(copy, 'utf-8')).toBe(`# Team\n\n${BLOCK}\n`);+ });+});++describe("init's exit-code help names every soft exit-0 case these tests pin", () => {+ const exit0 = initDoc.exitCodes.find(entry => entry.code === 0)?.when ?? '';+ it.each([+ ['the home or a settings folder', /home folder, or in a settings folder/u],+ [+ 'a GEMINI.md that resolves outside the project',+ /a GEMINI\.md that resolves outside the project/u,+ ],+ [+ 'a project-root file below the root',+ /below the project root, a project-root agent file/u,+ ],+ [+ "the project's Claude Code file that only imports an existing AGENTS.md",+ /Claude Code file \(root CLAUDE\.md, or \.claude\/CLAUDE\.md when there is no root one\)[^;]*block-less import of an existing AGENTS\.md/u,+ ],+ [+ 'beside an ignored CLAUDE.md, the copy --agent claude adds or a block-less import',+ /beside a CLAUDE\.md the project ignores, the one --agent claude adds or a block-less import of an existing AGENTS\.md/u,+ ],+ [+ '--agent claude removing a block beside a CLAUDE.md',+ /with --agent claude beside a CLAUDE\.md, one whose block it would remove/u,+ ],+ ])('%s', (_label, pattern) => {+ expect(exit0).toMatch(pattern);+ });+});++describe('init exit codes and output', () => {+ it('an ignored GEMINI.md with notes: written through, exit 0, nothing on stderr', async () => {+ const {project} = layout();+ fs.writeFileSync(path.join(project, 'package.json'), '{"name":"app"}\n');+ fs.writeFileSync(path.join(project, '.gitignore'), 'GEMINI.md\n');+ fs.writeFileSync(path.join(project, 'GEMINI.md'), '# My Gemini notes\n');++ const json = await runCli(+ ['init', '--features', 'agents', '--json'],+ project,+ );+ expect(json.status).toBe(0);+ const {data} = JSON.parse(json.stdout);+ expect(data.docsWritten).toEqual(['AGENTS.md', 'GEMINI.md']);+ expect(data.docsError).toBeNull();++ const text = await runCli(['init', '--features', 'agents'], project);+ expect(text.status).toBe(0);+ expect(text.stderr).toBe('');+ }, 30_000);++ it('a path that escapes the project still exits 1, as in 0.7.1', async () => {+ const {project, outside} = layout();+ fs.writeFileSync(path.join(project, 'package.json'), '{"name":"app"}\n');+ const shared = path.join(outside, 'CLAUDE.md');+ fs.writeFileSync(shared, '# Shared\n');+ fs.symlinkSync(shared, path.join(project, 'CLAUDE.md'));++ const text = await runCli(['init', '--features', 'agents'], project);+ expect(text.status).toBe(1);+ expect(fs.readFileSync(shared, 'utf-8')).toBe('# Shared\n');+ }, 30_000);+});++describe("the sandbox app's postinstall stays quiet", () => {+ // apps/sandbox runs `astryx init --features agents` on every install, and its+ // .gitignore lists the files init writes there.+ const sandboxIgnore = fs.readFileSync(+ new URL('../../../../apps/sandbox/.gitignore', import.meta.url),+ 'utf-8',+ );++ it('prints nothing on stderr on a fresh install, a second install, or with an old .claude/CLAUDE.md init wrote', async () => {+ const {project} = layout();+ fs.writeFileSync(+ path.join(project, 'package.json'),+ '{"name":"sandbox"}\n',+ );+ fs.writeFileSync(path.join(project, '.gitignore'), sandboxIgnore);++ for (let round = 0; round < 2; round++) {+ const r = await runCli(['init', '--features', 'agents'], project);+ expect(r.status, `round ${round}`).toBe(0);+ expect(r.stderr, `round ${round}`).toBe('');+ }++ // A dev machine where an older init created .claude/CLAUDE.md.+ fs.mkdirSync(path.join(project, '.claude'), {recursive: true});+ const claude = path.join(project, '.claude', 'CLAUDE.md');+ fs.writeFileSync(+ claude,+ '# CLAUDE\n\nProject-specific guidance for AI coding agents.\n\n<!-- ASTRYX:START -->\nold\n<!-- ASTRYX:END -->\n',+ );+ const r = await runCli(['init', '--features', 'agents'], project);+ expect(r.status).toBe(0);+ expect(r.stderr).toBe('');+ expect(fs.readFileSync(claude, 'utf-8')).not.toContain('\nold\n');+ }, 60_000);+});++describe('removing the copy in .claude/CLAUDE.md', () => {+ it('removes only the managed block, keeps the user text, and only once root CLAUDE.md holds the same block', () => {+ const {project} = layout();+ fs.writeFileSync(path.join(project, 'CLAUDE.md'), '# Claude\n');+ fs.mkdirSync(path.join(project, '.claude'));+ const dirFile = path.join(project, '.claude', 'CLAUDE.md');+ fs.writeFileSync(+ dirFile,+ `# My notes\nKeep this guidance.\n\n${BLOCK}\n\nAnd this.\n`,+ );++ expect(installAgentDocs(project, {renderedBlock: BLOCK})).toEqual([+ 'AGENTS.md',+ 'CLAUDE.md',+ '.claude/CLAUDE.md',+ 'GEMINI.md',+ ]);+ expect(fs.readFileSync(dirFile, 'utf-8').trimEnd()).toBe(+ '# My notes\nKeep this guidance.\n\nAnd this.',+ );+ expect(fs.readFileSync(path.join(project, 'CLAUDE.md'), 'utf-8')).toContain(+ BLOCK,+ );+ });++ it('keeps the copy when root CLAUDE.md does not end up holding the same block', () => {+ const {project} = layout();+ // A root CLAUDE.md with a malformed block is refused before any write, so+ // the copy in .claude/CLAUDE.md stays where it is.+ fs.writeFileSync(+ path.join(project, 'CLAUDE.md'),+ '<!-- ASTRYX:START -->\nbroken\n',+ );+ fs.mkdirSync(path.join(project, '.claude'));+ const dirFile = path.join(project, '.claude', 'CLAUDE.md');+ fs.writeFileSync(dirFile, `${BLOCK}\n`);++ expect(() => installAgentDocs(project, {renderedBlock: BLOCK})).toThrow(+ /Malformed/u,+ );+ expect(fs.readFileSync(dirFile, 'utf-8')).toBe(`${BLOCK}\n`);+ });++ it('deletes .claude/CLAUDE.md only when nothing but whitespace is left', () => {+ const {project} = layout();+ fs.writeFileSync(path.join(project, 'CLAUDE.md'), '# Claude\n');+ fs.mkdirSync(path.join(project, '.claude'));+ const dirFile = path.join(project, '.claude', 'CLAUDE.md');+ fs.writeFileSync(dirFile, `\n\n${BLOCK}\n \n`);++ installAgentDocs(project, {renderedBlock: BLOCK});++ expect(fs.existsSync(dirFile)).toBe(false);+ });+});++describe('removeXdsBlock deletes only a file init created', () => {+ it('keeps a file whose own text mentions guidance (the 0.7.0 heading match deleted it)', () => {+ const {project} = layout();+ const file = path.join(project, 'AGENTS.md');+ fs.writeFileSync(+ file,+ `# Team rules\nOur guidance for reviewers.\n\n${BLOCK}\n`,+ );++ expect(removeXdsBlock(file, {deleteIfEmpty: true})).toBe(true);+ expect(fs.readFileSync(file, 'utf-8')).toBe(+ '# Team rules\nOur guidance for reviewers.\n',+ );+ });++ it('deletes a file that holds only the heading init writes', () => {+ const {project} = layout();+ const file = path.join(project, 'AGENTS.md');+ fs.writeFileSync(+ file,+ `# AGENTS.md\n\nProject-specific guidance for AI coding agents.\n\n${BLOCK}\n`,+ );++ expect(removeXdsBlock(file, {deleteIfEmpty: true})).toBe(true);+ expect(fs.existsSync(file)).toBe(false);+ });+});diff --git a/packages/cli/foundation/agent-docs/agent-docs.test.mjs b/packages/cli/foundation/agent-docs/agent-docs.test.mjsindex ad448eabf9..dae4455872 100644--- a/packages/cli/foundation/agent-docs/agent-docs.test.mjs+++ b/packages/cli/foundation/agent-docs/agent-docs.test.mjs@@ -20,10 +20,64 @@ import {renderAgentDocsBlock,inspectAgentDocs,isAstryxInitialized,+ AgentDocsHomeError,+ resolveAgentDocsRoot,} from './agent-docs.mjs';let tmpDir;+/** The managed import of AGENTS.md the default writes to GEMINI.md. */+const GEMINI_IMPORT = '<!-- ASTRYX:START -->\n@./AGENTS.md\n<!-- ASTRYX:END -->\n';+/** The heading of a .claude/CLAUDE.md the default creates. */+const CLAUDE_HEADING = '# CLAUDE\n\nProject-specific guidance for AI coding agents.\n\n';++/** Every file the default layout can write. */+const LAYOUT_FILES = ['AGENTS.md', 'CLAUDE.md', '.claude/CLAUDE.md', 'GEMINI.md'];++/**+ * How many full managed blocks the files hold, by the header every block+ * starts with. An import of AGENTS.md carries no header.+ * @param {string} dir+ * @param {string[]} files+ */+function countBlocks(dir, files) {+ return files+ .filter(f => fs.existsSync(path.join(dir, f)))+ .map(f => fs.readFileSync(path.join(dir, f), 'utf-8').split(/Astryx v\d/).length - 1)+ .reduce((a, b) => a + b, 0);+}++/**+ * Full blocks in the files each agent reads at the project root, as measured:+ * Codex reads AGENTS.md; Copilot CLI reads AGENTS.md, CLAUDE.md and GEMINI.md+ * and does not expand an import in GEMINI.md; Claude Code reads CLAUDE.md and+ * .claude/CLAUDE.md, or AGENTS.md when neither exists; Gemini CLI reads+ * GEMINI.md and expands its import of AGENTS.md.+ * @param {string} dir+ */+function blocksSeen(dir) {+ const claudeFiles = ['CLAUDE.md', '.claude/CLAUDE.md'].filter(f =>+ fs.existsSync(path.join(dir, f)),+ );+ const gemini = fs.existsSync(path.join(dir, 'GEMINI.md'))+ ? fs.readFileSync(path.join(dir, 'GEMINI.md'), 'utf-8')+ : null;+ return {+ claude: countBlocks(dir, claudeFiles.length > 0 ? claudeFiles : ['AGENTS.md']),+ codex: countBlocks(dir, ['AGENTS.md']),+ gemini:+ gemini == null+ ? 0+ : countBlocks(dir, ['GEMINI.md']) ++ (/(^|\s)@(\.\/)?AGENTS\.md(\s|$)/.test(gemini) ? countBlocks(dir, ['AGENTS.md']) : 0),+ copilot: countBlocks(dir, ['AGENTS.md', 'CLAUDE.md', 'GEMINI.md']),+ };+}+/** Every agent reads one copy. */+const ONCE_EACH = {claude: 1, codex: 1, gemini: 1, copilot: 1};+/** Copilot CLI reads AGENTS.md and a root CLAUDE.md together: the accepted duplicate. */+const COPILOT_TWICE = {claude: 1, codex: 1, gemini: 1, copilot: 2};+beforeEach(() => {tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-agent-docs-test-'));});@@ -301,7 +355,8 @@ describe('renderAgentDocsBlock', () => {'utf-8',);expect(firstAgents).toContain(renderedBlock);- expect(firstClaude).toContain(renderedBlock);+ expect(firstClaude).toBe(`# Claude\n\n${renderedBlock}\n`);+ expect(fs.existsSync(path.join(projectDir, '.claude'))).toBe(false);installAgentDocs(projectDir, {renderedBlock});expect(fs.readFileSync(path.join(projectDir, 'AGENTS.md'), 'utf-8')).toBe(@@ -655,24 +710,27 @@ describe('installAgentDocs', () => {);}- it('creates AGENTS.md when no agent docs exist (tool-agnostic default)', () => {+ it('creates AGENTS.md, plus the GEMINI.md import, when no agent docs exist', () => {setupCorePackage(tmpDir);const written = installAgentDocs(tmpDir);- expect(written).toEqual(['AGENTS.md']);+ expect(written).toEqual(['AGENTS.md', 'GEMINI.md']);expect(fs.existsSync(path.join(tmpDir, 'AGENTS.md'))).toBe(true);- // Must NOT create the Claude-specific file by default.+ // Claude Code reads AGENTS.md when the project has no CLAUDE.md, so no+ // Claude file is created.expect(fs.existsSync(path.join(tmpDir, '.claude', 'CLAUDE.md'))).toBe(false);+ expect(fs.existsSync(path.join(tmpDir, 'CLAUDE.md'))).toBe(false);const content = fs.readFileSync(path.join(tmpDir, 'AGENTS.md'), 'utf-8');expect(content).toContain('# AGENTS.md');expect(content).toContain('<!-- ASTRYX:START -->');+ expect(fs.readFileSync(path.join(tmpDir, 'GEMINI.md'), 'utf-8')).toBe(GEMINI_IMPORT);});it('defaults to AGENTS.md but writes .claude/CLAUDE.md only when --agent claude is explicit', () => {// Default (no agent): tool-agnostic AGENTS.md, never the Claude file.setupCorePackage(tmpDir);- expect(installAgentDocs(tmpDir)).toEqual(['AGENTS.md']);+ expect(installAgentDocs(tmpDir)).toEqual(['AGENTS.md', 'GEMINI.md']);expect(fs.existsSync(path.join(tmpDir, '.claude', 'CLAUDE.md'))).toBe(false);// Explicit Claude: the Claude-specific file, in a fresh project.@@ -686,46 +744,193 @@ describe('installAgentDocs', () => {}});- it('injects into CLAUDE.md at root when it exists', () => {+ it('writes the block to AGENTS.md and to root CLAUDE.md when the project has only CLAUDE.md', () => {+ // Codex reads only AGENTS.md, and Claude Code skips AGENTS.md beside a+ // CLAUDE.md. The copy goes in the committed root CLAUDE.md; init creates+ // no .claude/ folder.setupCorePackage(tmpDir);fs.writeFileSync(path.join(tmpDir, 'CLAUDE.md'), '# Claude\n\nProject rules.\n');const written = installAgentDocs(tmpDir);- expect(written).toEqual(['CLAUDE.md']);- expect(fs.existsSync(path.join(tmpDir, 'AGENTS.md'))).toBe(false);- const claudeContent = fs.readFileSync(path.join(tmpDir, 'CLAUDE.md'), 'utf-8');- expect(claudeContent).toContain('<!-- ASTRYX:START -->');- expect(claudeContent).toContain('Project rules.');+ expect(written).toEqual(['AGENTS.md', 'CLAUDE.md', 'GEMINI.md']);+ expect(+ fs.readFileSync(path.join(tmpDir, 'CLAUDE.md'), 'utf-8').startsWith(+ '# Claude\n\nProject rules.\n\n<!-- ASTRYX:START -->',+ ),+ ).toBe(true);+ expect(fs.existsSync(path.join(tmpDir, '.claude'))).toBe(false);+ expect(fs.readFileSync(path.join(tmpDir, 'GEMINI.md'), 'utf-8')).toBe(GEMINI_IMPORT);+ expect(blocksSeen(tmpDir)).toEqual(COPILOT_TWICE);});- it('injects into all existing agent doc files', () => {+ it('keeps the block in root CLAUDE.md when AGENTS.md and CLAUDE.md both exist', () => {setupCorePackage(tmpDir);fs.writeFileSync(path.join(tmpDir, 'AGENTS.md'), '# Agents\n\nAgent rules.\n');fs.writeFileSync(path.join(tmpDir, 'CLAUDE.md'), '# Claude\n\nClaude rules.\n');const written = installAgentDocs(tmpDir);- expect(written).toContain('AGENTS.md');- expect(written).toContain('CLAUDE.md');+ expect(written).toEqual(['AGENTS.md', 'CLAUDE.md', 'GEMINI.md']);const agentsContent = fs.readFileSync(path.join(tmpDir, 'AGENTS.md'), 'utf-8');- const claudeContent = fs.readFileSync(path.join(tmpDir, 'CLAUDE.md'), 'utf-8');+ expect(agentsContent).toContain('Agent rules.');expect(agentsContent).toContain('<!-- ASTRYX:START -->');- expect(claudeContent).toContain('<!-- ASTRYX:START -->');+ expect(fs.readFileSync(path.join(tmpDir, 'CLAUDE.md'), 'utf-8')).toContain(+ 'Claude rules.',+ );+ expect(blocksSeen(tmpDir)).toEqual(COPILOT_TWICE);+ });++ it('refreshes a block an older run wrote into CLAUDE.md and adds one to AGENTS.md', () => {+ setupCorePackage(tmpDir, '2.0.0');+ fs.writeFileSync(+ path.join(tmpDir, 'CLAUDE.md'),+ '# Claude\n\nRules.\n\n<!-- ASTRYX:START -->\nAstryx v1.0.0 · old\n<!-- ASTRYX:END -->\n\nMore rules.\n',+ );++ const written = installAgentDocs(tmpDir);++ expect(written).toEqual(['AGENTS.md', 'CLAUDE.md', 'GEMINI.md']);+ const claude = fs.readFileSync(path.join(tmpDir, 'CLAUDE.md'), 'utf-8');+ expect(claude).toContain('Astryx v2.0.0');+ expect(claude).not.toContain('Astryx v1.0.0');+ expect(claude).toContain('More rules.');+ expect(fs.readFileSync(path.join(tmpDir, 'AGENTS.md'), 'utf-8')).toContain(+ 'Astryx v2.0.0',+ );+ expect(blocksSeen(tmpDir)).toEqual(COPILOT_TWICE);+ });++ it('gives Claude Code one copy when CLAUDE.md and .claude/CLAUDE.md both exist', () => {+ // The copy goes in root CLAUDE.md, which projects commit even when they+ // ignore .claude/; a block an older run left in .claude/CLAUDE.md goes.+ setupCorePackage(tmpDir, '2.0.0');+ fs.writeFileSync(path.join(tmpDir, 'CLAUDE.md'), '# Claude\n');+ fs.mkdirSync(path.join(tmpDir, '.claude'));+ fs.writeFileSync(+ path.join(tmpDir, '.claude', 'CLAUDE.md'),+ '# Local\n\n<!-- ASTRYX:START -->\nAstryx v1.0.0 · old\n<!-- ASTRYX:END -->\n',+ );++ const written = installAgentDocs(tmpDir);++ expect(written).toEqual(['AGENTS.md', 'CLAUDE.md', '.claude/CLAUDE.md', 'GEMINI.md']);+ expect(fs.readFileSync(path.join(tmpDir, '.claude', 'CLAUDE.md'), 'utf-8')).toBe(+ '# Local\n',+ );+ expect(blocksSeen(tmpDir)).toEqual(COPILOT_TWICE);+ });++ it('writes the same bytes when run again', () => {+ setupCorePackage(tmpDir);+ fs.writeFileSync(path.join(tmpDir, 'CLAUDE.md'), '# Claude\n');+ installAgentDocs(tmpDir);+ const files = ['AGENTS.md', 'CLAUDE.md', 'GEMINI.md'];+ const first = files.map(f => fs.readFileSync(path.join(tmpDir, f), 'utf-8'));++ expect(installAgentDocs(tmpDir)).toEqual(files);+ expect(files.map(f => fs.readFileSync(path.join(tmpDir, f), 'utf-8'))).toEqual(first);+ });++ it('adds no import when GEMINI.md already imports AGENTS.md inline', () => {+ setupCorePackage(tmpDir);+ const gemini = '# Gemini\n\nFollow @./AGENTS.md always.\n';+ fs.writeFileSync(path.join(tmpDir, 'GEMINI.md'), gemini);++ expect(installAgentDocs(tmpDir)).toEqual(['AGENTS.md']);+ expect(fs.readFileSync(path.join(tmpDir, 'GEMINI.md'), 'utf-8')).toBe(gemini);+ expect(blocksSeen(tmpDir)).toEqual(ONCE_EACH);+ });++ it('removes its own import when GEMINI.md also imports AGENTS.md', () => {+ setupCorePackage(tmpDir);+ fs.writeFileSync(+ path.join(tmpDir, 'GEMINI.md'),+ `# Gemini\n\nSee @AGENTS.md first.\n\n${GEMINI_IMPORT}`,+ );++ expect(installAgentDocs(tmpDir)).toEqual(['AGENTS.md', 'GEMINI.md']);+ expect(fs.readFileSync(path.join(tmpDir, 'GEMINI.md'), 'utf-8')).toBe(+ '# Gemini\n\nSee @AGENTS.md first.\n',+ );+ });++ it('adds the import when GEMINI.md mentions AGENTS.md only in code or not as an import', () => {+ setupCorePackage(tmpDir);+ // Gemini CLI follows no `@` inside backticks, none glued to a word, and+ // none whose path does not name AGENTS.md exactly.+ const gemini = 'Write `@./AGENTS.md` to import.\[email protected]\nRead @./AGENTS.md.\n';+ fs.writeFileSync(path.join(tmpDir, 'GEMINI.md'), gemini);++ expect(installAgentDocs(tmpDir)).toEqual(['AGENTS.md', 'GEMINI.md']);+ expect(fs.readFileSync(path.join(tmpDir, 'GEMINI.md'), 'utf-8')).toBe(+ `${gemini}\n${GEMINI_IMPORT}`,+ );+ });++ it.each([+ ['a list', '{"context": {"fileName": ["AGENTS.md", "GEMINI.md"]}}'],+ ['a name', '{"context": {"fileName": "AGENTS.md"}}'],+ ['comments', '{\n // Gemini reads AGENTS.md\n "context": {/* both */ "fileName": ["AGENTS.md", "GEMINI.md"]}\n}\n'],+ ['another file', '{"context": {"fileName": "GEMINI.md"}}'],+ ])('writes the GEMINI.md import whatever the project Gemini settings read (%s)', (_label, settings) => {+ // Gemini loads project settings only when it starts at the project root;+ // started in a subfolder, the import is its only copy.+ setupCorePackage(tmpDir);+ fs.mkdirSync(path.join(tmpDir, '.gemini'));+ fs.writeFileSync(path.join(tmpDir, '.gemini', 'settings.json'), settings);++ expect(installAgentDocs(tmpDir)).toEqual(['AGENTS.md', 'GEMINI.md']);+ expect(fs.readFileSync(path.join(tmpDir, 'GEMINI.md'), 'utf-8')).toBe(GEMINI_IMPORT);+ });++ it('keeps its GEMINI.md import when the project Gemini settings read AGENTS.md', () => {+ setupCorePackage(tmpDir);+ fs.writeFileSync(path.join(tmpDir, 'GEMINI.md'), `# Gemini\n\n${GEMINI_IMPORT}`);+ fs.mkdirSync(path.join(tmpDir, '.gemini'));+ fs.writeFileSync(+ path.join(tmpDir, '.gemini', 'settings.json'),+ '{"context": {"fileName": ["AGENTS.md", "GEMINI.md"]}}',+ );++ expect(installAgentDocs(tmpDir)).toEqual(['AGENTS.md', 'GEMINI.md']);+ expect(fs.readFileSync(path.join(tmpDir, 'GEMINI.md'), 'utf-8')).toBe(+ `# Gemini\n\n${GEMINI_IMPORT}`,+ );+ });++ it('leaves a file that is AGENTS.md under another name alone', () => {+ setupCorePackage(tmpDir);+ fs.writeFileSync(path.join(tmpDir, 'AGENTS.md'), '# Agents\n');+ fs.symlinkSync('AGENTS.md', path.join(tmpDir, 'CLAUDE.md'));++ // Claude Code reads the block through CLAUDE.md, so no copy is added.+ expect(installAgentDocs(tmpDir)).toEqual(['AGENTS.md', 'GEMINI.md']);+ expect(fs.existsSync(path.join(tmpDir, '.claude', 'CLAUDE.md'))).toBe(false);+ expect(countBlocks(tmpDir, ['AGENTS.md'])).toBe(1);+ });++ it('keeps an existing GEMINI.md and adds the import to it', () => {+ setupCorePackage(tmpDir);+ fs.writeFileSync(path.join(tmpDir, 'GEMINI.md'), '# Gemini\n\nUse tabs.\n');++ expect(installAgentDocs(tmpDir)).toEqual(['AGENTS.md', 'GEMINI.md']);+ expect(fs.readFileSync(path.join(tmpDir, 'GEMINI.md'), 'utf-8')).toBe(+ `# Gemini\n\nUse tabs.\n\n${GEMINI_IMPORT}`,+ );});it('preserves import wrappers while initializing standalone files', () => {setupCorePackage(tmpDir);fs.writeFileSync(path.join(tmpDir, 'AGENTS.md'), '# Agents\n');- fs.mkdirSync(path.join(tmpDir, '.claude'), {recursive: true});- const wrapperPath = path.join(tmpDir, '.claude', 'CLAUDE.md');- const wrapper = '@../AGENTS.md\n';+ const wrapperPath = path.join(tmpDir, '.hermes.md');+ const wrapper = '@AGENTS.md\n';fs.writeFileSync(wrapperPath, wrapper);fs.writeFileSync(path.join(tmpDir, '.cursorrules'), 'Cursor rules.\n');const written = installAgentDocs(tmpDir);- expect(written).toEqual(['AGENTS.md', '.cursorrules']);+ expect(written).toEqual(['AGENTS.md', 'GEMINI.md', '.cursorrules']);expect(fs.readFileSync(wrapperPath, 'utf-8')).toBe(wrapper);expect(fs.readFileSync(path.join(tmpDir, 'AGENTS.md'), 'utf-8')).toContain('<!-- ASTRYX:START -->',@@ -735,7 +940,7 @@ describe('installAgentDocs', () => {);});- it('keeps cyclic imports standalone when another file exists', () => {+ it('treats cyclic imports as standalone files', () => {setupCorePackage(tmpDir);fs.writeFileSync(path.join(tmpDir, 'AGENTS.md'), '@CLAUDE.md\n');fs.writeFileSync(path.join(tmpDir, 'CLAUDE.md'), '@AGENTS.md\n');@@ -743,22 +948,30 @@ describe('installAgentDocs', () => {const written = installAgentDocs(tmpDir);- expect(written).toEqual(['AGENTS.md', 'CLAUDE.md', '.cursorrules']);- for (const rel of written) {- expect(fs.readFileSync(path.join(tmpDir, rel), 'utf-8')).toContain(- '<!-- ASTRYX:START -->',- );+ expect(written).toEqual(['AGENTS.md', 'CLAUDE.md', 'GEMINI.md', '.cursorrules']);+ for (const rel of ['AGENTS.md', 'CLAUDE.md', '.cursorrules']) {+ expect(countBlocks(tmpDir, [rel])).toBe(1);}});+ it('keeps the per-file layout when a wrapper imports a file other than AGENTS.md', () => {+ setupCorePackage(tmpDir);+ fs.writeFileSync(path.join(tmpDir, 'CLAUDE.md'), '# Claude\n');+ fs.writeFileSync(path.join(tmpDir, 'AGENTS.md'), '@CLAUDE.md\n');++ expect(installAgentDocs(tmpDir)).toEqual(['CLAUDE.md']);+ expect(fs.readFileSync(path.join(tmpDir, 'AGENTS.md'), 'utf-8')).toBe('@CLAUDE.md\n');+ expect(countBlocks(tmpDir, ['CLAUDE.md'])).toBe(1);+ expect(fs.existsSync(path.join(tmpDir, 'GEMINI.md'))).toBe(false);+ });+it('removes a managed block previously expanded into an import wrapper', () => {setupCorePackage(tmpDir);installAgentDocs(tmpDir, {agent: 'codex'});- fs.mkdirSync(path.join(tmpDir, '.claude'), {recursive: true});- const wrapperPath = path.join(tmpDir, '.claude', 'CLAUDE.md');- const wrapper = '@../AGENTS.md\n';+ const wrapperPath = path.join(tmpDir, '.hermes.md');+ const wrapper = '@AGENTS.md\n';fs.writeFileSync(wrapperPath, wrapper);- installAgentDocs(tmpDir, {agent: 'claude'});+ installAgentDocs(tmpDir, {agent: 'hermes'});expect(fs.readFileSync(wrapperPath, 'utf-8')).toContain('<!-- ASTRYX:START -->',);@@ -766,7 +979,7 @@ describe('installAgentDocs', () => {const written = installAgentDocs(tmpDir, {onlyReplace: true});expect(written).toContain('AGENTS.md');- expect(written).toContain('.claude/CLAUDE.md');+ expect(written).toContain('.hermes.md');expect(fs.readFileSync(wrapperPath, 'utf-8')).toBe(wrapper);});@@ -782,17 +995,123 @@ describe('installAgentDocs', () => {expect(() => installAgentDocs(tmpDir)).toThrow(/malformed|no matching/i);});- it('updates existing .claude/CLAUDE.md', () => {+ it('adds the block to an existing .claude/CLAUDE.md and to AGENTS.md', () => {setupCorePackage(tmpDir);fs.mkdirSync(path.join(tmpDir, '.claude'), {recursive: true});fs.writeFileSync(path.join(tmpDir, '.claude', 'CLAUDE.md'), '# Project\n\nExisting content.\n');const written = installAgentDocs(tmpDir);- expect(written).toEqual(['.claude/CLAUDE.md']);+ expect(written).toEqual(['AGENTS.md', '.claude/CLAUDE.md', 'GEMINI.md']);const content = fs.readFileSync(path.join(tmpDir, '.claude', 'CLAUDE.md'), 'utf-8');- expect(content).toContain('Existing content.');- expect(content).toContain('<!-- ASTRYX:START -->');+ expect(content.startsWith('# Project\n\nExisting content.\n\n<!-- ASTRYX:START -->')).toBe(+ true,+ );+ expect(blocksSeen(tmpDir)).toEqual(ONCE_EACH);+ });++ it('gives a root CLAUDE.md that imports AGENTS.md a copy too', () => {+ // Claude Code does not follow an import of a file above the folder it+ // starts in, so a session in a subfolder reads only the copy.+ setupCorePackage(tmpDir);+ const claude = '# Claude\n\[email protected]\n';+ fs.writeFileSync(path.join(tmpDir, 'CLAUDE.md'), claude);++ expect(installAgentDocs(tmpDir)).toEqual(['AGENTS.md', 'CLAUDE.md', 'GEMINI.md']);+ const content = fs.readFileSync(path.join(tmpDir, 'CLAUDE.md'), 'utf-8');+ expect(content.startsWith(`${claude}\n<!-- ASTRYX:START -->`)).toBe(true);+ expect(countBlocks(tmpDir, ['AGENTS.md', 'CLAUDE.md'])).toBe(2);+ expect(fs.existsSync(path.join(tmpDir, '.claude'))).toBe(false);++ // Running again keeps the copy where it is.+ expect(installAgentDocs(tmpDir)).toEqual(['AGENTS.md', 'CLAUDE.md', 'GEMINI.md']);+ expect(fs.readFileSync(path.join(tmpDir, 'CLAUDE.md'), 'utf-8')).toBe(content);+ });++ it('keeps the copy in root CLAUDE.md, not .claude/CLAUDE.md, when root CLAUDE.md imports AGENTS.md', () => {+ // Root CLAUDE.md is committed even where .claude/ is ignored, so a fresh+ // clone still gives a session in a subfolder its copy.+ setupCorePackage(tmpDir, '2.0.0');+ fs.writeFileSync(path.join(tmpDir, 'CLAUDE.md'), '# Claude\n\[email protected]\n');+ fs.mkdirSync(path.join(tmpDir, '.claude'));+ fs.writeFileSync(+ path.join(tmpDir, '.claude', 'CLAUDE.md'),+ '# Local\n\n<!-- ASTRYX:START -->\nAstryx v1.0.0 · old\n<!-- ASTRYX:END -->\n',+ );++ expect(installAgentDocs(tmpDir)).toEqual([+ 'AGENTS.md',+ 'CLAUDE.md',+ '.claude/CLAUDE.md',+ 'GEMINI.md',+ ]);+ expect(countBlocks(tmpDir, ['CLAUDE.md'])).toBe(1);+ expect(fs.readFileSync(path.join(tmpDir, '.claude', 'CLAUDE.md'), 'utf-8')).toBe(+ '# Local\n',+ );+ });++ it('gives a .claude/CLAUDE.md that imports AGENTS.md a copy when there is no root CLAUDE.md', () => {+ setupCorePackage(tmpDir);+ fs.writeFileSync(path.join(tmpDir, 'AGENTS.md'), '# Agents\n');+ fs.mkdirSync(path.join(tmpDir, '.claude'));+ fs.writeFileSync(path.join(tmpDir, '.claude', 'CLAUDE.md'), '@../AGENTS.md\n');++ expect(installAgentDocs(tmpDir)).toEqual(['AGENTS.md', '.claude/CLAUDE.md', 'GEMINI.md']);+ const content = fs.readFileSync(path.join(tmpDir, '.claude', 'CLAUDE.md'), 'utf-8');+ expect(content.startsWith('@../AGENTS.md\n\n<!-- ASTRYX:START -->')).toBe(true);+ });++ it('onlyReplace: refreshes the copy in a Claude file that imports AGENTS.md instead of removing it', () => {+ setupCorePackage(tmpDir, '1.0.0');+ fs.writeFileSync(path.join(tmpDir, 'CLAUDE.md'), '# Claude\n\[email protected]\n');+ installAgentDocs(tmpDir);+ setupCorePackage(tmpDir, '2.0.0');++ expect(installAgentDocs(tmpDir, {onlyReplace: true})).toEqual(['AGENTS.md', 'CLAUDE.md']);+ const content = fs.readFileSync(path.join(tmpDir, 'CLAUDE.md'), 'utf-8');+ expect(content).toContain('@AGENTS.md');+ expect(content).toContain('Astryx v2.0.0');+ expect(content).not.toContain('Astryx v1.0.0');+ });++ it('--agent all after the default keeps the GEMINI.md import and one Claude copy', () => {+ setupCorePackage(tmpDir);+ fs.writeFileSync(path.join(tmpDir, 'AGENTS.md'), '# Agents\n');+ fs.writeFileSync(path.join(tmpDir, 'CLAUDE.md'), '# Claude\n');+ fs.mkdirSync(path.join(tmpDir, '.claude'));+ fs.writeFileSync(path.join(tmpDir, '.claude', 'CLAUDE.md'), '# Local\n');+ installAgentDocs(tmpDir);++ expect(installAgentDocs(tmpDir, {agent: 'all'})).toEqual(['AGENTS.md', 'CLAUDE.md']);+ expect(fs.readFileSync(path.join(tmpDir, 'GEMINI.md'), 'utf-8')).toBe(GEMINI_IMPORT);+ expect(fs.readFileSync(path.join(tmpDir, '.claude', 'CLAUDE.md'), 'utf-8')).toBe(+ '# Local\n',+ );+ expect(blocksSeen(tmpDir)).toEqual(COPILOT_TWICE);+ });++ it('--agent claude writes CLAUDE.md and removes a block from .claude/CLAUDE.md', () => {+ setupCorePackage(tmpDir);+ fs.writeFileSync(path.join(tmpDir, 'CLAUDE.md'), '# Claude\n');+ fs.mkdirSync(path.join(tmpDir, '.claude'));+ fs.writeFileSync(+ path.join(tmpDir, '.claude', 'CLAUDE.md'),+ '# Local\n\n<!-- ASTRYX:START -->\nAstryx v1.0.0 · old\n<!-- ASTRYX:END -->\n',+ );+ installAgentDocs(tmpDir);++ expect(installAgentDocs(tmpDir, {agent: 'claude'})).toEqual(['CLAUDE.md']);+ expect(installAgentDocs(tmpDir, {agent: 'all'})).toEqual(['AGENTS.md', 'CLAUDE.md']);+ fs.writeFileSync(+ path.join(tmpDir, '.claude', 'CLAUDE.md'),+ '# Local\n\n<!-- ASTRYX:START -->\nAstryx v1.0.0 · old\n<!-- ASTRYX:END -->\n',+ );+ expect(installAgentDocs(tmpDir, {agent: 'claude'})).toEqual(['CLAUDE.md', '.claude/CLAUDE.md']);+ expect(fs.readFileSync(path.join(tmpDir, '.claude', 'CLAUDE.md'), 'utf-8')).toBe(+ '# Local\n',+ );+ expect(blocksSeen(tmpDir).claude).toBe(1);});it('respects --agent claude preset: finds existing CLAUDE.md', () => {@@ -879,6 +1198,39 @@ describe('installAgentDocs', () => {expect(content).toContain('Other rules.');});+ it('onlyReplace: refreshes both copies of the block and leaves the GEMINI.md import alone', () => {+ setupCorePackage(tmpDir, '1.0.0');+ fs.writeFileSync(path.join(tmpDir, 'CLAUDE.md'), '# Claude\n');+ installAgentDocs(tmpDir);+ setupCorePackage(tmpDir, '2.0.0');++ expect(installAgentDocs(tmpDir, {onlyReplace: true})).toEqual([+ 'AGENTS.md',+ 'CLAUDE.md',+ ]);+ for (const rel of ['AGENTS.md', 'CLAUDE.md']) {+ const content = fs.readFileSync(path.join(tmpDir, rel), 'utf-8');+ expect(content).toContain('Astryx v2.0.0');+ expect(content).not.toContain('Astryx v1.0.0');+ }+ expect(fs.readFileSync(path.join(tmpDir, 'GEMINI.md'), 'utf-8')).toBe(GEMINI_IMPORT);+ expect(blocksSeen(tmpDir)).toEqual(COPILOT_TWICE);+ });++ it('onlyReplace: refreshes a block beside an import of a missing AGENTS.md', () => {+ setupCorePackage(tmpDir, '2.0.0');+ fs.writeFileSync(+ path.join(tmpDir, 'CLAUDE.md'),+ '@AGENTS.md\n\n<!-- ASTRYX:START -->\nAstryx v1.0.0\n<!-- ASTRYX:END -->\n',+ );++ expect(installAgentDocs(tmpDir, {onlyReplace: true})).toEqual(['CLAUDE.md']);+ expect(fs.readFileSync(path.join(tmpDir, 'CLAUDE.md'), 'utf-8')).toContain(+ 'Astryx v2.0.0',+ );+ expect(fs.existsSync(path.join(tmpDir, 'AGENTS.md'))).toBe(false);+ });+it('onlyReplace: does not create the default AGENTS.md when nothing exists', () => {setupCorePackage(tmpDir);@@ -1084,6 +1436,25 @@ describe('inspectAgentDocs', () => {expect(res.staleFiles).toEqual(['CLAUDE.md']);});+ it('checks both copies of the block and does not count the GEMINI.md import', () => {+ const core = path.join(tmpDir, 'node_modules', '@astryxdesign', 'core');+ fs.mkdirSync(core, {recursive: true});+ fs.writeFileSync(path.join(core, 'package.json'), JSON.stringify({version: '3.0.0'}));+ fs.writeFileSync(path.join(tmpDir, 'CLAUDE.md'), '# Claude\n');+ installAgentDocs(tmpDir);++ const current = inspectAgentDocs(tmpDir, '3.0.0');+ expect(current.status).toBe('current');+ expect(current.files.map(f => f.path)).toEqual(['AGENTS.md', 'CLAUDE.md']);+ expect(inspectAgentDocs(tmpDir, '4.0.0').staleFiles).toEqual(['AGENTS.md', 'CLAUDE.md']);++ // Without the blocks, the import alone reads as not set up.+ fs.rmSync(path.join(tmpDir, 'AGENTS.md'));+ fs.rmSync(path.join(tmpDir, 'CLAUDE.md'));+ expect(inspectAgentDocs(tmpDir, '3.0.0').status).toBe('missing');+ expect(isAstryxInitialized(tmpDir)).toBe(false);+ });+it('defaults the installed version to the core package when omitted', () => {const coreDir = path.join(tmpDir, 'node_modules', '@astryxdesign', 'core');fs.mkdirSync(coreDir, {recursive: true});@@ -1179,3 +1550,275 @@ describe('isAstryxInitialized — resilient to malformed markers (postinstall hoexpect(isAstryxInitialized(path.join(tmpDir, 'does-not-exist'))).toBe(false);});});++describe('removeAgentDocs after the default layout', () => {+ beforeEach(() => {+ vi.spyOn(console, 'log').mockImplementation(() => {});+ });++ it('deletes the files the default created and keeps the project files', () => {+ const core = path.join(tmpDir, 'node_modules', '@astryxdesign', 'core');+ fs.mkdirSync(core, {recursive: true});+ fs.writeFileSync(path.join(core, 'package.json'), JSON.stringify({version: '1.0.0'}));+ fs.writeFileSync(path.join(tmpDir, 'CLAUDE.md'), '# Claude\n');+ installAgentDocs(tmpDir);++ expect(removeAgentDocs(tmpDir)).toEqual(['AGENTS.md', 'CLAUDE.md', 'GEMINI.md']);+ expect(fs.existsSync(path.join(tmpDir, 'AGENTS.md'))).toBe(false);+ expect(fs.existsSync(path.join(tmpDir, 'GEMINI.md'))).toBe(false);+ expect(fs.readFileSync(path.join(tmpDir, 'CLAUDE.md'), 'utf-8')).toBe('# Claude\n');+ });++ it('keeps a GEMINI.md that has the project\'s own content', () => {+ fs.writeFileSync(+ path.join(tmpDir, 'GEMINI.md'),+ `# Gemini\n\nUse tabs.\n\n${GEMINI_IMPORT}`,+ );++ expect(removeAgentDocs(tmpDir)).toEqual(['GEMINI.md']);+ expect(fs.readFileSync(path.join(tmpDir, 'GEMINI.md'), 'utf-8')).toBe(+ '# Gemini\n\nUse tabs.\n',+ );+ });+});++describe('agent docs never go into the home folder', () => {+ const saved = {HOME: process.env.HOME, USERPROFILE: process.env.USERPROFILE};+ const personal = '# My notes\n\nAlways use tabs.\n';++ beforeEach(() => {+ process.env.HOME = tmpDir;+ process.env.USERPROFILE = tmpDir;+ fs.mkdirSync(path.join(tmpDir, '.claude'), {recursive: true});+ fs.writeFileSync(path.join(tmpDir, '.claude', 'CLAUDE.md'), personal);+ });+ afterEach(() => {+ for (const [key, value] of Object.entries(saved)) {+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ }+ });++ it.each([+ ['the default', {}],+ ['a preset', {agent: 'claude'}],+ ['an explicit path', {paths: ['AGENTS.md']}],+ ['a refresh', {onlyReplace: true}],+ ])('refuses %s and writes nothing', (_label, options) => {+ expect(() => installAgentDocs(tmpDir, options)).toThrow(AgentDocsHomeError);+ expect(fs.readFileSync(path.join(tmpDir, '.claude', 'CLAUDE.md'), 'utf-8')).toBe(+ personal,+ );+ expect(fs.readdirSync(tmpDir).sort()).toEqual(['.claude']);+ });++ it('writes an explicit path into a plain folder of the home folder, as 0.7.x did', () => {+ expect(installAgentDocs(tmpDir, {paths: ['notes/AI.md']})).toEqual(['notes/AI.md']);+ expect(fs.readFileSync(path.join(tmpDir, 'notes', 'AI.md'), 'utf-8')).toContain(+ '<!-- ASTRYX:START -->',+ );+ });++ it.each([+ ['a file in the home folder', ['AI.md']],+ ['a file at the top of a settings folder', ['.claude/CLAUDE.md']],+ ['one of several paths', ['notes/AI.md', 'AI.md']],+ ])('refuses an explicit path to %s, and writes nothing', (_label, paths) => {+ expect(() => installAgentDocs(tmpDir, {paths})).toThrow(AgentDocsHomeError);+ expect(fs.readFileSync(path.join(tmpDir, '.claude', 'CLAUDE.md'), 'utf-8')).toBe(+ personal,+ );+ expect(fs.readdirSync(tmpDir).sort()).toEqual(['.claude']);+ });++ it('init with an explicit path from the home folder writes it, and refuses one in the home folder', async () => {+ const {init} = await import('../../api/init/init.mjs');+ const written = await init(+ {features: ['agents'], agentDocsPath: 'notes/AI.md'},+ {cwd: tmpDir},+ );+ expect(written.data.docsWritten).toEqual(['notes/AI.md']);+ expect(written.data.docsError ?? null).toBeNull();+ const refused = await init(+ {features: ['agents'], agentDocsPath: 'AI.md'},+ {cwd: tmpDir},+ );+ expect(refused.data.docsError).toMatchObject({kind: 'install-failed'});+ expect(fs.existsSync(path.join(tmpDir, 'AI.md'))).toBe(false);+ });++ it('refuses through a symlink to the home folder', () => {+ const link = `${tmpDir}-link`;+ fs.symlinkSync(tmpDir, link);+ try {+ expect(() => installAgentDocs(link)).toThrow(AgentDocsHomeError);+ } finally {+ fs.rmSync(link);+ }+ });++ it('still removes a block an older run wrote there', () => {+ vi.spyOn(console, 'log').mockImplementation(() => {});+ fs.writeFileSync(+ path.join(tmpDir, '.claude', 'CLAUDE.md'),+ `${personal}\n<!-- ASTRYX:START -->\nAstryx v1.0.0\n<!-- ASTRYX:END -->\n`,+ );++ expect(removeAgentDocs(tmpDir)).toEqual(['.claude/CLAUDE.md']);+ expect(fs.readFileSync(path.join(tmpDir, '.claude', 'CLAUDE.md'), 'utf-8')).toBe(+ personal,+ );+ });++ it.each(['.gemini', '.claude', '.codex', path.join('.gemini', 'extensions', 'x')])(+ 'refuses the settings folder ~/%s',+ folder => {+ const dir = path.join(tmpDir, folder);+ fs.mkdirSync(dir, {recursive: true});+ const before = fs.readdirSync(dir);+ expect(() => installAgentDocs(dir)).toThrow(AgentDocsHomeError);+ expect(fs.readdirSync(dir)).toEqual(before);+ expect(fs.readFileSync(path.join(tmpDir, '.claude', 'CLAUDE.md'), 'utf-8')).toBe(+ personal,+ );+ },+ );++ it('writes in a project folder inside the home folder', () => {+ const project = path.join(tmpDir, 'app');+ fs.mkdirSync(project);+ expect(installAgentDocs(project)).toEqual(['AGENTS.md', 'GEMINI.md']);+ });++ /**+ * A git project that declares Astryx, at `rel` under the home folder, with+ * Core installed at `version`.+ * @param {string} rel+ * @param {string} version+ */+ function writeProject(rel, version) {+ const project = path.join(tmpDir, rel);+ fs.mkdirSync(path.join(project, 'src'), {recursive: true});+ fs.writeFileSync(path.join(project, '.git'), 'gitdir: /elsewhere/.git/worktrees/web\n');+ fs.writeFileSync(+ path.join(project, 'package.json'),+ JSON.stringify({name: 'web', dependencies: {'@astryxdesign/core': version}}),+ );+ const core = path.join(project, 'node_modules', '@astryxdesign', 'core');+ fs.mkdirSync(core, {recursive: true});+ fs.writeFileSync(path.join(core, 'package.json'), JSON.stringify({version}));+ return project;+ }++ it.each([+ ['a Codex worktree', path.join('.codex', 'worktrees', 'a1b2c3', 'web')],+ ['a Cursor worktree', path.join('.cursor', 'worktrees', 'web', 'x9y8')],+ ['a project with its package.json one level in', path.join('.config', 'web')],+ ])('writes and refreshes the docs of a project inside a settings folder (%s)', (_label, rel) => {+ const project = writeProject(rel, '1.0.0');++ expect(resolveAgentDocsRoot(path.join(project, 'src'))).toBe(project);+ expect(installAgentDocs(project)).toEqual(['AGENTS.md', 'GEMINI.md']);++ // upgrade refreshes the block in place.+ writeProject(rel, '2.0.0');+ expect(installAgentDocs(project, {onlyReplace: true})).toEqual(['AGENTS.md']);+ expect(fs.readFileSync(path.join(project, 'AGENTS.md'), 'utf-8')).toContain(+ 'Astryx v2.0.0',+ );++ // Nothing reaches the settings folder or the home folder.+ const settings = path.join(tmpDir, rel.split(path.sep)[0]);+ expect(fs.readdirSync(settings)).toEqual([rel.split(path.sep)[1]]);+ expect(fs.readFileSync(path.join(tmpDir, '.claude', 'CLAUDE.md'), 'utf-8')).toBe(+ personal,+ );+ });++ it('refuses the top of a settings folder even with a package.json, and the folders in it outside a project', () => {+ // A package.json in ~/.claude (for hook scripts, say) would otherwise put the+ // block in ~/.claude/CLAUDE.md, which Claude Code reads in every project.+ fs.writeFileSync(path.join(tmpDir, '.claude', 'package.json'), '{"name":"hooks"}\n');+ fs.mkdirSync(path.join(tmpDir, '.claude', 'hooks'));++ expect(() => installAgentDocs(path.join(tmpDir, '.claude'))).toThrow(AgentDocsHomeError);+ expect(() => installAgentDocs(path.join(tmpDir, '.claude', 'hooks'))).toThrow(+ AgentDocsHomeError,+ );+ expect(resolveAgentDocsRoot(path.join(tmpDir, '.claude', 'hooks'))).toBe(+ path.join(tmpDir, '.claude'),+ );+ expect(fs.readFileSync(path.join(tmpDir, '.claude', 'CLAUDE.md'), 'utf-8')).toBe(+ personal,+ );++ // A worktree folder whose project has no package.json is not a project.+ const bare = path.join(tmpDir, '.codex', 'worktrees', 'a1b2c3', 'notes');+ fs.mkdirSync(bare, {recursive: true});+ expect(() => installAgentDocs(bare)).toThrow(AgentDocsHomeError);+ expect(fs.readdirSync(bare)).toEqual([]);+ });+});++describe('resolveAgentDocsRoot', () => {+ /** @param {string} dir @param {object} pkg */+ const writePkg = (dir, pkg) => {+ fs.mkdirSync(dir, {recursive: true});+ fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify(pkg));+ };+ const astryx = {devDependencies: {'@astryxdesign/cli': '0.7.0'}};++ it('finds the nearest folder whose package.json declares Astryx', () => {+ writePkg(tmpDir, astryx);+ const sub = path.join(tmpDir, 'src', 'app');+ fs.mkdirSync(sub, {recursive: true});+ expect(resolveAgentDocsRoot(sub)).toBe(tmpDir);+ expect(resolveAgentDocsRoot(tmpDir)).toBe(tmpDir);++ // A nested package that does not declare Astryx is passed over.+ const functions = path.join(tmpDir, 'functions');+ writePkg(functions, {name: 'functions'});+ fs.mkdirSync(path.join(functions, 'src'));+ expect(resolveAgentDocsRoot(path.join(functions, 'src'))).toBe(tmpDir);++ // A nested package that declares Astryx is its own project.+ const web = path.join(tmpDir, 'apps', 'web');+ writePkg(web, {dependencies: {'@astryxdesign/core': '0.7.0'}});+ expect(resolveAgentDocsRoot(web)).toBe(web);+ });++ it('falls back to the nearest package.json when none declares Astryx', () => {+ writePkg(tmpDir, {name: 'app'});+ const pkg = path.join(tmpDir, 'packages', 'web');+ writePkg(pkg, {name: 'web'});+ fs.mkdirSync(path.join(pkg, 'src'));+ expect(resolveAgentDocsRoot(path.join(pkg, 'src'))).toBe(pkg);+ });++ it('stops at a repository root, and finds no project without a package.json', () => {+ writePkg(tmpDir, astryx);+ const repo = path.join(tmpDir, 'repo');+ fs.mkdirSync(path.join(repo, '.git'), {recursive: true});+ const sub = path.join(repo, 'docs');+ fs.mkdirSync(sub);+ expect(resolveAgentDocsRoot(sub)).toBeNull();+ });++ it('never returns the home folder', () => {+ const saved = {HOME: process.env.HOME, USERPROFILE: process.env.USERPROFILE};+ process.env.HOME = tmpDir;+ process.env.USERPROFILE = tmpDir;+ try {+ writePkg(tmpDir, astryx);+ const scratch = path.join(tmpDir, 'scratch');+ fs.mkdirSync(scratch);+ expect(resolveAgentDocsRoot(scratch)).toBeNull();+ expect(resolveAgentDocsRoot(tmpDir)).toBeNull();+ } finally {+ for (const [key, value] of Object.entries(saved)) {+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ }+ }+ });+});diff --git a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs b/packages/cli/foundation/doc-compiler/doc-loads.test.mjsindex 29c9df7c84..f32d1c89d9 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/agent-docs/agent-docs.mjs': {+ runs: 'git, sl or hg, to read whether the repository ignores an untracked agent file',+ sites: ['child_process.spawnSync'],+ },'foundation/fs/file-protection.mjs': {runs: 'the ignore matcher (CommonJS), loaded when a resolver first reads an ignore file',sites: ['require(ignore)'],diff --git a/packages/core/scripts/agent-doc-state.mjs b/packages/core/scripts/agent-doc-state.mjsindex cd07f69dfd..e4eccd5b0d 100644--- a/packages/core/scripts/agent-doc-state.mjs+++ b/packages/core/scripts/agent-doc-state.mjs@@ -39,6 +39,7 @@ import * as path from 'node:path';export const AGENTS_MD = 'AGENTS.md';export const CLAUDE_MD = 'CLAUDE.md';export const CLAUDE_DIR_MD = '.claude/CLAUDE.md'; // cross-platform literal+export const GEMINI_MD = 'GEMINI.md';export const CURSOR_RULES = '.cursorrules';export const HERMES_DOT_MD = '.hermes.md';export const HERMES_MD = 'HERMES.md';@@ -51,15 +52,18 @@ export const LEGACY_MARKER_END = '<!-- XDS:END -->';/*** The canonical set of EVERY location an --agent preset (or the default) can- * write the Astryx block. SINGLE SOURCE OF TRUTH: discovery, removal, and the- * `isAstryxInitialized` predicate all derive from this list, so "where init- * writes" and "where we look" can never drift. (Explicit --agent-docs-path- * targets are user-chosen and not enumerable here.)+ * write a managed Astryx block — the full block, or the one-line import of+ * AGENTS.md that the default writes to GEMINI.md. SINGLE+ * SOURCE OF TRUTH: discovery, removal, and the `isAstryxInitialized` predicate+ * all derive from this list, so "where init writes" and "where we look" can+ * never drift. (Explicit --agent-docs-path targets are user-chosen and not+ * enumerable here.)*/export const AGENT_DOC_PATHS = [AGENTS_MD, // Codex / ChatGPT / Muse / genericCLAUDE_MD, // Claude Code (root)CLAUDE_DIR_MD, // Claude Code (.claude/CLAUDE.md)+ GEMINI_MD, // Gemini CLICURSOR_RULES, // CursorHERMES_DOT_MD, // HermesHERMES_MD, // Hermes@@ -74,7 +78,7 @@ export const INIT_MARKERS = [MARKER_START, LEGACY_MARKER_START];/*** Find all existing agent doc files in a directory, across EVERY location any* preset can write (see {@link AGENT_DOC_PATHS}: AGENTS.md, CLAUDE.md,- * .claude/CLAUDE.md, .cursorrules, .hermes.md, HERMES.md).+ * .claude/CLAUDE.md, GEMINI.md, .cursorrules, .hermes.md, HERMES.md).* @param {string} targetDir* @returns {string[]} Relative paths of existing agent doc files*/@@ -82,10 +86,33 @@ export function discoverAgentDocs(targetDir) {return AGENT_DOC_PATHS.filter(p => fs.existsSync(path.join(targetDir, p)));}+/**+ * Whether `content` holds an Astryx block. A managed block that only imports+ * another file (the one-line `@./AGENTS.md` that init writes to GEMINI.md) does+ * not count: it holds nothing once that file has lost its block. A malformed+ * block still counts, so a half-written file reads as set up.+ *+ * @param {string} content+ * @returns {boolean}+ */+export function holdsAstryxBlock(content) {+ for (const marker of INIT_MARKERS) {+ let at = content.indexOf(marker);+ while (at !== -1) {+ const from = at + marker.length;+ const end = content.indexOf('<!--', from);+ const inner = (end === -1 ? content.slice(from) : content.slice(from, end)).trim();+ if (!/^@\S+$/.test(inner)) return true;+ at = content.indexOf(marker, from);+ }+ }+ return false;+}+/*** Single source of truth for "is Astryx set up in this project?" — true when any- * agent-doc file already carries the Astryx marker, i.e. `init` / `agent-docs`- * has run. Reused by the init & upgrade commands, the per-command setup nudge+ * agent-doc file already holds an Astryx block, i.e. `init` / `agent-docs` has+ * run. Reused by the init & upgrade commands, the per-command setup nudge* (enforcement layer 3), and the cli postinstall nudge (layer 2). Core's* postinstall (separate package, layer 1) mirrors the same marker contract.*@@ -96,7 +123,7 @@ export function isAstryxInitialized(targetDir = process.cwd()) {for (const rel of discoverAgentDocs(targetDir)) {try {const content = fs.readFileSync(path.join(targetDir, rel), 'utf-8');- if (INIT_MARKERS.some(m => content.includes(m))) {+ if (holdsAstryxBlock(content)) {return true;}} catch {