@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.
@@ -30,6 +30,8 @@ import {
30
30
  } from '../../assets/codemods/integration-discovery.mjs';
31
31
  import {runIntegrationCodemods} from '../../assets/codemods/integration-runner.mjs';
32
32
  import {
33
+ AgentDocsHomeError,
34
+ assertAgentDocsTarget,
33
35
  installAgentDocs,
34
36
  inspectAgentDocs,
35
37
  renderAgentDocsBlock,
@@ -286,6 +288,21 @@ export async function runPostCodemodHooks(hooks, context) {
286
288
  * @property {import('./upgrade.type.mjs').AgentDocsSummary} summary
287
289
  */
288
290
 
291
+ /**
292
+ * Why upgrade leaves the agent docs of a project at the home folder or the
293
+ * top of a settings folder, and what to do instead. init refuses the same
294
+ * folder, so the line never points at it.
295
+ * @param {AgentDocsHomeError} err
296
+ * @param {'stale' | 'missing'} [state] whether a block is there to refresh
297
+ * @returns {string}
298
+ */
299
+ function homeRefusalLine(err, state = 'stale') {
300
+ const where = `${err.dir} is the home folder or a settings folder in it, which every project's agents read.`;
301
+ return state === 'missing'
302
+ ? `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.`
303
+ : `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.`;
304
+ }
305
+
289
306
  /**
290
307
  * Compute the expected managed block and report staleness without writing.
291
308
  * Apply-mode callers commit the prepared bytes only after codemods and hooks
@@ -312,6 +329,16 @@ export async function prepareAgentDocsRefresh({
312
329
  };
313
330
 
314
331
  if (initial.status === 'missing') {
332
+ // init writes nothing in a project at the home folder or the top of a
333
+ // settings folder, so it is not the remedy there (INV31).
334
+ try {
335
+ assertAgentDocsTarget(cwd);
336
+ } catch (err) {
337
+ if (!(err instanceof AgentDocsHomeError)) throw err;
338
+ summary.action = 'error';
339
+ logger.warn(homeRefusalLine(err, 'missing'));
340
+ return {cwd, renderedBlock: null, summary};
341
+ }
315
342
  summary.action = 'nudge-init';
316
343
  logger.warn(
317
344
  `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({
340
367
  summary.files = inspection.staleFiles;
341
368
  if (inspection.status === 'current') return {cwd, renderedBlock, summary};
342
369
 
370
+ // A project at the home folder or the top of a settings folder is never
371
+ // refreshed (INV31): the dry run says so, as --apply does, rather than
372
+ // offering a refresh that would be refused.
373
+ try {
374
+ assertAgentDocsTarget(cwd);
375
+ } catch (err) {
376
+ if (!(err instanceof AgentDocsHomeError)) throw err;
377
+ summary.action = 'error';
378
+ logger.warn(homeRefusalLine(err));
379
+ return {cwd, renderedBlock: null, summary};
380
+ }
381
+
343
382
  summary.action = 'would-refresh';
344
383
  if (!apply) {
345
384
  logger.warn(
@@ -363,6 +402,9 @@ export function applyAgentDocsRefresh(plan) {
363
402
  const written = installAgentDocs(cwd, {
364
403
  onlyReplace: true,
365
404
  renderedBlock,
405
+ // A GEMINI.md that resolves outside the project is left as it is.
406
+ onSkipped: (file, reason) =>
407
+ logger.warn(`Note: ${file} left as it is (${reason}).`),
366
408
  });
367
409
  summary.refreshed = written.length > 0;
368
410
  summary.files = written;
@@ -374,12 +416,18 @@ export function applyAgentDocsRefresh(plan) {
374
416
  `Agent docs look stale but couldn't be refreshed. Run \`${formatCliCommand('astryx init --features agents')}\` to reinstall the block.`,
375
417
  );
376
418
  }
377
- } catch {
419
+ } catch (err) {
378
420
  summary.action = 'error';
379
421
  summary.refreshed = false;
380
- logger.warn(
381
- `Could not refresh agent docs. Run \`${formatCliCommand('astryx init --features agents')}\` to update them manually.`,
382
- );
422
+ if (err instanceof AgentDocsHomeError) {
423
+ // init refuses this folder too, so pointing at it would loop: say why,
424
+ // and what to do instead.
425
+ logger.warn(homeRefusalLine(err));
426
+ } else {
427
+ logger.warn(
428
+ `Could not refresh agent docs. Run \`${formatCliCommand('astryx init --features agents')}\` to update them manually.`,
429
+ );
430
+ }
383
431
  }
384
432
  return summary;
385
433
  }
@@ -246,6 +246,200 @@ describe('upgrade() — receipts', () => {
246
246
  expect(content).not.toMatch(/Astryx v0\.0\.1 ·/);
247
247
  });
248
248
 
249
+ it('leaves the block of a project at the top of a home settings folder, saying why and not pointing at init', async () => {
250
+ const saved = {
251
+ HOME: process.env.HOME,
252
+ USERPROFILE: process.env.USERPROFILE,
253
+ };
254
+ process.env.HOME = tmpDir;
255
+ process.env.USERPROFILE = tmpDir;
256
+ const warned = [];
257
+ const warn = vi
258
+ .spyOn(console, 'error')
259
+ .mockImplementation((...a) => warned.push(a.join(' ')));
260
+ logger.setSilent(false);
261
+ try {
262
+ const project = path.join(tmpDir, '.dotfiles');
263
+ fs.mkdirSync(project, {recursive: true});
264
+ writePkg(project, {'@astryxdesign/core': '0.0.15'});
265
+ writeInstalledCore(project, '0.0.15');
266
+ writeAgentBlock(project, 'AGENTS.md', '0.0.1');
267
+
268
+ const res = await upgrade({from: '0.0.15', apply: true}, {cwd: project});
269
+
270
+ expect(res.data.agentDocs.action).toBe('error');
271
+ expect(res.data.agentDocs.refreshed).toBe(false);
272
+ expect(fs.readFileSync(path.join(project, 'AGENTS.md'), 'utf-8')).toMatch(
273
+ /Astryx v0\.0\.1 ·/,
274
+ );
275
+ const text = warned.join('\n');
276
+ expect(text).toContain(
277
+ `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.`,
278
+ );
279
+ expect(text).not.toContain('init --features agents');
280
+ } finally {
281
+ logger.setSilent(true);
282
+ warn.mockRestore();
283
+ for (const [key, value] of Object.entries(saved)) {
284
+ if (value === undefined) delete process.env[key];
285
+ else process.env[key] = value;
286
+ }
287
+ }
288
+ });
289
+
290
+ it('with no block, in a project at the top of a home settings folder, says why instead of pointing at init', async () => {
291
+ const saved = {
292
+ HOME: process.env.HOME,
293
+ USERPROFILE: process.env.USERPROFILE,
294
+ };
295
+ process.env.HOME = tmpDir;
296
+ process.env.USERPROFILE = tmpDir;
297
+ const warned = [];
298
+ const warn = vi
299
+ .spyOn(console, 'error')
300
+ .mockImplementation((...a) => warned.push(a.join(' ')));
301
+ logger.setSilent(false);
302
+ try {
303
+ const project = path.join(tmpDir, '.dotfiles');
304
+ fs.mkdirSync(project, {recursive: true});
305
+ writePkg(project, {'@astryxdesign/core': '0.0.15'});
306
+ writeInstalledCore(project, '0.0.15');
307
+
308
+ const res = await upgrade({from: '0.0.15'}, {cwd: project});
309
+
310
+ expect(res.data.agentDocs.action).toBe('error');
311
+ const text = warned.join('\n');
312
+ expect(text).toContain(
313
+ `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.`,
314
+ );
315
+ expect(text).not.toContain('init --features agents');
316
+ } finally {
317
+ logger.setSilent(true);
318
+ warn.mockRestore();
319
+ for (const [key, value] of Object.entries(saved)) {
320
+ if (value === undefined) delete process.env[key];
321
+ else process.env[key] = value;
322
+ }
323
+ }
324
+ });
325
+
326
+ it('a dry run in a project at the top of a home settings folder reports the refusal, not a refresh to apply', async () => {
327
+ const saved = {
328
+ HOME: process.env.HOME,
329
+ USERPROFILE: process.env.USERPROFILE,
330
+ };
331
+ process.env.HOME = tmpDir;
332
+ process.env.USERPROFILE = tmpDir;
333
+ const warned = [];
334
+ const warn = vi
335
+ .spyOn(console, 'error')
336
+ .mockImplementation((...a) => warned.push(a.join(' ')));
337
+ logger.setSilent(false);
338
+ try {
339
+ const project = path.join(tmpDir, '.dotfiles');
340
+ fs.mkdirSync(project, {recursive: true});
341
+ writePkg(project, {'@astryxdesign/core': '0.0.15'});
342
+ writeInstalledCore(project, '0.0.15');
343
+ writeAgentBlock(project, 'AGENTS.md', '0.0.1');
344
+
345
+ const res = await upgrade({from: '0.0.15'}, {cwd: project});
346
+
347
+ expect(res.data.agentDocs.action).toBe('error');
348
+ expect(res.data.agentDocs.refreshed).toBe(false);
349
+ const text = warned.join('\n');
350
+ expect(text).toContain(
351
+ `Agent docs not refreshed: ${fs.realpathSync(project)} is the home folder or a settings folder in it`,
352
+ );
353
+ expect(text).not.toContain('--apply to refresh');
354
+ expect(text).not.toContain('init --features agents');
355
+ } finally {
356
+ logger.setSilent(true);
357
+ warn.mockRestore();
358
+ for (const [key, value] of Object.entries(saved)) {
359
+ if (value === undefined) delete process.env[key];
360
+ else process.env[key] = value;
361
+ }
362
+ }
363
+ });
364
+
365
+ it('refreshes the agent docs of a project in an agent worktree inside a home settings folder', async () => {
366
+ const saved = {
367
+ HOME: process.env.HOME,
368
+ USERPROFILE: process.env.USERPROFILE,
369
+ };
370
+ process.env.HOME = tmpDir;
371
+ process.env.USERPROFILE = tmpDir;
372
+ try {
373
+ const project = path.join(tmpDir, '.codex', 'worktrees', 'a1b2c3', 'web');
374
+ fs.mkdirSync(project, {recursive: true});
375
+ writePkg(project, {'@astryxdesign/core': '0.0.15'});
376
+ writeInstalledCore(project, '0.0.15');
377
+ writeAgentBlock(project, 'AGENTS.md', '0.0.1');
378
+
379
+ const res = await upgrade({from: '0.0.15', apply: true}, {cwd: project});
380
+
381
+ expect(res.data.agentDocs.action).toBe('refreshed');
382
+ expect(fs.readFileSync(path.join(project, 'AGENTS.md'), 'utf-8')).toMatch(
383
+ /Astryx v0\.0\.15 ·/,
384
+ );
385
+ } finally {
386
+ for (const [key, value] of Object.entries(saved)) {
387
+ if (value === undefined) delete process.env[key];
388
+ else process.env[key] = value;
389
+ }
390
+ }
391
+ });
392
+
393
+ it('refreshes the managed block in an ignored .claude/CLAUDE.md and keeps the text around it (INV31)', async () => {
394
+ writePkg(tmpDir);
395
+ writeInstalledCore(tmpDir, '0.0.15');
396
+ writeAgentBlock(tmpDir, 'AGENTS.md', '0.0.1');
397
+ fs.mkdirSync(path.join(tmpDir, '.claude'));
398
+ writeAgentBlock(tmpDir, '.claude/CLAUDE.md', '0.0.1');
399
+ const claude = path.join(tmpDir, '.claude', 'CLAUDE.md');
400
+ fs.writeFileSync(
401
+ claude,
402
+ `# Team notes\n\n${fs.readFileSync(claude, 'utf-8')}\nMore notes.\n`,
403
+ );
404
+ fs.writeFileSync(path.join(tmpDir, '.gitignore'), '.claude/\n');
405
+
406
+ const res = await upgrade({from: '0.0.15', apply: true}, {cwd: tmpDir});
407
+
408
+ expect(res.data.agentDocs.action).toBe('refreshed');
409
+ expect(res.data.agentDocs.files).toEqual([
410
+ 'AGENTS.md',
411
+ '.claude/CLAUDE.md',
412
+ ]);
413
+ expect(res.data.agentDocs).not.toHaveProperty('protectedFiles');
414
+ const content = fs.readFileSync(claude, 'utf-8');
415
+ expect(content).toMatch(/^# Team notes\n/u);
416
+ expect(content).toMatch(/Astryx v0\.0\.15 ·/u);
417
+ expect(content).toMatch(/More notes\.\n$/u);
418
+ });
419
+
420
+ it('refreshes a committed .claude/CLAUDE.md that imports AGENTS.md and keeps a copy beside an ignored root CLAUDE.md', async () => {
421
+ writePkg(tmpDir);
422
+ writeInstalledCore(tmpDir, '0.0.15');
423
+ writeAgentBlock(tmpDir, 'AGENTS.md', '0.0.1');
424
+ writeAgentBlock(tmpDir, 'CLAUDE.md', '0.0.1');
425
+ fs.writeFileSync(path.join(tmpDir, '.gitignore'), '/CLAUDE.md\n');
426
+ fs.mkdirSync(path.join(tmpDir, '.claude'));
427
+ const copy = path.join(tmpDir, '.claude', 'CLAUDE.md');
428
+ fs.writeFileSync(
429
+ copy,
430
+ `@../AGENTS.md\n\n${generateCompressedIndex('0.0.1')}\n`,
431
+ );
432
+
433
+ for (let round = 0; round < 2; round++) {
434
+ await upgrade({from: '0.0.15', apply: true}, {cwd: tmpDir});
435
+ const content = fs.readFileSync(copy, 'utf-8');
436
+ expect(content, `round ${round}`).toMatch(/^@\.\.\/AGENTS\.md\n/u);
437
+ expect(content, `round ${round}`).toMatch(/Astryx v0\.0\.15 ·/u);
438
+ }
439
+ const dry = await upgrade({from: '0.0.15'}, {cwd: tmpDir});
440
+ expect(dry.data.agentDocs.status).toBe('current');
441
+ });
442
+
249
443
  it('reports would-refresh on a dry run without writing (honors cwd)', async () => {
250
444
  writePkg(tmpDir);
251
445
  writeInstalledCore(tmpDir, '0.0.15');
@@ -44,7 +44,7 @@ export const docs = {
44
44
  },
45
45
  {
46
46
  type: 'prose',
47
- text: "By default this creates `AGENTS.md` (the tool-agnostic standard most agents read). To target a specific tool's file instead:",
47
+ 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:",
48
48
  },
49
49
  {
50
50
  type: 'code',
@@ -55,7 +55,11 @@ astryx init --features agents --agent cursor # .cursorrules if present, else
55
55
  astryx init --features agents --agent codex # AGENTS.md (Copilot, Codex, etc.)
56
56
  astryx init --features agents --agent hermes # .hermes.md or HERMES.md if present, else AGENTS.md
57
57
  astryx init --features agents --agent muse # AGENTS.md (Muse)
58
- astryx init --features agents --agent all # every agent file present, else AGENTS.md and .claude/CLAUDE.md`,
58
+ astryx init --features agents --agent all # every agent file present except GEMINI.md, else AGENTS.md and .claude/CLAUDE.md`,
59
+ },
60
+ {
61
+ type: 'prose',
62
+ 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.',
59
63
  },
60
64
  {
61
65
  type: 'prose',
@@ -191,6 +191,31 @@ describe('doctor — individual checks', () => {
191
191
  expect(res.fix).toContain('`npx astryx init --features agents`');
192
192
  });
193
193
 
194
+ it('agent-docs: at the top of a home settings folder, the fix moves the project or edits by hand, never init', () => {
195
+ const saved = {HOME: process.env.HOME, USERPROFILE: process.env.USERPROFILE};
196
+ process.env.HOME = tmpDir;
197
+ process.env.USERPROFILE = tmpDir;
198
+ try {
199
+ const project = path.join(tmpDir, '.dotfiles');
200
+ fs.mkdirSync(project);
201
+ fs.writeFileSync(path.join(project, 'package.json'), '{"name":"dots"}');
202
+ for (const content of [null, '# Agents\nno markers here\n']) {
203
+ if (content != null) fs.writeFileSync(path.join(project, 'AGENTS.md'), content);
204
+ const res = checkAgentDocs({cwd: project});
205
+ expect(res.fix).toContain('Agent docs are not written into the home folder');
206
+ expect(res.fix).toContain(
207
+ 'Move the project into a folder of its own, or edit the Astryx block in its agent file by hand.',
208
+ );
209
+ expect(res.fix).not.toContain('init --features agents');
210
+ }
211
+ } finally {
212
+ for (const [key, value] of Object.entries(saved)) {
213
+ if (value === undefined) delete process.env[key];
214
+ else process.env[key] = value;
215
+ }
216
+ }
217
+ });
218
+
194
219
  it('agent-docs: WARN when docs exist without XDS markers', () => {
195
220
  fs.writeFileSync(path.join(tmpDir, 'AGENTS.md'), '# AGENTS\nno markers here');
196
221
  const res = checkAgentDocs({cwd: tmpDir});
@@ -221,6 +246,25 @@ describe('doctor — individual checks', () => {
221
246
  );
222
247
  });
223
248
 
249
+ it('agent-docs: PASS from a nested package, reading the root that declares Astryx', () => {
250
+ fs.writeFileSync(
251
+ path.join(tmpDir, 'package.json'),
252
+ JSON.stringify({dependencies: {'@astryxdesign/core': '0.7.0'}}),
253
+ );
254
+ fs.writeFileSync(
255
+ path.join(tmpDir, 'AGENTS.md'),
256
+ '<!-- ASTRYX:START -->\nstuff\n<!-- ASTRYX:END -->\n',
257
+ );
258
+ const functions = path.join(tmpDir, 'functions');
259
+ fs.mkdirSync(path.join(functions, 'src'), {recursive: true});
260
+ fs.writeFileSync(path.join(functions, 'package.json'), '{"name":"functions"}');
261
+
262
+ expect(checkAgentDocs({cwd: path.join(functions, 'src')})).toMatchObject({
263
+ status: 'pass',
264
+ message: `Astryx agent docs section present in ${path.join('..', '..', 'AGENTS.md')}.`,
265
+ });
266
+ });
267
+
224
268
  it('agent-docs: reads every file init can write, Hermes included', () => {
225
269
  fs.writeFileSync(
226
270
  path.join(tmpDir, 'HERMES.md'),
@@ -232,6 +276,27 @@ describe('doctor — individual checks', () => {
232
276
  });
233
277
  });
234
278
 
279
+ it('agent-docs: FAIL when GEMINI.md imports an AGENTS.md that holds no block', () => {
280
+ const geminiImport = '<!-- ASTRYX:START -->\n@./AGENTS.md\n<!-- ASTRYX:END -->\n';
281
+ fs.writeFileSync(path.join(tmpDir, 'GEMINI.md'), geminiImport);
282
+ expect(checkAgentDocs({cwd: tmpDir})).toMatchObject({
283
+ status: 'fail',
284
+ message: expect.stringMatching(/^GEMINI\.md imports AGENTS\.md, which holds no Astryx block/),
285
+ fix: expect.stringMatching(/init --features agents/),
286
+ });
287
+
288
+ // A copy elsewhere does not mend it: Codex and Gemini CLI still get none.
289
+ fs.writeFileSync(path.join(tmpDir, 'CLAUDE.md'), '<!-- ASTRYX:START -->\nstuff\n<!-- ASTRYX:END -->\n');
290
+ fs.writeFileSync(path.join(tmpDir, 'AGENTS.md'), '# Agents\n');
291
+ expect(checkAgentDocs({cwd: tmpDir}).status).toBe('fail');
292
+
293
+ fs.writeFileSync(path.join(tmpDir, 'AGENTS.md'), '<!-- ASTRYX:START -->\nstuff\n<!-- ASTRYX:END -->\n');
294
+ expect(checkAgentDocs({cwd: tmpDir})).toMatchObject({
295
+ status: 'pass',
296
+ message: 'Astryx agent docs section present in AGENTS.md, CLAUDE.md.',
297
+ });
298
+ });
299
+
235
300
  it('agent-docs: INFO names what it looked for and where', () => {
236
301
  const res = checkAgentDocs({cwd: tmpDir});
237
302
  expect(res.status).toBe('info');
@@ -70,10 +70,12 @@ describe('astryx init — default (no flags)', () => {
70
70
  });
71
71
 
72
72
  describe('astryx init --features', () => {
73
- it('--features agents writes AGENTS.md only', async () => {
73
+ it('--features agents writes AGENTS.md and the GEMINI.md import of it', async () => {
74
74
  const {status} = await runCli(['init', '--features', 'agents'], {cwd: tmpDir});
75
75
  expect(status).toBe(0);
76
76
  expect(exists('AGENTS.md')).toBe(true);
77
+ expect(read('GEMINI.md')).toBe(`${MARKER_START}\n@./AGENTS.md\n<!-- ASTRYX:END -->\n`);
78
+ expect(exists('theme.template.ts')).toBe(false);
77
79
  });
78
80
 
79
81
  it('--features theme writes the annotated theme template', async () => {
@@ -126,7 +128,234 @@ describe('astryx init --agent <preset>', () => {
126
128
  });
127
129
  });
128
130
 
131
+ describe('astryx init from a subfolder', () => {
132
+ /** @param {string} dir */
133
+ const astryxProject = dir =>
134
+ fs.writeFileSync(
135
+ path.join(dir, 'package.json'),
136
+ JSON.stringify({name: 'app', dependencies: {'@astryxdesign/core': '0.7.0'}}),
137
+ );
138
+
139
+ it('writes the agent docs at the project root and reports them from where it ran', async () => {
140
+ astryxProject(tmpDir);
141
+ const sub = path.join(tmpDir, 'src', 'app');
142
+ fs.mkdirSync(sub, {recursive: true});
143
+
144
+ const json = await runCli(['init', '--json'], {cwd: sub});
145
+ expect(json.status).toBe(0);
146
+ expect(JSON.parse(json.stdout).data.docsWritten).toEqual([
147
+ '../../AGENTS.md',
148
+ '../../GEMINI.md',
149
+ ]);
150
+ expect(read('AGENTS.md')).toContain(MARKER_START);
151
+ expect(fs.readdirSync(sub)).toEqual([]);
152
+ });
153
+
154
+ it('keeps --agent-docs-path relative to where it ran', async () => {
155
+ astryxProject(tmpDir);
156
+ const sub = path.join(tmpDir, 'docs');
157
+ fs.mkdirSync(sub);
158
+
159
+ const json = await runCli(['init', '--agent-docs-path', 'AI.md', '--json'], {cwd: sub});
160
+ expect(JSON.parse(json.stdout).data.docsWritten).toEqual(['AI.md']);
161
+ expect(fs.readFileSync(path.join(sub, 'AI.md'), 'utf8')).toContain(MARKER_START);
162
+ expect(exists('AGENTS.md')).toBe(false);
163
+ });
164
+ });
165
+
166
+ describe('astryx init in the home folder', () => {
167
+ const saved = {HOME: process.env.HOME, USERPROFILE: process.env.USERPROFILE};
168
+ const personal = '# My notes\n\nAlways use tabs.\n';
169
+
170
+ beforeEach(() => {
171
+ process.env.HOME = tmpDir;
172
+ process.env.USERPROFILE = tmpDir;
173
+ fs.mkdirSync(path.join(tmpDir, '.claude'), {recursive: true});
174
+ fs.writeFileSync(path.join(tmpDir, '.claude', 'CLAUDE.md'), personal);
175
+ });
176
+ afterEach(() => {
177
+ for (const [key, value] of Object.entries(saved)) {
178
+ if (value === undefined) delete process.env[key];
179
+ else process.env[key] = value;
180
+ }
181
+ });
182
+
183
+ it('writes no agent docs, says why, and keeps the soft-failure exit code', async () => {
184
+ const json = await runCli(['init', '--json'], {cwd: tmpDir});
185
+ expect(json.status).toBe(0);
186
+ const env = JSON.parse(json.stdout);
187
+ expect(env.data.docsWritten).toEqual([]);
188
+ expect(env.data.docsError).toEqual({
189
+ kind: 'install-failed',
190
+ message: expect.stringMatching(/not written into the home folder/),
191
+ });
192
+
193
+ const text = await runCli(['init'], {cwd: tmpDir});
194
+ expect(text.status).toBe(0);
195
+ expect(text.stderr).toMatch(/not written into the home folder/);
196
+ expect(text.stderr).not.toMatch(/Error:/);
197
+
198
+ expect(read('.claude/CLAUDE.md')).toBe(personal);
199
+ expect(fs.readdirSync(tmpDir)).toEqual(['.claude']);
200
+ });
201
+
202
+ it('does not let a package.json in the home folder pull the docs there', async () => {
203
+ fs.writeFileSync(
204
+ path.join(tmpDir, 'package.json'),
205
+ JSON.stringify({dependencies: {'@astryxdesign/core': '0.7.0'}}),
206
+ );
207
+ const scratch = path.join(tmpDir, 'scratch');
208
+ fs.mkdirSync(scratch);
209
+
210
+ const json = await runCli(['init', '--json'], {cwd: scratch});
211
+ expect(json.status).toBe(0);
212
+ expect(JSON.parse(json.stdout).data.docsWritten).toEqual(['AGENTS.md', 'GEMINI.md']);
213
+ expect(fs.existsSync(path.join(scratch, 'AGENTS.md'))).toBe(true);
214
+ expect(exists('AGENTS.md')).toBe(false);
215
+ expect(read('.claude/CLAUDE.md')).toBe(personal);
216
+ });
217
+
218
+ it('--remove-agents in a folder in home never reaches the home folder', async () => {
219
+ fs.writeFileSync(
220
+ path.join(tmpDir, '.claude', 'CLAUDE.md'),
221
+ `${personal}\n<!-- ASTRYX:START -->\nAstryx v0.7.0\n<!-- ASTRYX:END -->\n`,
222
+ );
223
+ fs.writeFileSync(
224
+ path.join(tmpDir, 'package.json'),
225
+ JSON.stringify({dependencies: {'@astryxdesign/core': '0.7.0'}}),
226
+ );
227
+ const scratch = path.join(tmpDir, 'scratch');
228
+ fs.mkdirSync(scratch);
229
+
230
+ const json = await runCli(['init', '--remove-agents', '--json'], {cwd: scratch});
231
+ expect(JSON.parse(json.stdout).data.removed).toBe(false);
232
+ expect(read('.claude/CLAUDE.md')).toContain('<!-- ASTRYX:START -->');
233
+
234
+ // Run in the home folder itself, it still removes the block there.
235
+ const home = await runCli(['init', '--remove-agents', '--json'], {cwd: tmpDir});
236
+ expect(JSON.parse(home.stdout).data.removed).toBe(true);
237
+ expect(read('.claude/CLAUDE.md')).toBe(personal);
238
+ });
239
+
240
+ it.each(['.gemini', '.claude'])('refuses the settings folder ~/%s', async folder => {
241
+ const dir = path.join(tmpDir, folder);
242
+ fs.mkdirSync(dir, {recursive: true});
243
+ const before = fs.readdirSync(dir);
244
+
245
+ const json = await runCli(['init', '--json'], {cwd: dir});
246
+ expect(json.status).toBe(0);
247
+ const env = JSON.parse(json.stdout);
248
+ expect(env.data.docsWritten).toEqual([]);
249
+ expect(env.data.docsError.message).toMatch(/settings folder in it outside a project/);
250
+ expect(fs.readdirSync(dir)).toEqual(before);
251
+ expect(read('.claude/CLAUDE.md')).toBe(personal);
252
+ });
253
+ });
254
+
255
+ describe('astryx init in an agent worktree inside a home settings folder', () => {
256
+ const saved = {HOME: process.env.HOME, USERPROFILE: process.env.USERPROFILE};
257
+
258
+ beforeEach(() => {
259
+ process.env.HOME = tmpDir;
260
+ process.env.USERPROFILE = tmpDir;
261
+ });
262
+ afterEach(() => {
263
+ for (const [key, value] of Object.entries(saved)) {
264
+ if (value === undefined) delete process.env[key];
265
+ else process.env[key] = value;
266
+ }
267
+ });
268
+
269
+ it.each([
270
+ ['Codex', path.join('.codex', 'worktrees', 'a1b2c3', 'web')],
271
+ ['Cursor', path.join('.cursor', 'worktrees', 'web', 'x9y8')],
272
+ ])('writes at the project root of a %s worktree', async (_tool, rel) => {
273
+ const project = path.join(tmpDir, rel);
274
+ fs.mkdirSync(path.join(project, 'src'), {recursive: true});
275
+ fs.writeFileSync(path.join(project, '.git'), 'gitdir: /elsewhere/.git/worktrees/web\n');
276
+ fs.writeFileSync(
277
+ path.join(project, 'package.json'),
278
+ JSON.stringify({name: 'web', dependencies: {'@astryxdesign/core': '0.7.0'}}),
279
+ );
280
+
281
+ const json = await runCli(['init', '--json'], {cwd: path.join(project, 'src')});
282
+ expect(json.status).toBe(0);
283
+ const env = JSON.parse(json.stdout);
284
+ expect(env.data.docsWritten).toEqual(['../AGENTS.md', '../GEMINI.md']);
285
+ expect(env.data.docsError).toBeNull();
286
+
287
+ const explicit = await runCli(['init', '--agent-docs-path', 'AI.md', '--json'], {
288
+ cwd: path.join(project, 'src'),
289
+ });
290
+ expect(JSON.parse(explicit.stdout).data.docsWritten).toEqual(['AI.md']);
291
+
292
+ // Nothing reaches the settings folder itself.
293
+ const settings = path.join(tmpDir, rel.split(path.sep)[0]);
294
+ expect(fs.readdirSync(settings)).toEqual(['worktrees']);
295
+ });
296
+ });
297
+
298
+ describe('astryx init and the project root', () => {
299
+ it('writes where it runs when no folder above has a package.json, as before', async () => {
300
+ const notes = path.join(tmpDir, 'notes');
301
+ fs.mkdirSync(notes);
302
+
303
+ const json = await runCli(['init', '--json'], {cwd: notes});
304
+ expect(json.status).toBe(0);
305
+ const env = JSON.parse(json.stdout);
306
+ expect(env.data.docsWritten).toEqual(['AGENTS.md', 'GEMINI.md']);
307
+ expect(env.data.docsError).toBeNull();
308
+ expect(fs.readdirSync(notes).sort()).toEqual(['AGENTS.md', 'GEMINI.md']);
309
+ expect(fs.readdirSync(tmpDir)).toEqual(['notes']);
310
+ });
311
+
312
+ it('writes at the project root that declares Astryx, past a nested package that does not', async () => {
313
+ fs.writeFileSync(
314
+ path.join(tmpDir, 'package.json'),
315
+ JSON.stringify({name: 'app', dependencies: {'@astryxdesign/core': '0.7.0'}}),
316
+ );
317
+ const functions = path.join(tmpDir, 'functions');
318
+ fs.mkdirSync(path.join(functions, 'src'), {recursive: true});
319
+ fs.writeFileSync(path.join(functions, 'package.json'), '{"name":"functions"}\n');
320
+
321
+ const json = await runCli(['init', '--json'], {cwd: path.join(functions, 'src')});
322
+ expect(JSON.parse(json.stdout).data.docsWritten).toEqual([
323
+ '../../AGENTS.md',
324
+ '../../GEMINI.md',
325
+ ]);
326
+ expect(fs.readdirSync(functions).sort()).toEqual(['package.json', 'src']);
327
+ });
328
+ });
329
+
129
330
  describe('astryx init --remove-agents', () => {
331
+ it('run in a subfolder, removes what init wrote at the project root, with the same JSON shape', async () => {
332
+ fs.writeFileSync(
333
+ path.join(tmpDir, 'package.json'),
334
+ JSON.stringify({name: 'app', dependencies: {'@astryxdesign/core': '0.7.0'}}),
335
+ );
336
+ const sub = path.join(tmpDir, 'src', 'app');
337
+ fs.mkdirSync(sub, {recursive: true});
338
+ await runCli(['init'], {cwd: sub});
339
+ expect(exists('AGENTS.md')).toBe(true);
340
+
341
+ const text = await runCli(['init', '--remove-agents'], {cwd: sub});
342
+ expect(text.status).toBe(0);
343
+ expect(text.stdout).toMatch(/Removed empty \.\.\/\.\.\/AGENTS\.md/);
344
+ expect(exists('AGENTS.md')).toBe(false);
345
+ expect(exists('GEMINI.md')).toBe(false);
346
+
347
+ await runCli(['init'], {cwd: sub});
348
+ const json = await runCli(['init', '--remove-agents', '--json'], {cwd: sub});
349
+ expect(json.status).toBe(0);
350
+ // meta.answeredBy names the release that answered (spec AST-081).
351
+ expect(JSON.parse(json.stdout)).toEqual({
352
+ apiVersion: 1,
353
+ type: 'init.remove',
354
+ data: {removed: true},
355
+ meta: {answeredBy: expect.any(Object)},
356
+ });
357
+ });
358
+
130
359
  it('removes the Astryx section it previously installed', async () => {
131
360
  await runCli(['init', '--features', 'agents'], {cwd: tmpDir});
132
361
  expect(exists('AGENTS.md')).toBe(true);