@atlaskit/ads-cli 0.8.2 → 0.10.0

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.
@@ -14,6 +14,7 @@ import { commands } from './commands/definitions';
14
14
  import { getCommand } from './commands/get-command';
15
15
  import { getVersion } from './commands/get-version';
16
16
  import { importToolHandler } from './commands/import-tool-handler';
17
+ import { runInitCommand } from './commands/init';
17
18
  import { runTool } from './commands/run-tool';
18
19
  import { createErrorEnvelope } from './envelope/create-error-envelope';
19
20
  import { createSuccessEnvelope } from './envelope/create-success-envelope';
@@ -53,6 +54,9 @@ const buildHelpText = invocation => {
53
54
  return ` --${flag.name}${aliases}`.padEnd(18) + flag.description;
54
55
  }).join('\n');
55
56
  const examples = [{
57
+ command: 'init',
58
+ comment: 'set up repository-local frontend skills and the Atlas plugin'
59
+ }, {
56
60
  command: 'search contrast',
57
61
  comment: 'unified: components, tokens, icons & docs'
58
62
  }, {
@@ -111,6 +115,15 @@ const runRegistryCommand = async ({
111
115
  invocation
112
116
  }) => {
113
117
  var _resolved$meta3;
118
+ if (command.action === 'init') {
119
+ return runInitCommand({
120
+ input,
121
+ json,
122
+ writer,
123
+ invocation,
124
+ cwd: process.cwd()
125
+ });
126
+ }
114
127
  const resolved = command.resolve(input);
115
128
 
116
129
  // A resolver returning `{ error }` indicates invalid input (a usage error).
@@ -366,6 +379,7 @@ const runBatchChild = async ({
366
379
  request,
367
380
  invocation
368
381
  }) => {
382
+ var _getCommand;
369
383
  const parsed = parseArgs(request.argv);
370
384
  let response;
371
385
  if (!parsed.command) {
@@ -380,6 +394,12 @@ const runBatchChild = async ({
380
394
  code: 'USAGE_ERROR',
381
395
  message: 'Nested batch requests are not supported.'
382
396
  });
397
+ } else if ((_getCommand = getCommand(parsed.command)) !== null && _getCommand !== void 0 && _getCommand.action) {
398
+ response = createErrorEnvelope({
399
+ command: parsed.command,
400
+ code: 'USAGE_ERROR',
401
+ message: `Action command "${parsed.command}" cannot run inside batch.`
402
+ });
383
403
  } else {
384
404
  const captured = createCapturedWriter();
385
405
  await run([...request.argv, '--json'], captured, {
@@ -542,6 +542,16 @@ const resolveBatch = input => {
542
542
  * The full set of CLI commands. Order here is the order shown by `manifest` and `--help`.
543
543
  */
544
544
  export const commands = [{
545
+ name: 'init',
546
+ action: 'init',
547
+ description: 'Set up the ADS, UI Styling Standard, and Accessibility Foundation skills at the Git repository root and install the Atlas CLI ADS plugin.',
548
+ usage: 'init',
549
+ arguments: [],
550
+ flags: [],
551
+ examples: ['init'],
552
+ responseTypes: ['ads-cli/init'],
553
+ envelopeType: () => 'init'
554
+ }, {
545
555
  name: 'search',
546
556
  description: 'Fuzzy-search ADS components, tokens, icons, and docs together (or narrow results with --type). Returns up to 2 matches per term, per result type by default; override with --limit.',
547
557
  usage: `search <query...> [--type ${Object.keys(SEARCH_TYPE_VALUES).join('|')}] [--limit N]`,
@@ -0,0 +1,371 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { lstatSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { createErrorEnvelope } from '../envelope/create-error-envelope';
5
+ import { createSuccessEnvelope } from '../envelope/create-success-envelope';
6
+ import { writeHumanError } from '../output/write-human-error';
7
+ import { writeJsonEnvelope } from '../output/write-json-envelope';
8
+ import { ExitCode } from '../types';
9
+ import { CLI_ATLAS_INVOCATION } from './cli-metadata';
10
+ import { AGENTS_FILE_RELATIVE_PATH, updateAgentsFile } from './update-agents-file';
11
+ const SKILL_ENTRYPOINT = 'SKILL.md';
12
+ const SKILLS = [{
13
+ name: 'atlassian-design-system',
14
+ displayName: 'ADS',
15
+ relativePath: '.agents/skills/atlassian-design-system',
16
+ requiredFiles: [SKILL_ENTRYPOINT]
17
+ }, {
18
+ name: 'ui-styling-standard',
19
+ displayName: 'UI Styling Standard',
20
+ relativePath: '.agents/skills/ui-styling-standard',
21
+ requiredFiles: [SKILL_ENTRYPOINT]
22
+ }, {
23
+ name: 'a11y-foundation',
24
+ displayName: 'Accessibility Foundation',
25
+ relativePath: '.agents/skills/a11y-foundation',
26
+ requiredFiles: [SKILL_ENTRYPOINT]
27
+ }];
28
+ const ADS_SKILL = SKILLS[0];
29
+ const SKILL_GET_STARTED_RELATIVE_PATH = `${ADS_SKILL.relativePath}/references/get-started.md`;
30
+ const GIT_MARKER = '.git';
31
+ const SKILLS_INSTALLER_PACKAGE = '@atlassian/skills';
32
+ const SKILLS_INSTALLER_UNAVAILABLE_REASON = 'skills-installer-unavailable';
33
+ const SKILLS_INSTALLER_UNAVAILABLE_ERROR_CODES = new Set(['EACCES', 'EAI_AGAIN', 'ECONNREFUSED', 'ECONNRESET', 'ENOENT', 'ENOTFOUND', 'ETIMEDOUT']);
34
+ const defaultPathExists = target => {
35
+ try {
36
+ lstatSync(target);
37
+ return true;
38
+ } catch (error) {
39
+ if (error.code === 'ENOENT') {
40
+ return false;
41
+ }
42
+ throw error;
43
+ }
44
+ };
45
+ const defaultRunProcess = ({
46
+ command,
47
+ args,
48
+ cwd,
49
+ capture
50
+ }) => {
51
+ const result = spawnSync(command, args, {
52
+ cwd,
53
+ encoding: 'utf8',
54
+ stdio: capture ? 'pipe' : 'inherit'
55
+ });
56
+ return {
57
+ status: result.status,
58
+ stdout: typeof result.stdout === 'string' ? result.stdout : '',
59
+ stderr: typeof result.stderr === 'string' ? result.stderr : '',
60
+ error: result.error
61
+ };
62
+ };
63
+ const processFailureMessage = (result, fallback) => {
64
+ var _result$error;
65
+ const details = result.stderr.trim() || ((_result$error = result.error) === null || _result$error === void 0 ? void 0 : _result$error.message);
66
+ return details ? `${fallback}: ${details}` : fallback;
67
+ };
68
+ const isSkillsInstallerUnavailableFailure = result => {
69
+ var _result$error2, _result$error$message, _result$error3;
70
+ if (result.status === null || (_result$error2 = result.error) !== null && _result$error2 !== void 0 && _result$error2.code && SKILLS_INSTALLER_UNAVAILABLE_ERROR_CODES.has(result.error.code)) {
71
+ return true;
72
+ }
73
+ const details = `${result.stdout}\n${result.stderr}\n${(_result$error$message = (_result$error3 = result.error) === null || _result$error3 === void 0 ? void 0 : _result$error3.message) !== null && _result$error$message !== void 0 ? _result$error$message : ''}`.toLowerCase();
74
+ if (!details.trim()) {
75
+ return true;
76
+ }
77
+ return ['401 unauthorized', '403 forbidden', '404 not found', 'authentication required', 'could not resolve', 'e401', 'e403', 'e404', 'eneedauth', 'failed to fetch', 'network error', 'not in this registry', 'registry unavailable', 'unable to authenticate', 'unable to resolve'].some(message => details.includes(message));
78
+ };
79
+ const createNotInstalledSkillResults = reason => SKILLS.map(skillDefinition => ({
80
+ name: skillDefinition.name,
81
+ status: 'not-installed',
82
+ path: skillDefinition.relativePath,
83
+ reason
84
+ }));
85
+ const findRepositoryRoot = cwd => {
86
+ let current = path.resolve(cwd);
87
+ while (true) {
88
+ if (defaultPathExists(path.join(current, GIT_MARKER))) {
89
+ return current;
90
+ }
91
+ const parent = path.dirname(current);
92
+ if (parent === current) {
93
+ return undefined;
94
+ }
95
+ current = parent;
96
+ }
97
+ };
98
+ const writeUsageError = ({
99
+ message,
100
+ json,
101
+ writer
102
+ }) => {
103
+ if (json) {
104
+ writeJsonEnvelope({
105
+ envelope: createErrorEnvelope({
106
+ command: 'init',
107
+ code: 'USAGE_ERROR',
108
+ message
109
+ }),
110
+ writer
111
+ });
112
+ } else {
113
+ writeHumanError({
114
+ message,
115
+ writer
116
+ });
117
+ writer.err('Usage: init');
118
+ }
119
+ return ExitCode.UsageError;
120
+ };
121
+ const validateInput = input => {
122
+ if (input.positionals.length > 0) {
123
+ return '`init` does not accept positional arguments.';
124
+ }
125
+ const allowedFlags = new Set(['json']);
126
+ const unknownFlag = Object.keys(input.flags).find(flag => !allowedFlags.has(flag));
127
+ if (unknownFlag) {
128
+ return `Unknown flag "--${unknownFlag}".`;
129
+ }
130
+ return undefined;
131
+ };
132
+ const writeAgentsFileResult = ({
133
+ result,
134
+ writer
135
+ }) => {
136
+ switch (result.status) {
137
+ case 'created':
138
+ writer.out(`✓ Created ${AGENTS_FILE_RELATIVE_PATH} with ADS setup guidance`);
139
+ return;
140
+ case 'appended':
141
+ writer.out(`✓ Appended ADS setup guidance to ${AGENTS_FILE_RELATIVE_PATH}`);
142
+ return;
143
+ case 'updated':
144
+ writer.out(`✓ Updated ADS setup guidance in ${AGENTS_FILE_RELATIVE_PATH}`);
145
+ return;
146
+ case 'already-current':
147
+ writer.out(`✓ ADS setup guidance already current in ${AGENTS_FILE_RELATIVE_PATH}`);
148
+ return;
149
+ case 'not-written':
150
+ writer.out(`– ${AGENTS_FILE_RELATIVE_PATH} not updated because the current directory is not in a Git repository`);
151
+ }
152
+ };
153
+ export const runInitCommand = async ({
154
+ input,
155
+ json,
156
+ writer,
157
+ invocation,
158
+ cwd
159
+ }) => {
160
+ const usageError = validateInput(input);
161
+ if (usageError) {
162
+ return writeUsageError({
163
+ message: usageError,
164
+ json,
165
+ writer
166
+ });
167
+ }
168
+ const projectRoot = findRepositoryRoot(cwd);
169
+ const skills = [];
170
+ let agentsMd;
171
+ const repositorySetupErrors = [];
172
+ if (!projectRoot) {
173
+ skills.push(...createNotInstalledSkillResults('not-in-git-repository'));
174
+ if (!json) {
175
+ writer.out('– Repository-local skills not installed because the current directory is not in a Git repository');
176
+ }
177
+ agentsMd = {
178
+ status: 'not-written',
179
+ path: AGENTS_FILE_RELATIVE_PATH,
180
+ reason: 'not-in-git-repository'
181
+ };
182
+ if (!json) {
183
+ writeAgentsFileResult({
184
+ result: agentsMd,
185
+ writer
186
+ });
187
+ }
188
+ } else {
189
+ const npxCommand = process.platform === 'win32' ? 'npx.cmd' : 'npx';
190
+ let skillsInstallerUnavailable = false;
191
+ const skillHumanOutput = [];
192
+ for (const skillDefinition of SKILLS) {
193
+ try {
194
+ const skillPath = path.join(projectRoot, skillDefinition.relativePath);
195
+ const skillEntrypoint = path.join(skillPath, SKILL_ENTRYPOINT);
196
+ const skillPathExists = defaultPathExists(skillPath);
197
+ const skillEntrypointExists = defaultPathExists(skillEntrypoint);
198
+ const isCurrent = skillDefinition.requiredFiles.every(requiredFile => defaultPathExists(path.join(skillPath, requiredFile)));
199
+ if (skillPathExists && !skillEntrypointExists) {
200
+ throw new Error(`Cannot install the ${skillDefinition.displayName} skill because ${skillDefinition.relativePath} already exists without a ${SKILL_ENTRYPOINT}. Move or remove it, then run init again.`);
201
+ }
202
+ let skillResult;
203
+ if (isCurrent) {
204
+ skillResult = {
205
+ name: skillDefinition.name,
206
+ status: 'already-installed',
207
+ path: skillDefinition.relativePath
208
+ };
209
+ } else {
210
+ const result = defaultRunProcess({
211
+ command: npxCommand,
212
+ args: ['--yes', SKILLS_INSTALLER_PACKAGE, 'add', skillDefinition.name, '--universal', '--yes'],
213
+ cwd: projectRoot,
214
+ capture: true
215
+ });
216
+ if (result.status !== 0) {
217
+ if (isSkillsInstallerUnavailableFailure(result)) {
218
+ skillsInstallerUnavailable = true;
219
+ break;
220
+ }
221
+ throw new Error(processFailureMessage(result, `Failed to install the ${skillDefinition.displayName} skill`));
222
+ }
223
+ const missingRequiredFile = skillDefinition.requiredFiles.find(requiredFile => !defaultPathExists(path.join(skillPath, requiredFile)));
224
+ if (missingRequiredFile) {
225
+ const missingRelativePath = `${skillDefinition.relativePath}/${missingRequiredFile}`;
226
+ throw new Error(`The skill installer completed without creating ${missingRelativePath}.`);
227
+ }
228
+ skillResult = {
229
+ name: skillDefinition.name,
230
+ status: skillEntrypointExists ? 'updated' : 'installed',
231
+ path: skillDefinition.relativePath
232
+ };
233
+ }
234
+ skills.push(skillResult);
235
+ if (!json) {
236
+ const statusMessage = skillResult.status === 'already-installed' ? 'already set up' : skillResult.status;
237
+ skillHumanOutput.push(`✓ ${skillDefinition.displayName} skill ${statusMessage} at ${skillDefinition.relativePath}`);
238
+ }
239
+ } catch (error) {
240
+ repositorySetupErrors.push(error instanceof Error ? error : new Error(`Failed to set up the ${skillDefinition.displayName} skill.`));
241
+ }
242
+ }
243
+ if (skillsInstallerUnavailable) {
244
+ const skillResultsByName = new Map(skills.map(skill => [skill.name, skill]));
245
+ skills.splice(0, skills.length, ...SKILLS.map(skillDefinition => {
246
+ var _skillResultsByName$g;
247
+ return (_skillResultsByName$g = skillResultsByName.get(skillDefinition.name)) !== null && _skillResultsByName$g !== void 0 ? _skillResultsByName$g : {
248
+ name: skillDefinition.name,
249
+ status: 'not-installed',
250
+ path: skillDefinition.relativePath,
251
+ reason: SKILLS_INSTALLER_UNAVAILABLE_REASON
252
+ };
253
+ }));
254
+ }
255
+ if (!json) {
256
+ for (const line of skillHumanOutput) {
257
+ writer.out(line);
258
+ }
259
+ if (skillsInstallerUnavailable) {
260
+ writer.out(skillHumanOutput.length > 0 ? '– Remaining repository-local skills skipped because @atlassian/skills is unavailable; npx @atlaskit/ads-cli remains available' : '– Repository-local skills skipped because @atlassian/skills is unavailable; npx @atlaskit/ads-cli remains available');
261
+ }
262
+ }
263
+ const installedSkills = skills.filter(skill => skill.status !== 'not-installed');
264
+ const adsSkillInstalled = installedSkills.some(skill => skill.name === ADS_SKILL.name);
265
+ if (skillsInstallerUnavailable || adsSkillInstalled) {
266
+ try {
267
+ agentsMd = updateAgentsFile({
268
+ projectRoot,
269
+ guidance: adsSkillInstalled ? {
270
+ mode: 'skills-installed',
271
+ skillEntrypoints: installedSkills.map(skill => `${skill.path}/${SKILL_ENTRYPOINT}`),
272
+ getStartedPath: SKILL_GET_STARTED_RELATIVE_PATH
273
+ } : {
274
+ mode: 'public'
275
+ }
276
+ });
277
+ if (!json) {
278
+ writeAgentsFileResult({
279
+ result: agentsMd,
280
+ writer
281
+ });
282
+ }
283
+ } catch (error) {
284
+ repositorySetupErrors.push(error instanceof Error ? error : new Error('Failed to set up the ADS repository guidance.'));
285
+ }
286
+ }
287
+ }
288
+ const atlasCwd = projectRoot !== null && projectRoot !== void 0 ? projectRoot : path.resolve(cwd);
289
+ let atlasPluginStatus;
290
+ if (invocation === CLI_ATLAS_INVOCATION) {
291
+ atlasPluginStatus = 'already-installed';
292
+ if (!json) {
293
+ writer.out('✓ Atlas CLI ADS plugin already available');
294
+ }
295
+ } else {
296
+ var _atlasCheck$error;
297
+ const atlasCheck = defaultRunProcess({
298
+ command: 'atlas',
299
+ args: ['ads', '--help'],
300
+ cwd: atlasCwd,
301
+ capture: true
302
+ });
303
+ if (atlasCheck.status === 0) {
304
+ atlasPluginStatus = 'already-installed';
305
+ if (!json) {
306
+ writer.out('✓ Atlas CLI ADS plugin already available');
307
+ }
308
+ } else if (((_atlasCheck$error = atlasCheck.error) === null || _atlasCheck$error === void 0 ? void 0 : _atlasCheck$error.code) === 'ENOENT') {
309
+ atlasPluginStatus = 'atlas-cli-unavailable';
310
+ if (!json) {
311
+ writer.out('– Atlas CLI is unavailable; use npx @atlaskit/ads-cli for ADS commands');
312
+ }
313
+ } else {
314
+ const installResult = defaultRunProcess({
315
+ command: 'atlas',
316
+ args: ['plugin', 'install', '--name', 'ads'],
317
+ cwd: atlasCwd,
318
+ capture: json
319
+ });
320
+ if (installResult.status !== 0) {
321
+ throw new Error(processFailureMessage(installResult, 'Failed to install the Atlas CLI ADS plugin. npx @atlaskit/ads-cli remains available'));
322
+ }
323
+ const verification = defaultRunProcess({
324
+ command: 'atlas',
325
+ args: ['ads', '--help'],
326
+ cwd: atlasCwd,
327
+ capture: true
328
+ });
329
+ if (verification.status !== 0) {
330
+ throw new Error('The Atlas CLI ADS plugin was installed but `atlas ads --help` did not succeed. npx @atlaskit/ads-cli remains available.');
331
+ }
332
+ atlasPluginStatus = 'installed';
333
+ if (!json) {
334
+ writer.out('✓ Atlas CLI ADS plugin installed');
335
+ }
336
+ }
337
+ }
338
+ if (repositorySetupErrors.length > 0) {
339
+ throw new Error(repositorySetupErrors.map(error => error.message).join('\n'));
340
+ }
341
+ // Keep the successful-path invariant explicit so future control-flow changes cannot return a partial result.
342
+ if (skills.length !== SKILLS.length || !agentsMd) {
343
+ throw new Error('Failed to determine the ADS repository setup result.');
344
+ }
345
+ const adsSkillInstalled = skills.some(skill => skill.name === ADS_SKILL.name && skill.status !== 'not-installed');
346
+ const nextStep = projectRoot && adsSkillInstalled ? SKILL_GET_STARTED_RELATIVE_PATH : null;
347
+ if (!json && nextStep) {
348
+ writer.out(`→ Next: follow ${nextStep} to complete repository setup`);
349
+ }
350
+ const data = {
351
+ projectRoot: projectRoot !== null && projectRoot !== void 0 ? projectRoot : null,
352
+ skills,
353
+ agentsMd,
354
+ atlas: {
355
+ status: atlasPluginStatus
356
+ },
357
+ nextStep
358
+ };
359
+ if (json) {
360
+ writeJsonEnvelope({
361
+ envelope: createSuccessEnvelope({
362
+ envelopeType: 'init',
363
+ command: 'init',
364
+ data,
365
+ meta: {}
366
+ }),
367
+ writer
368
+ });
369
+ }
370
+ return ExitCode.Ok;
371
+ };
@@ -0,0 +1,139 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { lstatSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ export const ADS_INIT_START_MARKER = '<!-- ADS:INIT:START -->';
5
+ export const ADS_INIT_END_MARKER = '<!-- ADS:INIT:END -->';
6
+ export const AGENTS_FILE_RELATIVE_PATH = 'AGENTS.md';
7
+ const markerError = () => new Error(`Cannot update ${AGENTS_FILE_RELATIVE_PATH} because the ${ADS_INIT_START_MARKER} and ${ADS_INIT_END_MARKER} markers are malformed or ambiguous. Repair or remove the markers, then run init again.`);
8
+ const countOccurrences = (content, value) => content.split(value).length - 1;
9
+ const isStandaloneMarker = (content, marker, index) => {
10
+ const beforeIsLineBoundary = index === 0 || content[index - 1] === '\n';
11
+ const afterIndex = index + marker.length;
12
+ const afterIsLineBoundary = afterIndex === content.length || content[afterIndex] === '\n' || content[afterIndex] === '\r' && content[afterIndex + 1] === '\n';
13
+ return beforeIsLineBoundary && afterIsLineBoundary;
14
+ };
15
+ const detectLineEnding = content => {
16
+ var _content$match$length, _content$match, _content$replace$matc, _content$replace$matc2;
17
+ const crlfCount = (_content$match$length = (_content$match = content.match(/\r\n/g)) === null || _content$match === void 0 ? void 0 : _content$match.length) !== null && _content$match$length !== void 0 ? _content$match$length : 0;
18
+ const lfOnlyCount = (_content$replace$matc = (_content$replace$matc2 = content.replace(/\r\n/g, '').match(/\n/g)) === null || _content$replace$matc2 === void 0 ? void 0 : _content$replace$matc2.length) !== null && _content$replace$matc !== void 0 ? _content$replace$matc : 0;
19
+ return crlfCount > lfOnlyCount ? '\r\n' : '\n';
20
+ };
21
+ const MCP_GUIDANCE = ['Use `atlas ads` first for structured ADS lookups. If Atlas is unavailable, use `npx @atlaskit/ads-cli` with the same trailing arguments.', '', '### Hosted ADS MCP fallback', '', 'Prefer the CLI first. Configure the hosted ADS MCP server only if this repository does not already configure `ads-mcp` or `atlassian-ads-mcp`. Merge the selected server into the existing configuration without replacing other servers, then reload the agent or IDE.', '', '**Cursor — `.cursor/mcp.json`:**', '', '```json', '{', ' "mcpServers": {', ' "ads-mcp": {', ' "url": "https://mcp.atlassian.com/v1/ads/public/mcp"', ' }', ' }', '}', '```', '', '**VS Code — `.vscode/mcp.json`:**', '', '```json', '{', ' "servers": {', ' "ads-mcp": {', ' "type": "http",', ' "url": "https://mcp.atlassian.com/v1/ads/public/mcp"', ' }', ' }', '}', '```', '', '**Codex — `.codex/config.toml`:**', '', '```toml', '[mcp_servers.atlassian-ads-mcp]', 'url = "https://mcp.atlassian.com/v1/ads/public/mcp"', '```', '', 'Do not add Rovo MCP configuration to the repository.'];
22
+ const renderManagedBlock = ({
23
+ lineEnding,
24
+ guidance
25
+ }) => {
26
+ const skillGuidance = guidance.mode === 'skills-installed' ? ['`init` installed repository-local guidance for setting up and using the Atlassian Design System.', '', 'For Atlassian frontend UI work—including component selection, tokens, icons, styling, accessibility, product content and ADS lint rules—follow:', '', ...guidance.skillEntrypoints.map(entrypoint => `- \`${entrypoint}\``), '', "Before starting frontend UI work, check and complete this repository's ADS setup by following:", '', `\`${guidance.getStartedPath}\``, '', 'Apply only the setup that is missing, and preserve equivalent existing configuration.', ''] : ['`init` did not install repository-local skills. Use the public ADS CLI and optional MCP guidance below.', ''];
27
+ return [ADS_INIT_START_MARKER, '## Getting started with the Atlassian Design System', '', ...skillGuidance, ...MCP_GUIDANCE, '', "This is a temporary initialization section. It may be removed or rephrased once this repository's ADS setup has been completed.", ADS_INIT_END_MARKER].join(lineEnding);
28
+ };
29
+ const readTargetStats = targetPath => {
30
+ try {
31
+ return lstatSync(targetPath);
32
+ } catch (error) {
33
+ if (error.code === 'ENOENT') {
34
+ return undefined;
35
+ }
36
+ throw error;
37
+ }
38
+ };
39
+ const atomicWriteFile = ({
40
+ targetPath,
41
+ content,
42
+ mode,
43
+ targetExists
44
+ }) => {
45
+ const temporaryPath = path.join(path.dirname(targetPath), `.${path.basename(targetPath)}.${process.pid}.${randomUUID()}.tmp`);
46
+ let temporaryFileExists = false;
47
+ try {
48
+ writeFileSync(temporaryPath, content, {
49
+ encoding: 'utf8',
50
+ flag: 'wx',
51
+ mode
52
+ });
53
+ temporaryFileExists = true;
54
+ try {
55
+ renameSync(temporaryPath, targetPath);
56
+ temporaryFileExists = false;
57
+ } catch (error) {
58
+ const code = error.code;
59
+ const canFallbackOnWindows = process.platform === 'win32' && targetExists && (code === 'EACCES' || code === 'EEXIST' || code === 'EPERM');
60
+ if (!canFallbackOnWindows) {
61
+ throw error;
62
+ }
63
+ writeFileSync(targetPath, content, {
64
+ encoding: 'utf8',
65
+ mode
66
+ });
67
+ unlinkSync(temporaryPath);
68
+ temporaryFileExists = false;
69
+ }
70
+ } finally {
71
+ if (temporaryFileExists) {
72
+ try {
73
+ unlinkSync(temporaryPath);
74
+ } catch {
75
+ // Preserve the original write failure if temporary cleanup also fails.
76
+ }
77
+ }
78
+ }
79
+ };
80
+ export const updateAgentsFile = ({
81
+ projectRoot,
82
+ guidance
83
+ }) => {
84
+ var _stats$mode;
85
+ const targetPath = path.join(projectRoot, AGENTS_FILE_RELATIVE_PATH);
86
+ const stats = readTargetStats(targetPath);
87
+ if (stats !== null && stats !== void 0 && stats.isSymbolicLink()) {
88
+ throw new Error(`Cannot update ${AGENTS_FILE_RELATIVE_PATH} because it is a symbolic link.`);
89
+ }
90
+ if (stats && !stats.isFile()) {
91
+ throw new Error(`Cannot update ${AGENTS_FILE_RELATIVE_PATH} because it is not a regular file.`);
92
+ }
93
+ const existingContent = stats ? readFileSync(targetPath, 'utf8') : '';
94
+ const lineEnding = detectLineEnding(existingContent);
95
+ const managedBlock = renderManagedBlock({
96
+ lineEnding,
97
+ guidance
98
+ });
99
+ const startCount = countOccurrences(existingContent, ADS_INIT_START_MARKER);
100
+ const endCount = countOccurrences(existingContent, ADS_INIT_END_MARKER);
101
+ let nextContent;
102
+ let status;
103
+ if (!stats) {
104
+ nextContent = `${managedBlock}${lineEnding}`;
105
+ status = 'created';
106
+ } else if (startCount === 0 && endCount === 0) {
107
+ const separator = existingContent.length === 0 ? '' : existingContent.endsWith(`${lineEnding}${lineEnding}`) ? '' : existingContent.endsWith(lineEnding) ? lineEnding : `${lineEnding}${lineEnding}`;
108
+ nextContent = `${existingContent}${separator}${managedBlock}${lineEnding}`;
109
+ status = 'appended';
110
+ } else {
111
+ if (startCount !== 1 || endCount !== 1) {
112
+ throw markerError();
113
+ }
114
+ const startIndex = existingContent.indexOf(ADS_INIT_START_MARKER);
115
+ const endIndex = existingContent.indexOf(ADS_INIT_END_MARKER);
116
+ if (startIndex > endIndex || !isStandaloneMarker(existingContent, ADS_INIT_START_MARKER, startIndex) || !isStandaloneMarker(existingContent, ADS_INIT_END_MARKER, endIndex)) {
117
+ throw markerError();
118
+ }
119
+ const afterManagedBlock = endIndex + ADS_INIT_END_MARKER.length;
120
+ nextContent = `${existingContent.slice(0, startIndex)}${managedBlock}${existingContent.slice(afterManagedBlock)}`;
121
+ if (nextContent === existingContent) {
122
+ return {
123
+ status: 'already-current',
124
+ path: AGENTS_FILE_RELATIVE_PATH
125
+ };
126
+ }
127
+ status = 'updated';
128
+ }
129
+ atomicWriteFile({
130
+ targetPath,
131
+ content: nextContent,
132
+ mode: (_stats$mode = stats === null || stats === void 0 ? void 0 : stats.mode) !== null && _stats$mode !== void 0 ? _stats$mode : 0o666,
133
+ targetExists: stats !== undefined
134
+ });
135
+ return {
136
+ status,
137
+ path: AGENTS_FILE_RELATIVE_PATH
138
+ };
139
+ };