@astryxdesign/cli 0.7.3-canary.b1e1936 → 0.7.3-canary.b74cf21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -28,7 +28,15 @@ import * as fs from 'node:fs';
28
28
  import * as path from 'node:path';
29
29
 
30
30
  import {MIN_NODE_VERSION, isNodeVersionSupported} from '../../foundation/env/node-version.mjs';
31
- import {AGENT_DOC_PATHS} from '../../foundation/agent-docs/agent-doc-state.mjs';
31
+ import {
32
+ AGENT_DOC_PATHS,
33
+ holdsAstryxBlock,
34
+ } from '../../foundation/agent-docs/agent-doc-state.mjs';
35
+ import {
36
+ agentDocsTargetDir,
37
+ assertAgentDocsTarget,
38
+ resolveAgentDocsRoot,
39
+ } from '../../foundation/agent-docs/agent-docs.mjs';
32
40
  import {CLI_ROOT, findProjectCoreDir, findInstalledPackage} from '../../foundation/fs/paths.mjs';
33
41
  import {explainPackageManager, formatCliCommand, getCliInvocation, guessCliInvocation} from '../../foundation/env/package-manager.mjs';
34
42
  import {chooseDeclaredCliCommand, declaredCliCommandsOf} from '../../foundation/env/cli-command.mjs';
@@ -610,6 +618,21 @@ export function checkConfiguredIntegrations(ctx) {
610
618
  };
611
619
  }
612
620
 
621
+ /**
622
+ * Why init writes no agent docs for `cwd`, or null when it does: the folder
623
+ * it would write to is the home folder or the top of a settings folder in it.
624
+ * @param {string} cwd
625
+ * @returns {string | null}
626
+ */
627
+ function agentDocsRefusal(cwd) {
628
+ try {
629
+ assertAgentDocsTarget(agentDocsTargetDir(cwd));
630
+ return null;
631
+ } catch (err) {
632
+ return err instanceof Error && err.name === 'AgentDocsHomeError' ? err.message : null;
633
+ }
634
+ }
635
+
613
636
  /**
614
637
  * Check 7 — agent docs exist and contain the Astryx section markers.
615
638
  * @param {DoctorContext} ctx
@@ -617,8 +640,15 @@ export function checkConfiguredIntegrations(ctx) {
617
640
  */
618
641
  export function checkAgentDocs(ctx) {
619
642
  // Every file init can write (one shared list), looked for in the working
620
- // directory and in the project root: run from src/, the docs sit at the root.
621
- const dirs = [...new Set([ctx.cwd, projectRootOf(ctx)])];
643
+ // directory, the project root, and the folder init writes them to: run from
644
+ // src/ or a nested package, the docs sit at the root.
645
+ const dirs = [
646
+ ...new Set(
647
+ [ctx.cwd, projectRootOf(ctx), resolveAgentDocsRoot(ctx.cwd) ?? ctx.cwd].map(dir =>
648
+ path.resolve(dir),
649
+ ),
650
+ ),
651
+ ];
622
652
  const present = dirs.flatMap(dir =>
623
653
  AGENT_DOC_PATHS.map(rel => path.join(dir, rel)).filter(abs =>
624
654
  fs.existsSync(abs),
@@ -626,6 +656,15 @@ export function checkAgentDocs(ctx) {
626
656
  );
627
657
  /** @param {string} abs */
628
658
  const shown = abs => path.relative(ctx.cwd, abs) || path.basename(abs);
659
+ // In the home folder, or at the top of a settings folder in it, init
660
+ // writes no agent docs (INV31), so the fix is moving the project or a hand
661
+ // edit, never init.
662
+ const refusal = agentDocsRefusal(ctx.cwd);
663
+ /** @param {string} initFix */
664
+ const fixFor = initFix =>
665
+ refusal
666
+ ? `${refusal} Move the project into a folder of its own, or edit the Astryx block in its agent file by hand.`
667
+ : initFix;
629
668
 
630
669
  if (present.length === 0) {
631
670
  return {
@@ -633,29 +672,64 @@ export function checkAgentDocs(ctx) {
633
672
  label: 'AI agent docs',
634
673
  status: 'info',
635
674
  message: `No agent docs found: looked for ${AGENT_DOC_PATHS.join(', ')} in ${dirs.map(dir => path.relative(ctx.cwd, dir) || '.').join(' and ')}.`,
636
- fix: `Generate agent docs with \`${getCliInvocation(ctx.cwd)} init --features agents\`.`,
675
+ fix: fixFor(
676
+ `Generate agent docs with \`${getCliInvocation(ctx.cwd)} init --features agents\`.`,
677
+ ),
637
678
  };
638
679
  }
639
680
 
640
- const withMarkers = present.filter(abs => {
681
+ /** @param {string} abs */
682
+ const read = abs => {
641
683
  try {
642
- const content = fs.readFileSync(abs, 'utf-8');
643
- return (
644
- (content.includes('<!-- ASTRYX:START -->') || content.includes('<!-- XDS:START -->')) &&
645
- (content.includes('<!-- ASTRYX:END -->') || content.includes('<!-- XDS:END -->'))
646
- );
684
+ return fs.readFileSync(abs, 'utf-8');
647
685
  } catch {
648
- return false;
686
+ return '';
649
687
  }
688
+ };
689
+ const withMarkers = present.filter(abs => {
690
+ const content = read(abs);
691
+ return (
692
+ (content.includes('<!-- ASTRYX:START -->') || content.includes('<!-- XDS:START -->')) &&
693
+ (content.includes('<!-- ASTRYX:END -->') || content.includes('<!-- XDS:END -->')) &&
694
+ holdsAstryxBlock(content)
695
+ );
650
696
  });
651
697
 
698
+ // A managed block that only imports another file (init's GEMINI.md import
699
+ // of AGENTS.md) is broken when that file holds no block: the agents that
700
+ // read either file get no Astryx docs.
701
+ const dangling = present.flatMap(abs => {
702
+ const match = /<!-- ASTRYX:START -->\s*@(\S+)\s*<!-- ASTRYX:END -->/.exec(read(abs));
703
+ if (match == null) return [];
704
+ const target = path.resolve(path.dirname(abs), match[1]);
705
+ return holdsAstryxBlock(read(target)) ? [] : [{abs, target}];
706
+ });
707
+ if (dangling.length > 0) {
708
+ return {
709
+ id: 'agent-docs',
710
+ label: 'AI agent docs',
711
+ status: 'fail',
712
+ message: dangling
713
+ .map(
714
+ ({abs, target}) =>
715
+ `${shown(abs)} imports ${shown(target)}, which holds no Astryx block, so agents that read them get no Astryx docs.`,
716
+ )
717
+ .join(' '),
718
+ fix: fixFor(
719
+ `Write the block again with \`${getCliInvocation(ctx.cwd)} init --features agents\`.`,
720
+ ),
721
+ };
722
+ }
723
+
652
724
  if (withMarkers.length === 0) {
653
725
  return {
654
726
  id: 'agent-docs',
655
727
  label: 'AI agent docs',
656
728
  status: 'warn',
657
729
  message: `Agent docs present (${present.map(shown).join(', ')}) but no Astryx section markers found.`,
658
- fix: `Add the Astryx section to your agent docs with \`${getCliInvocation(ctx.cwd)} init --features agents\`.`,
730
+ fix: fixFor(
731
+ `Add the Astryx section to your agent docs with \`${getCliInvocation(ctx.cwd)} init --features agents\`.`,
732
+ ),
659
733
  };
660
734
  }
661
735
 
@@ -17,11 +17,22 @@ export const doc = {
17
17
  'Non-interactive project setup: install agent docs and point at the theme + build workflows.',
18
18
  description:
19
19
  'Sets a project up with NO prompts, so it behaves identically for humans, ' +
20
- 'agents, CI, and piped I/O. By default it installs the AGENTS.md/CLAUDE.md ' +
21
- 'agent-docs cheat sheet, including guidance from configured integrations, and ' +
20
+ 'agents, CI, and piped I/O. By default it writes the agent-docs cheat sheet, ' +
21
+ 'including guidance from configured integrations, at the project root (the nearest ' +
22
+ 'package.json that declares an @astryxdesign package, else the nearest package.json, ' +
23
+ 'searching no higher than the repository root): to AGENTS.md, ' +
24
+ "to the project's Claude Code file (CLAUDE.md, else .claude/CLAUDE.md; when CLAUDE.md " +
25
+ 'exists, a block in .claude/CLAUDE.md is removed, unless the project ignores CLAUDE.md, in which case a ' +
26
+ '.claude/CLAUDE.md the project commits keeps a copy), and as a ' +
27
+ 'one-line import of AGENTS.md in GEMINI.md unless GEMINI.md already imports it. ' +
28
+ 'In the home folder, or in a settings folder in it outside a project, it writes none: every ' +
29
+ 'folder of the home folder whose name starts with a dot is a settings folder, and such a folder itself never ' +
30
+ 'counts as a project, even with a package.json; a folder below it with a package.json does. ' +
31
+ 'The managed block is Astryx-owned: it is written, refreshed, and removed whatever ignore rules ' +
32
+ 'or generated markers say, and the text around it is never changed. It then ' +
22
33
  "prints getting-started guidance; `features` / `all` print only the chosen features' " +
23
34
  'guidance instead (the theme feature also writes the annotated theme template). ' +
24
- 'With `removeAgents` it removes the managed agent-docs block instead of installing. ' +
35
+ 'With `removeAgents` it removes the managed agent-docs block, at the project root and in `ctx.cwd`, instead of installing. ' +
25
36
  '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. ' +
26
37
  "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. " +
27
38
  '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 = {
46
57
  name: 'options.removeAgents',
47
58
  type: 'boolean',
48
59
  description:
49
- 'Remove the managed agent-docs block instead of installing. With `user`, remove the computer-level agent text instead.',
60
+ '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.',
50
61
  },
51
62
  {
52
63
  name: 'options.user',
@@ -62,7 +73,10 @@ export const doc = {
62
73
  name: 'options.agent',
63
74
  type: 'string',
64
75
  description:
65
- 'Agent preset: claude, cursor, codex, hermes, muse, all. Used only when the agents feature runs. Refused with `user`.',
76
+ 'Agent preset: claude, cursor, codex, hermes, muse, all. `all` writes every existing agent doc except GEMINI.md, ' +
77
+ 'which keeps its one-line import of AGENTS.md. With claude and all, when CLAUDE.md gets the block, a block in ' +
78
+ '.claude/CLAUDE.md is removed, unless the project ignores CLAUDE.md, in which case a .claude/CLAUDE.md the ' +
79
+ 'project commits gets a copy too. Used only when the agents feature runs. Refused with `user`.',
66
80
  },
67
81
  {
68
82
  name: 'options.agentDocsPath',
@@ -122,7 +136,7 @@ export const doc = {
122
136
  },
123
137
  {
124
138
  code: 'ERR_PATH_TRAVERSAL',
125
- 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',
139
+ 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)',
126
140
  },
127
141
  ],
128
142
  examples: [
@@ -10,6 +10,7 @@
10
10
 
11
11
  import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
12
12
  import * as fs from 'node:fs';
13
+ import * as os from 'node:os';
13
14
  import * as path from 'node:path';
14
15
  import {init, getNextSteps} from './init.mjs';
15
16
  import {logger} from '../logger.mjs';
@@ -21,7 +22,8 @@ const MARKER_START = '<!-- ASTRYX:START -->';
21
22
  let tmpDir;
22
23
 
23
24
  beforeEach(() => {
24
- tmpDir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-init-api-'));
25
+ // Outside any package: init writes agent docs at the nearest package.json.
26
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-init-api-'));
25
27
  });
26
28
 
27
29
  afterEach(() => {
@@ -30,6 +32,18 @@ afterEach(() => {
30
32
 
31
33
  /** @param {string} rel */
32
34
  const read = rel => fs.readFileSync(path.join(tmpDir, rel), 'utf8');
35
+
36
+ /**
37
+ * Make tmpDir a project that declares Astryx: a folder that declares nothing
38
+ * is outside a project, where init prints no getting-started steps (spec
39
+ * AST-081 FR3).
40
+ */
41
+ function asProject() {
42
+ fs.writeFileSync(
43
+ path.join(tmpDir, 'package.json'),
44
+ JSON.stringify({name: 'app', dependencies: {'@astryxdesign/core': '*'}}),
45
+ );
46
+ }
33
47
  /** @param {string} rel */
34
48
  const exists = rel => fs.existsSync(path.join(tmpDir, rel));
35
49
 
@@ -58,6 +72,7 @@ function writeIntegration() {
58
72
 
59
73
  describe('init() — receipts + side effects', () => {
60
74
  it('default mode installs AGENTS.md and returns an init.run receipt', async () => {
75
+ asProject();
61
76
  const res = await init({}, {cwd: tmpDir});
62
77
  expect(res.type).toBe('init.run');
63
78
  if (res.type !== 'init.run') return;
@@ -217,6 +232,7 @@ describe('init() — logger', () => {
217
232
  });
218
233
 
219
234
  it('emits the install line + full next-steps through the shared logger', async () => {
235
+ asProject();
220
236
  /** @type {string[]} */
221
237
  const lines = [];
222
238
  const logSpy = vi.spyOn(console, 'log').mockImplementation((...a) => lines.push(a.join(' ')));
@@ -243,7 +259,7 @@ describe('init() — ASCII output', () => {
243
259
  const lines = [];
244
260
  const logSpy = vi.spyOn(console, 'log').mockImplementation((...a) => lines.push(a.join(' ')));
245
261
  const errSpy = vi.spyOn(console, 'error').mockImplementation((...a) => lines.push(a.join(' ')));
246
- const empty = fs.mkdtempSync(path.join(process.cwd(), '.astryx-init-remove-'));
262
+ const empty = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-init-remove-'));
247
263
  logger.setSilent(false);
248
264
  try {
249
265
  await init({}, {cwd: tmpDir});
@@ -11,11 +11,11 @@ export type InitRunData = {
11
11
  */
12
12
  features: string[];
13
13
  /**
14
- * Agent-doc files written (empty if agents weren't run or install failed).
14
+ * 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.
15
15
  */
16
16
  docsWritten: string[];
17
17
  /**
18
- * Soft agent-docs failure, if any. `path-safety` also implies a non-zero exit.
18
+ * 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.
19
19
  */
20
20
  docsError: {
21
21
  kind: "path-safety" | "install-failed";
@@ -113,7 +113,7 @@ export type InitOptions = {
113
113
  */
114
114
  all?: boolean | undefined;
115
115
  /**
116
- * Remove the managed agent-docs block instead of installing; with `user`, remove the computer-level agent text.
116
+ * 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.
117
117
  */
118
118
  removeAgents?: boolean | undefined;
119
119
  /**
@@ -10,8 +10,8 @@
10
10
  * @typedef {object} InitRunData
11
11
  * @property {'default' | 'features'} mode `default` (no flags) or `features` (--features/--all).
12
12
  * @property {string[]} features Features that were run, in order.
13
- * @property {string[]} docsWritten Agent-doc files written (empty if agents weren't run or install failed).
14
- * @property {{kind: 'path-safety' | 'install-failed', message?: string} | null} docsError Soft agent-docs failure, if any. `path-safety` also implies a non-zero exit.
13
+ * @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.
14
+ * @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.
15
15
  * @property {boolean} theme Whether the theme feature ran.
16
16
  * @property {'created' | 'skipped' | 'failed' | null} themeTemplate Outcome of writing the annotated theme template (`skipped` = a file was already there).
17
17
  * @property {string | null} themeTemplatePath Relative output path when `themeTemplate === 'created'`.
@@ -70,7 +70,7 @@
70
70
  * @typedef {object} InitOptions
71
71
  * @property {string} [features] Comma-separated features to install (agents, theme, template).
72
72
  * @property {boolean} [all] Install all features.
73
- * @property {boolean} [removeAgents] Remove the managed agent-docs block instead of installing; with `user`, remove the computer-level agent text.
73
+ * @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.
74
74
  * @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.
75
75
  * @property {string} [agent] Agent preset: claude, cursor, codex, hermes, muse, all. Refused with `user`.
76
76
  * @property {string | string[]} [agentDocsPath] Explicit agent-docs file path(s).
@@ -4,15 +4,16 @@
4
4
  * @file init.remove leaf — the `--remove-agents` path behind `astryx init`.
5
5
  *
6
6
  * `remove(ctx)` deletes the managed agent-docs block from every agent-doc file
7
- * and returns an `init.remove` receipt. The removal engine lives in
8
- * lib/agent-docs; this leaf only wires the cwd.
7
+ * at the project root, where init writes it, and in the working folder, and
8
+ * returns an `init.remove` receipt. The removal engine lives in
9
+ * foundation/agent-docs; this leaf only wires the cwd.
9
10
  *
10
11
  * Note: removeAgentDocs() still logs its own per-file lines via humanLog
11
12
  * (shared lib behavior) — so a programmatic remove is not perfectly silent yet.
12
13
  * Threading a logger through agent-docs is a separate cleanup.
13
14
  */
14
15
 
15
- import {removeAgentDocs} from '../../../foundation/agent-docs/agent-docs.mjs';
16
+ import {removeProjectAgentDocs} from '../../../foundation/agent-docs/agent-docs.mjs';
16
17
  import {logger} from '../../logger.mjs';
17
18
 
18
19
  /**
@@ -23,7 +24,19 @@ import {logger} from '../../logger.mjs';
23
24
  * @returns {Promise<import('../init.type.mjs').InitRemoveResponse>}
24
25
  */
25
26
  export async function remove({cwd = process.cwd()} = {}) {
26
- const removedFrom = removeAgentDocs(cwd);
27
+ /** @type {string[]} */
28
+ const skipped = [];
29
+ const removedFrom = removeProjectAgentDocs(cwd, {
30
+ onSkipped: (rel, reason) => skipped.push(`${rel} (${reason})`),
31
+ });
32
+ if (skipped.length > 0) {
33
+ // Below the project root, as install does there (0.7.x touched only the
34
+ // working folder): a root agent file outside the project is left alone.
35
+ logger.warn(
36
+ `Note: Left as ${skipped.length === 1 ? 'it is' : 'they are'}: ${skipped.join('; ')}. ` +
37
+ 'To remove the Astryx block there, delete it by hand.',
38
+ );
39
+ }
27
40
  const removed = removedFrom.length > 0;
28
41
  logger.log(
29
42
  removed
@@ -1,12 +1,124 @@
1
1
  // Copyright (c) Meta Platforms, Inc. and affiliates.
2
2
  import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
3
- import * as fs from 'node:fs'; import * as path from 'node:path';
3
+ import * as fs from 'node:fs'; import * as path from 'node:path'; import * as os from 'node:os';
4
4
  import {init} from '../init.mjs'; import {remove} from './remove.mjs'; import {logger} from '../../logger.mjs';
5
5
  let dir;
6
- 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'})); });
6
+ 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'})); });
7
7
  afterEach(() => { fs.rmSync(dir,{recursive:true,force:true}); logger.setSilent(true); });
8
8
  describe('init.remove says whether anything was removed', () => {
9
9
  it('false on clean', async () => { const r=await remove({cwd:dir}); expect(r.type).toBe('init.remove'); expect(r.data.removed).toBe(false); });
10
10
  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); });
11
11
  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'); });
12
12
  });
13
+
14
+ describe('init.remove acts where init writes, the project root, and in the folder it runs in', () => {
15
+ /** @type {string} */
16
+ let project;
17
+ beforeEach(() => {
18
+ project = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-rm-root-'));
19
+ fs.writeFileSync(
20
+ path.join(project, 'package.json'),
21
+ JSON.stringify({name: 'app', dependencies: {'@astryxdesign/core': '1.0.0'}}),
22
+ );
23
+ fs.mkdirSync(path.join(project, 'src', 'app'), {recursive: true});
24
+ });
25
+ afterEach(() => { fs.rmSync(project, {recursive: true, force: true}); });
26
+ const block = '<!-- ASTRYX:START -->\nAstryx v0.7.0 · old\n<!-- ASTRYX:END -->\n';
27
+
28
+ it('removes from a subfolder what init wrote at the project root', async () => {
29
+ const sub = path.join(project, 'src', 'app');
30
+ const written = await init({features: ['agents']}, {cwd: sub});
31
+ expect(written.data.docsWritten).toEqual(['../../AGENTS.md', '../../GEMINI.md']);
32
+
33
+ const r = await remove({cwd: sub});
34
+ expect(r).toEqual({type: 'init.remove', data: {removed: true}});
35
+ // Both files held only what init wrote, so they are deleted.
36
+ expect(fs.existsSync(path.join(project, 'AGENTS.md'))).toBe(false);
37
+ expect(fs.existsSync(path.join(project, 'GEMINI.md'))).toBe(false);
38
+ expect((await remove({cwd: sub})).data.removed).toBe(false);
39
+ });
40
+
41
+ it('removes a block an earlier version left in the subfolder, and keeps the files\' own text', async () => {
42
+ const sub = path.join(project, 'src', 'app');
43
+ fs.writeFileSync(path.join(project, 'AGENTS.md'), `# Agents\n\nRoot rules.\n\n${block}`);
44
+ fs.writeFileSync(path.join(sub, 'AGENTS.md'), `# App\n\nApp rules.\n\n${block}`);
45
+
46
+ expect((await remove({cwd: sub})).data.removed).toBe(true);
47
+ expect(fs.readFileSync(path.join(project, 'AGENTS.md'), 'utf8').trimEnd()).toBe('# Agents\n\nRoot rules.');
48
+ expect(fs.readFileSync(path.join(sub, 'AGENTS.md'), 'utf8').trimEnd()).toBe('# App\n\nApp rules.');
49
+ });
50
+
51
+ it('run at the project root, leaves a subfolder alone', async () => {
52
+ const sub = path.join(project, 'src', 'app');
53
+ fs.writeFileSync(path.join(project, 'AGENTS.md'), `# Agents\n\n${block}`);
54
+ fs.writeFileSync(path.join(sub, 'AGENTS.md'), `# App\n\n${block}`);
55
+
56
+ expect((await remove({cwd: project})).data.removed).toBe(true);
57
+ expect(fs.readFileSync(path.join(sub, 'AGENTS.md'), 'utf8')).toContain('<!-- ASTRYX:START -->');
58
+ });
59
+
60
+ 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 () => {
61
+ // A workspace member whose CLAUDE.md links to the monorepo's.
62
+ const monorepo = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-rm-mono-'));
63
+ try {
64
+ const web = path.join(monorepo, 'apps', 'web');
65
+ const sub = path.join(web, 'src');
66
+ fs.mkdirSync(sub, {recursive: true});
67
+ fs.writeFileSync(
68
+ path.join(web, 'package.json'),
69
+ JSON.stringify({name: 'web', dependencies: {'@astryxdesign/core': '1.0.0'}}),
70
+ );
71
+ fs.writeFileSync(path.join(monorepo, 'CLAUDE.md'), `# Shared\n\n${block}`);
72
+ fs.symlinkSync('../../CLAUDE.md', path.join(web, 'CLAUDE.md'));
73
+ fs.writeFileSync(path.join(web, 'AGENTS.md'), `# Web\n\n${block}`);
74
+ fs.writeFileSync(path.join(sub, 'AGENTS.md'), `# Src\n\n${block}`);
75
+ const warned = [];
76
+ const warn = vi.spyOn(console, 'error').mockImplementation((...a) => warned.push(a.join(' ')));
77
+ logger.setSilent(false);
78
+ let r;
79
+ try {
80
+ r = await remove({cwd: sub});
81
+ } finally {
82
+ logger.setSilent(true);
83
+ warn.mockRestore();
84
+ }
85
+ expect(r).toEqual({type: 'init.remove', data: {removed: true}});
86
+ expect(fs.readFileSync(path.join(web, 'AGENTS.md'), 'utf8').trimEnd()).toBe('# Web');
87
+ expect(fs.readFileSync(path.join(sub, 'AGENTS.md'), 'utf8').trimEnd()).toBe('# Src');
88
+ // The file outside the project keeps its block.
89
+ expect(fs.readFileSync(path.join(monorepo, 'CLAUDE.md'), 'utf8')).toContain('<!-- ASTRYX:START -->');
90
+ expect(warned.join('\n')).toMatch(/Note: Left as it is: \.\.\/CLAUDE\.md \(/u);
91
+ } finally {
92
+ fs.rmSync(monorepo, {recursive: true, force: true});
93
+ }
94
+ });
95
+
96
+ it('at the root, a root agent file linked outside the project still refuses the run', async () => {
97
+ const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-rm-outside-'));
98
+ try {
99
+ fs.writeFileSync(path.join(outside, 'CLAUDE.md'), `# Shared\n\n${block}`);
100
+ fs.symlinkSync(path.join(outside, 'CLAUDE.md'), path.join(project, 'CLAUDE.md'));
101
+ fs.writeFileSync(path.join(project, 'AGENTS.md'), `# Agents\n\n${block}`);
102
+ await expect(remove({cwd: project})).rejects.toMatchObject({code: 'ERR_PATH_TRAVERSAL'});
103
+ expect(fs.readFileSync(path.join(project, 'AGENTS.md'), 'utf8')).toContain('<!-- ASTRYX:START -->');
104
+ } finally {
105
+ fs.rmSync(outside, {recursive: true, force: true});
106
+ }
107
+ });
108
+
109
+ it('a link in the subfolder that escapes it refuses the run before anything is written', async () => {
110
+ const sub = path.join(project, 'src', 'app');
111
+ const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-rm-outside-'));
112
+ try {
113
+ fs.writeFileSync(path.join(project, 'AGENTS.md'), `# Agents\n\n${block}`);
114
+ fs.writeFileSync(path.join(outside, 'CLAUDE.md'), `# Shared\n\n${block}`);
115
+ fs.symlinkSync(path.join(outside, 'CLAUDE.md'), path.join(sub, 'CLAUDE.md'));
116
+
117
+ await expect(remove({cwd: sub})).rejects.toMatchObject({code: 'ERR_PATH_TRAVERSAL'});
118
+ expect(fs.readFileSync(path.join(project, 'AGENTS.md'), 'utf8')).toContain('<!-- ASTRYX:START -->');
119
+ expect(fs.readFileSync(path.join(outside, 'CLAUDE.md'), 'utf8')).toContain('<!-- ASTRYX:START -->');
120
+ } finally {
121
+ fs.rmSync(outside, {recursive: true, force: true});
122
+ }
123
+ });
124
+ });
@@ -4,10 +4,12 @@
4
4
  * @file init.run leaf — non-interactive project setup + feature installer.
5
5
  *
6
6
  * `run(options, ctx)` is the default / `--features` / `--all` path behind
7
- * `astryx init`. It installs the AGENTS.md/CLAUDE.md agent-docs cheat sheet,
8
- * points at the theme + page-building workflows, and (optionally) scaffolds a
9
- * starter template — with NO prompts, so it behaves identically for humans,
10
- * agents, CI, and piped I/O. It performs the side effects and returns an
7
+ * `astryx init`. It installs the agent-docs cheat sheet at the project root so
8
+ * every agent reads it (AGENTS.md, a copy in the project's Claude Code file, and
9
+ * a GEMINI.md import), points at the theme + page-building workflows, and
10
+ * (optionally) scaffolds a starter template — with NO prompts, so it behaves
11
+ * identically for humans, agents, CI, and piped I/O. It performs the side
12
+ * effects and returns an
11
13
  * `init.run` receipt. Hard errors (unknown feature/template) throw AstryxError
12
14
  * with a stable code. Human output is emitted through the shared `logger`
13
15
  * (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.
21
23
  import {getCliInvocation} from '../../../foundation/env/package-manager.mjs';
22
24
  import {isOutsideProject} from '../../../foundation/env/project-scope.mjs';
23
25
  import {
26
+ AgentDocsHomeError,
27
+ assertAgentDocsTarget,
24
28
  installAgentDocs,
25
29
  renderAgentDocsBlock,
30
+ agentDocsTargetDir,
26
31
  } from '../../../foundation/agent-docs/agent-docs.mjs';
27
32
  import {themeTemplate} from '../../theme/template/template.mjs';
28
33
  import {listTemplates} from '../../template/template.mjs';
@@ -64,6 +69,24 @@ export function getNextSteps(invocation) {
64
69
  ];
65
70
  }
66
71
 
72
+ /**
73
+ * Whether two paths name one folder, links resolved.
74
+ * @param {string} a
75
+ * @param {string} b
76
+ * @returns {boolean}
77
+ */
78
+ function sameFolder(a, b) {
79
+ /** @param {string} p */
80
+ const real = p => {
81
+ try {
82
+ return fs.realpathSync(p);
83
+ } catch {
84
+ return path.resolve(p);
85
+ }
86
+ };
87
+ return real(a) === real(b);
88
+ }
89
+
67
90
  /**
68
91
  * Install the agent-docs block; records the outcome (or soft error) on `data`.
69
92
  * Mirrors the CLI's historical soft-error policy: a PathSafetyError surfaces its
@@ -92,14 +115,46 @@ async function applyAgents(cwd, options, invocation, data) {
92
115
  ? options.agentDocsPath
93
116
  : [options.agentDocsPath]
94
117
  : undefined;
95
- const renderedBlock = await renderAgentDocsBlock(cwd);
96
- const written = installAgentDocs(cwd, {
118
+ // The docs belong at the project root, not in the subfolder init ran in;
119
+ // with no project above, they go where init ran, as before. Explicit
120
+ // --agent-docs-path entries stay relative to where init ran.
121
+ const root = agentDocsTargetDir(cwd);
122
+ const targetDir = paths ? cwd : root;
123
+ // With explicit paths, installAgentDocs checks each file's own folder.
124
+ if (!paths) assertAgentDocsTarget(targetDir);
125
+ const renderedBlock = await renderAgentDocsBlock(root);
126
+ /** @type {string[]} */
127
+ const skipped = [];
128
+ const files = installAgentDocs(targetDir, {
97
129
  agent: options.agent,
98
130
  paths,
99
131
  renderedBlock,
132
+ onSkipped: (rel, reason) => skipped.push(`${rel} (${reason})`),
133
+ // Below the project root, 0.7.1 wrote in the folder init ran in, so a
134
+ // project-root file that escapes the project is skipped and reported,
135
+ // not refused.
136
+ refuseEscapes: sameFolder(targetDir, cwd),
100
137
  });
138
+ // Each file is reported from where init ran, as before.
139
+ const written =
140
+ path.resolve(targetDir) === path.resolve(cwd)
141
+ ? files
142
+ : files.map(rel =>
143
+ path.relative(cwd, path.join(targetDir, rel)).split(path.sep).join('/'),
144
+ );
101
145
  data.docsWritten = written;
102
146
  logger.log(`[ok] AI agent docs installed -> ${written.join(', ')}`);
147
+ // A file 0.7.1 did not write (GEMINI.md, or a project-root file when init
148
+ // runs below the root) that resolves outside the project is left as it
149
+ // is, reported in docsError with one note; the exit code stays 0. A file
150
+ // 0.7.1 wrote whose path escapes the project still fails the run (below).
151
+ if (skipped.length > 0) {
152
+ const message =
153
+ `Left as ${skipped.length === 1 ? 'it is' : 'they are'}: ${skipped.join('; ')}. ` +
154
+ '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.';
155
+ logger.warn(`Note: ${message}`);
156
+ data.docsError = {kind: 'install-failed', message};
157
+ }
103
158
  } catch (err) {
104
159
  // PathSafetyError carries a precise, user-actionable message — surface it
105
160
  // (and flag exit 1) instead of the generic "could not install" warning so
@@ -109,6 +164,14 @@ async function applyAgents(cwd, options, invocation, data) {
109
164
  data.docsError = {kind: 'path-safety', message: err.message};
110
165
  return;
111
166
  }
167
+ // The home folder, and a settings folder in it outside a project, are
168
+ // refused: nothing is written, the reason is printed as a note, and the
169
+ // exit code stays 0.
170
+ if (err instanceof AgentDocsHomeError) {
171
+ logger.warn(`Note: ${err.message}`);
172
+ data.docsError = {kind: 'install-failed', message: err.message};
173
+ return;
174
+ }
112
175
  logger.error(
113
176
  `Could not install agent docs. Try again with \`${invocation} init --features agents\`.`,
114
177
  );
@@ -51,6 +51,7 @@ const PACKED_DIRS = ['clients', 'api', 'assets', 'authoring', 'foundation'];
51
51
  const RUNTIME_DEPS = [
52
52
  '@babel/parser',
53
53
  'commander',
54
+ 'ignore',
54
55
  'jiti',
55
56
  'jscodeshift',
56
57
  'zod',
@@ -84,12 +84,6 @@ export function runPostCodemodHooks(hooks: import("../../authoring/config/type")
84
84
  files: string[];
85
85
  apply: boolean;
86
86
  }): Promise<void>;
87
- /**
88
- * @typedef {object} AgentDocsRefreshPlan
89
- * @property {string} cwd
90
- * @property {string|null} renderedBlock
91
- * @property {import('./upgrade.type.mjs').AgentDocsSummary} summary
92
- */
93
87
  /**
94
88
  * Compute the expected managed block and report staleness without writing.
95
89
  * Apply-mode callers commit the prepared bytes only after codemods and hooks