@cubicecho/agent-docs 0.0.0-stage → 0.2.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.
Files changed (54) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +52 -2
  3. package/_agents/docs/01-install.md +55 -0
  4. package/_agents/docs/checks.md +16 -0
  5. package/_agents/docs/ci.md +71 -0
  6. package/_agents/docs/cli.md +39 -0
  7. package/_agents/docs/common-mistakes.md +54 -0
  8. package/_agents/docs/config.md +25 -0
  9. package/dist/bin.d.ts +7 -0
  10. package/dist/bin.js +11 -0
  11. package/dist/check/check-agent-docs.d.ts +23 -0
  12. package/dist/check/check-agent-docs.js +314 -0
  13. package/dist/check/generation.d.ts +37 -0
  14. package/dist/check/generation.js +86 -0
  15. package/dist/cli/run.d.ts +24 -0
  16. package/dist/cli/run.js +131 -0
  17. package/dist/consts.d.ts +16 -0
  18. package/dist/consts.js +16 -0
  19. package/dist/core/config.d.ts +31 -0
  20. package/dist/core/config.js +69 -0
  21. package/dist/core/errors.d.ts +17 -0
  22. package/dist/core/errors.js +21 -0
  23. package/dist/core/files.d.ts +28 -0
  24. package/dist/core/files.js +67 -0
  25. package/dist/core/json.d.ts +26 -0
  26. package/dist/core/json.js +44 -0
  27. package/dist/core/package-manifest.d.ts +38 -0
  28. package/dist/core/package-manifest.js +58 -0
  29. package/dist/defaults.d.ts +26 -0
  30. package/dist/defaults.js +14 -0
  31. package/dist/exports/entry-points.d.ts +30 -0
  32. package/dist/exports/entry-points.js +119 -0
  33. package/dist/exports/export-index.d.ts +44 -0
  34. package/dist/exports/export-index.js +233 -0
  35. package/dist/exports/module-source.d.ts +74 -0
  36. package/dist/exports/module-source.js +161 -0
  37. package/dist/exports/scan.d.ts +29 -0
  38. package/dist/exports/scan.js +156 -0
  39. package/dist/exports/summary.d.ts +36 -0
  40. package/dist/exports/summary.js +84 -0
  41. package/dist/index.d.ts +16 -0
  42. package/dist/index.js +16 -0
  43. package/dist/llms/identity.d.ts +21 -0
  44. package/dist/llms/identity.js +67 -0
  45. package/dist/llms/plan.d.ts +53 -0
  46. package/dist/llms/plan.js +318 -0
  47. package/dist/llms/sync.d.ts +16 -0
  48. package/dist/llms/sync.js +36 -0
  49. package/dist/markdown/anchors.d.ts +35 -0
  50. package/dist/markdown/anchors.js +66 -0
  51. package/dist/markdown/page.d.ts +20 -0
  52. package/dist/markdown/page.js +57 -0
  53. package/llms.txt +42 -0
  54. package/package.json +64 -4
@@ -0,0 +1,314 @@
1
+ import { existsSync, lstatSync, readdirSync, readFileSync } from 'node:fs';
2
+ import { dirname, join, relative } from 'node:path';
3
+ import { BYTES_PER_KB, LLMS_FILE, POINTER_LINE, POINTER_TEXT } from '../consts.js';
4
+ import { loadLlmsConfig } from '../core/config.js';
5
+ import { AgentDocsError } from '../core/errors.js';
6
+ import { markdownFiles } from '../core/files.js';
7
+ import { isJsonObject, readJsonFile } from '../core/json.js';
8
+ import { readPackageManifest } from '../core/package-manifest.js';
9
+ import { LIMIT_DEFAULTS } from '../defaults.js';
10
+ import { headings, links } from '../markdown/anchors.js';
11
+ import { EXEC_PLUGIN, EXEC_SUGGESTION, ignoresLlms, npmGeneratesLlms, PREPACK_SUGGESTION, releaseGeneratesLlms, } from './generation.js';
12
+ const URL_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
13
+ const LICENSE_FILE = /^(LICEN[CS]E|COPYING)(\.|$)/i;
14
+ const HAXELIB_PLUGIN = 'semantic-release-haxelib';
15
+ /** Files whose relative links are checked, beside the pages. */
16
+ const LINKED_FILES = [LLMS_FILE, 'README.md', 'AGENTS.md'];
17
+ /**
18
+ * Checks a package against the agent documentation standard, changing nothing.
19
+ *
20
+ * @param root - Package root.
21
+ * @param overrides - Limits to change, for a test or an unusual repo.
22
+ * @returns The problems found and the page count.
23
+ *
24
+ * @remarks
25
+ * The rules: pages within `pageLimitKb`, a contents list on a page over `contentsAfterLines`, relative links that
26
+ * resolve inside the repo (README has none but `#anchor`s), the README's hidden pointer, CLAUDE.md as a link to
27
+ * AGENTS.md, no hidden `.agents/`, a LICENSE and the right `files` for a published package, the
28
+ * semantic-release-haxelib file list, and llms.txt generated when the package is packed and kept out of git. A
29
+ * private workspace root is held to the repo-level rules only.
30
+ */
31
+ export function checkAgentDocs(root, overrides = {}) {
32
+ const limits = { ...LIMIT_DEFAULTS, ...overrides };
33
+ const problems = [];
34
+ const setup = readSetup(root, problems);
35
+ if (setup === undefined) {
36
+ return { problems, pageCount: 0 };
37
+ }
38
+ const { docsDir, isWorkspaceRoot, pages } = setup;
39
+ if (pages.length === 0 && isWorkspaceRoot === false) {
40
+ problems.push(`${docsDir}/ has no pages: write the agent docs there, starting with 01-install.md.`);
41
+ }
42
+ problems.push(...pageProblems(root, pages, limits), ...linkProblems(root, pages, isWorkspaceRoot), ...repoProblems(root, isWorkspaceRoot), ...packageProblems(root, docsDir), ...haxelibProblems(root, pages), ...generationProblems(root));
43
+ return { problems, pageCount: pages.length };
44
+ }
45
+ /**
46
+ * Reads what every rule needs: the docs folder, its pages and whether this is a workspace root.
47
+ *
48
+ * @param root - Package root.
49
+ * @param problems - Receives a line when a config file can't be read; appended to in place.
50
+ * @returns The setup, or undefined when llms.json or package.json can't be read.
51
+ */
52
+ function readSetup(root, problems) {
53
+ try {
54
+ const { docsDir } = loadLlmsConfig(root);
55
+ const isWorkspaceRoot = readPackageManifest(root)?.isWorkspaceRoot ?? false;
56
+ const pages = markdownFiles(root, docsDir).map((path) => join(root, path));
57
+ return { docsDir, isWorkspaceRoot, pages };
58
+ }
59
+ catch (error) {
60
+ if (error instanceof AgentDocsError) {
61
+ problems.push(...error.problems);
62
+ return undefined;
63
+ }
64
+ throw error;
65
+ }
66
+ }
67
+ /**
68
+ * A path as messages show it.
69
+ *
70
+ * @param root - Package root.
71
+ * @param path - Absolute path.
72
+ * @returns The path relative to the root, or `.` for the root itself.
73
+ */
74
+ function shown(root, path) {
75
+ return relative(root, path) || '.';
76
+ }
77
+ /**
78
+ * Rules 1 and 2: page size, and a contents list on a long page.
79
+ *
80
+ * @param root - Package root.
81
+ * @param pages - Absolute page paths.
82
+ * @param limits - The size limits.
83
+ * @returns One line per page over a limit.
84
+ */
85
+ function pageProblems(root, pages, limits) {
86
+ const { pageLimitKb, contentsAfterLines } = limits;
87
+ return pages.flatMap((page) => {
88
+ const text = readFileSync(page, 'utf8');
89
+ const found = [];
90
+ const size = Buffer.byteLength(text);
91
+ if (size > pageLimitKb * BYTES_PER_KB) {
92
+ found.push(`${shown(root, page)} is ${Math.round(size / BYTES_PER_KB)} KB, over ${pageLimitKb} KB: split it by task.`);
93
+ }
94
+ const lineCount = text.split('\n').length;
95
+ if (lineCount > contentsAfterLines) {
96
+ const top = text.slice(0, Math.max(0, text.search(/^## /m)));
97
+ const missing = headings(text).filter((h) => h.level === 2 && top.includes(`(#${h.anchor})`) === false);
98
+ if (missing.length > 0) {
99
+ const anchors = missing.map((h) => `#${h.anchor}`).join(', ');
100
+ found.push(`${shown(root, page)} is ${lineCount} lines; its contents list lacks ${anchors}: list each "##" heading above the first one.`);
101
+ }
102
+ }
103
+ return found;
104
+ });
105
+ }
106
+ /**
107
+ * Rule 3: every relative link resolves inside the repo, and the README has none but anchors.
108
+ *
109
+ * @param root - Package root.
110
+ * @param pages - Absolute page paths.
111
+ * @param isWorkspaceRoot - A private monorepo root, whose README is read on GitHub only.
112
+ * @returns One line per bad link.
113
+ */
114
+ function linkProblems(root, pages, isWorkspaceRoot) {
115
+ const readme = join(root, 'README.md');
116
+ const sources = [...pages, ...LINKED_FILES.map((file) => join(root, file)).filter((file) => existsSync(file))];
117
+ const found = [];
118
+ for (const file of sources) {
119
+ for (const href of links(readFileSync(file, 'utf8'))) {
120
+ const isAbsolute = URL_SCHEME.test(href) || href.startsWith('//');
121
+ if (isAbsolute) {
122
+ continue;
123
+ }
124
+ const [path, anchor] = href.split('#');
125
+ const isReadmeRelative = file === readme && path !== '' && isWorkspaceRoot === false;
126
+ if (isReadmeRelative) {
127
+ found.push(`README.md links to ${href} relatively: npm and haxelib render the README away from the repo, so use an absolute URL.`);
128
+ continue;
129
+ }
130
+ const target = path === '' ? file : join(dirname(file), decodeURI(path));
131
+ if (relative(root, target).startsWith('..')) {
132
+ found.push(`${shown(root, file)} links to ${href}, outside the repo: it breaks on GitHub and in the package. Use an absolute URL.`);
133
+ continue;
134
+ }
135
+ if (existsSync(target) === false) {
136
+ found.push(`${shown(root, file)} links to ${href}, which does not exist: fix the link or add the file.`);
137
+ continue;
138
+ }
139
+ if (anchor && target.endsWith('.md')) {
140
+ const known = new Set(headings(readFileSync(target, 'utf8')).map((h) => h.anchor));
141
+ if (known.has(anchor) === false) {
142
+ found.push(`${shown(root, file)} links to ${href}; ${shown(root, target)} has no such heading: fix the anchor or the heading.`);
143
+ }
144
+ }
145
+ }
146
+ }
147
+ return found;
148
+ }
149
+ /**
150
+ * Rules 4 to 6: the README and its pointer, CLAUDE.md, and the hidden `.agents/` folder.
151
+ *
152
+ * @param root - Package root.
153
+ * @param isWorkspaceRoot - A private monorepo root, which needs no pointer.
154
+ * @returns One line per problem.
155
+ */
156
+ function repoProblems(root, isWorkspaceRoot) {
157
+ const found = [];
158
+ const readme = join(root, 'README.md');
159
+ if (existsSync(readme) === false) {
160
+ found.push('README.md is missing: write one for people, starting with the hidden pointer line.');
161
+ }
162
+ else if (isWorkspaceRoot === false && readFileSync(readme, 'utf8').includes(`<!-- ${POINTER_TEXT}`) === false) {
163
+ found.push(`README.md lacks the hidden pointer: add ${POINTER_LINE} as its first line.`);
164
+ }
165
+ const claude = join(root, 'CLAUDE.md');
166
+ if (existsSync(claude)) {
167
+ const isLink = lstatSync(claude).isSymbolicLink();
168
+ const importsAgents = isLink || readFileSync(claude, 'utf8').includes('@AGENTS.md');
169
+ if (importsAgents === false) {
170
+ found.push('CLAUDE.md is a separate file: make it a symlink to AGENTS.md, or import it with "@AGENTS.md".');
171
+ }
172
+ }
173
+ const hidden = join(root, '.agents');
174
+ if (existsSync(hidden)) {
175
+ const strays = readdirSync(hidden).filter((name) => name !== 'skills');
176
+ if (strays.length > 0) {
177
+ found.push(`.agents/ holds ${strays.join(', ')}: move it with "git mv .agents _agents".`);
178
+ }
179
+ }
180
+ return found;
181
+ }
182
+ /**
183
+ * Rules 7 and 8: a published package ships a license, llms.txt and the pages, and never all of `_agents`.
184
+ *
185
+ * @param root - Package root.
186
+ * @param docsDir - The pages' folder, which `files` must list.
187
+ * @returns One line per problem; none for a private package.
188
+ */
189
+ function packageProblems(root, docsDir) {
190
+ const manifest = readPackageManifest(root);
191
+ if (manifest === undefined || manifest.isPrivate) {
192
+ return [];
193
+ }
194
+ const found = [];
195
+ const hasLicense = readdirSync(root).some((name) => LICENSE_FILE.test(name));
196
+ if (hasLicense === false) {
197
+ found.push('No LICENSE file: the published package carries no license text. Add one.');
198
+ }
199
+ if (manifest.files === undefined) {
200
+ return found;
201
+ }
202
+ const files = manifest.files.map((f) => f.replace(/^\.\//, '').replace(/\/$/, ''));
203
+ for (const needed of [LLMS_FILE, docsDir]) {
204
+ if (files.includes(needed) === false) {
205
+ found.push(`package.json "files" lacks "${needed}", so it never ships: add it.`);
206
+ }
207
+ }
208
+ if (files.includes('_agents')) {
209
+ found.push(`package.json "files" ships all of "_agents": list "${docsDir}" (and "_agents/skills") instead.`);
210
+ }
211
+ return found;
212
+ }
213
+ /**
214
+ * Rule 9: semantic-release-haxelib lists llms.txt and every page, every listed file exists, and LICENSE.md does.
215
+ *
216
+ * @param root - Package root.
217
+ * @param pages - Absolute page paths.
218
+ * @returns One line per problem; none unless the package has both haxelib.json and a release config.
219
+ *
220
+ * @remarks
221
+ * The plugin zips the class path plus `additionalFiles`, one file per entry, and silently skips a path that doesn't
222
+ * exist, so a page missing from the list never ships.
223
+ */
224
+ function haxelibProblems(root, pages) {
225
+ const release = readHaxelibRelease(root);
226
+ if (release === undefined) {
227
+ return [];
228
+ }
229
+ const { releaseFile, plugins, haxelibIndex, isJson } = release;
230
+ const found = [];
231
+ if (isJson === false) {
232
+ found.push(`${releaseFile} is not JSON, so the haxelib file list can't be checked: write it as JSON.`);
233
+ }
234
+ const haxelib = plugins[haxelibIndex];
235
+ if (Array.isArray(haxelib)) {
236
+ const generates = releaseGeneratesLlms(plugins, haxelibIndex);
237
+ const options = isJsonObject(haxelib[1]) ? haxelib[1] : {};
238
+ const listedFiles = Array.isArray(options.additionalFiles) ? options.additionalFiles : [];
239
+ const listed = new Set(listedFiles.filter((f) => typeof f === 'string').map((f) => f.replace(/^\.\//, '')));
240
+ const wanted = [LLMS_FILE, ...pages.map((page) => relative(root, page).split('\\').join('/'))];
241
+ for (const file of wanted.filter((f) => listed.has(f) === false)) {
242
+ found.push(`${releaseFile} ${HAXELIB_PLUGIN} "additionalFiles" lacks "${file}", so the haxelib zip won't contain it: add it.`);
243
+ }
244
+ // A release step writes llms.txt before the plugin zips, so a clone without it is fine.
245
+ const isMissing = (f) => generates && f === LLMS_FILE ? false : existsSync(join(root, f)) === false;
246
+ for (const file of [...listed].filter(isMissing)) {
247
+ found.push(`${releaseFile} lists "${file}" in "additionalFiles", but it doesn't exist (the plugin skips it silently): fix or remove the entry.`);
248
+ }
249
+ }
250
+ if (existsSync(join(root, 'LICENSE.md')) === false) {
251
+ found.push('LICENSE.md is missing: the haxelib zip only takes a license file by that exact name.');
252
+ }
253
+ return found;
254
+ }
255
+ /**
256
+ * Reads the release config of a package that has haxelib.json.
257
+ *
258
+ * @param root - Package root.
259
+ * @returns The config, or undefined without haxelib.json or a release config.
260
+ */
261
+ function readHaxelibRelease(root) {
262
+ const releaseFile = ['.releaserc.json', '.releaserc'].find((file) => existsSync(join(root, file)));
263
+ if (existsSync(join(root, 'haxelib.json')) === false || releaseFile === undefined) {
264
+ return undefined;
265
+ }
266
+ let release;
267
+ let isJson = true;
268
+ try {
269
+ release = readJsonFile(root, releaseFile);
270
+ }
271
+ catch {
272
+ isJson = false;
273
+ }
274
+ const plugins = isJsonObject(release) && Array.isArray(release.plugins) ? release.plugins : [];
275
+ const haxelibIndex = plugins.findIndex((plugin) => Array.isArray(plugin) && plugin[0] === HAXELIB_PLUGIN);
276
+ return { releaseFile, plugins, haxelibIndex, isJson };
277
+ }
278
+ /**
279
+ * Rule 10: whatever packs the package writes llms.txt first, and git doesn't track it.
280
+ *
281
+ * @param root - Package root.
282
+ * @returns One line per problem; none for a package nothing packs, such as one installed from git.
283
+ *
284
+ * @remarks
285
+ * npm runs `prepack` (or `prepublishOnly`) before it builds the tarball, and semantic-release-haxelib zips in its
286
+ * prepare step, so an `@semantic-release/exec` `prepareCmd` listed before it runs in time. A package installed
287
+ * straight from the repo, such as a HACS integration, commits llms.txt instead and runs `llms --check` in CI.
288
+ */
289
+ function generationProblems(root) {
290
+ const manifest = readPackageManifest(root);
291
+ const isNpm = manifest !== undefined && manifest.isPrivate === false && shipsLlms(manifest);
292
+ const release = readHaxelibRelease(root);
293
+ const isHaxelib = release !== undefined && release.haxelibIndex !== -1;
294
+ const found = [];
295
+ if (isNpm && npmGeneratesLlms(manifest) === false) {
296
+ found.push(`package.json has no prepack that writes ${LLMS_FILE}, so a publish can ship a stale one: add ${PREPACK_SUGGESTION}.`);
297
+ }
298
+ if (isHaxelib && releaseGeneratesLlms(release.plugins, release.haxelibIndex) === false) {
299
+ found.push(`${release.releaseFile} writes no ${LLMS_FILE} before ${HAXELIB_PLUGIN} zips: add ${EXEC_SUGGESTION} before it, and "${EXEC_PLUGIN}" to devDependencies.`);
300
+ }
301
+ if ((isNpm || isHaxelib) && ignoresLlms(root) === false) {
302
+ found.push(`${LLMS_FILE} is generated when the package is packed, so git shouldn't track it: add it to .gitignore and run "git rm --cached ${LLMS_FILE}".`);
303
+ }
304
+ return found;
305
+ }
306
+ /**
307
+ * Whether a published package.json ships llms.txt: npm's default of everything, or `files` listing it.
308
+ *
309
+ * @param manifest - The package manifest.
310
+ * @returns True when the tarball would hold llms.txt.
311
+ */
312
+ function shipsLlms(manifest) {
313
+ return manifest.files === undefined || manifest.files.some((f) => f.replace(/^\.\//, '') === LLMS_FILE);
314
+ }
@@ -0,0 +1,37 @@
1
+ import type { PackageManifest } from '../core/package-manifest.ts';
2
+ /** The semantic-release plugin that runs shell commands at each release step. */
3
+ export declare const EXEC_PLUGIN = "@semantic-release/exec";
4
+ /** The prepack script a failing check suggests. */
5
+ export declare const PREPACK_SUGGESTION = "\"prepack\": \"npm run build && agent-docs llms\"";
6
+ /** The plugin entry a failing haxelib check suggests. */
7
+ export declare const EXEC_SUGGESTION = "[\"@semantic-release/exec\", { \"prepareCmd\": \"npx -y @cubicecho/agent-docs llms\" }]";
8
+ /**
9
+ * Whether a shell command writes llms.txt: `agent-docs llms` without `--check` or `--stdout`.
10
+ *
11
+ * @param command - A script or command line.
12
+ * @param isSelf - The package being checked is this one, whose scripts run its own `bin.js` or `bin.ts`.
13
+ * @returns True when one of its commands writes llms.txt.
14
+ */
15
+ export declare function writesLlms(command: string, isSelf?: boolean): boolean;
16
+ /**
17
+ * Whether npm regenerates llms.txt each time it packs the package.
18
+ *
19
+ * @param manifest - The package manifest.
20
+ * @returns True when `prepack` or `prepublishOnly` writes llms.txt, directly or through `npm run`.
21
+ */
22
+ export declare function npmGeneratesLlms(manifest: PackageManifest): boolean;
23
+ /**
24
+ * Whether a semantic-release plugin list writes llms.txt before `beforePlugin` runs its prepare step.
25
+ *
26
+ * @param plugins - The `plugins` list of a release config.
27
+ * @param beforeIndex - Index of the plugin that must find llms.txt on disk.
28
+ * @returns True when an earlier `@semantic-release/exec` entry's `prepareCmd` writes llms.txt.
29
+ */
30
+ export declare function releaseGeneratesLlms(plugins: readonly unknown[], beforeIndex: number): boolean;
31
+ /**
32
+ * Whether the repo's root `.gitignore` ignores llms.txt.
33
+ *
34
+ * @param root - Package root.
35
+ * @returns True for a `llms.txt` or `/llms.txt` line.
36
+ */
37
+ export declare function ignoresLlms(root: string): boolean;
@@ -0,0 +1,86 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { LLMS_FILE, PACKAGE_NAME } from '../consts.js';
4
+ import { isJsonObject } from '../core/json.js';
5
+ /** npm lifecycle scripts that run before `npm publish` and `npm pack` build the tarball. */
6
+ const PACK_SCRIPTS = ['prepack', 'prepublishOnly'];
7
+ /** The semantic-release plugin that runs shell commands at each release step. */
8
+ export const EXEC_PLUGIN = '@semantic-release/exec';
9
+ /** The prepack script a failing check suggests. */
10
+ export const PREPACK_SUGGESTION = '"prepack": "npm run build && agent-docs llms"';
11
+ /** The plugin entry a failing haxelib check suggests. */
12
+ export const EXEC_SUGGESTION = `["${EXEC_PLUGIN}", { "prepareCmd": "npx -y ${PACKAGE_NAME} llms" }]`;
13
+ /**
14
+ * Whether a shell command writes llms.txt: `agent-docs llms` without `--check` or `--stdout`.
15
+ *
16
+ * @param command - A script or command line.
17
+ * @param isSelf - The package being checked is this one, whose scripts run its own `bin.js` or `bin.ts`.
18
+ * @returns True when one of its commands writes llms.txt.
19
+ */
20
+ export function writesLlms(command, isSelf = false) {
21
+ const runner = isSelf ? /(agent-docs(@\S*)?|\bbin\.[jt]s)\s+llms\b/ : /agent-docs(@\S*)?\s+llms\b/;
22
+ return command.split(/&&|\|\||;|\n/).some((part) => runner.test(part) && /--(check|stdout)\b/.test(part) === false);
23
+ }
24
+ /**
25
+ * Whether an npm script writes llms.txt, following `npm run <name>` into the scripts it calls.
26
+ *
27
+ * @param scripts - package.json `scripts`.
28
+ * @param name - The script to start from.
29
+ * @param isSelf - Passed to {@link writesLlms}.
30
+ * @param seen - Scripts already followed, so a loop ends; appended to in place.
31
+ * @returns True when the script, or one it runs, writes llms.txt.
32
+ */
33
+ function scriptWritesLlms(scripts, name, isSelf, seen = new Set()) {
34
+ const command = scripts[name];
35
+ if (command === undefined || seen.has(name)) {
36
+ return false;
37
+ }
38
+ seen.add(name);
39
+ if (writesLlms(command, isSelf)) {
40
+ return true;
41
+ }
42
+ const called = [...command.matchAll(/npm run(?:-script)? ([\w:.-]+)/g)].map((match) => match[1]);
43
+ return called.some((next) => next !== undefined && scriptWritesLlms(scripts, next, isSelf, seen));
44
+ }
45
+ /**
46
+ * Whether npm regenerates llms.txt each time it packs the package.
47
+ *
48
+ * @param manifest - The package manifest.
49
+ * @returns True when `prepack` or `prepublishOnly` writes llms.txt, directly or through `npm run`.
50
+ */
51
+ export function npmGeneratesLlms(manifest) {
52
+ const isSelf = manifest.name === PACKAGE_NAME;
53
+ return PACK_SCRIPTS.some((name) => scriptWritesLlms(manifest.scripts, name, isSelf));
54
+ }
55
+ /**
56
+ * Whether a semantic-release plugin list writes llms.txt before `beforePlugin` runs its prepare step.
57
+ *
58
+ * @param plugins - The `plugins` list of a release config.
59
+ * @param beforeIndex - Index of the plugin that must find llms.txt on disk.
60
+ * @returns True when an earlier `@semantic-release/exec` entry's `prepareCmd` writes llms.txt.
61
+ */
62
+ export function releaseGeneratesLlms(plugins, beforeIndex) {
63
+ return plugins.slice(0, beforeIndex).some((plugin) => {
64
+ if (Array.isArray(plugin) === false || plugin[0] !== EXEC_PLUGIN || isJsonObject(plugin[1]) === false) {
65
+ return false;
66
+ }
67
+ const command = plugin[1].prepareCmd;
68
+ return typeof command === 'string' && writesLlms(command);
69
+ });
70
+ }
71
+ /**
72
+ * Whether the repo's root `.gitignore` ignores llms.txt.
73
+ *
74
+ * @param root - Package root.
75
+ * @returns True for a `llms.txt` or `/llms.txt` line.
76
+ */
77
+ export function ignoresLlms(root) {
78
+ const path = join(root, '.gitignore');
79
+ if (existsSync(path) === false) {
80
+ return false;
81
+ }
82
+ return readFileSync(path, 'utf8')
83
+ .split('\n')
84
+ .map((line) => line.trim())
85
+ .some((line) => line === LLMS_FILE || line === `/${LLMS_FILE}`);
86
+ }
@@ -0,0 +1,24 @@
1
+ /** Where the CLI prints. */
2
+ export interface CliOutput {
3
+ /** Prints one line of normal output. */
4
+ out: (line: string) => void;
5
+ /** Prints one line of problems or usage. */
6
+ err: (line: string) => void;
7
+ }
8
+ /** The process exit codes the CLI returns. */
9
+ export declare const ExitCode: {
10
+ /** Everything passed or was written. */
11
+ readonly Ok: 0;
12
+ /** At least one problem, or a usage error. */
13
+ readonly Failed: 1;
14
+ };
15
+ export type ExitCode = (typeof ExitCode)[keyof typeof ExitCode];
16
+ /**
17
+ * Runs one CLI command against a package.
18
+ *
19
+ * @param argv - The arguments after the program name.
20
+ * @param cwd - The package root.
21
+ * @param output - Where to print.
22
+ * @returns The exit code: 1 with one line per problem, 0 otherwise.
23
+ */
24
+ export declare function runCli(argv: readonly string[], cwd: string, output: CliOutput): ExitCode;
@@ -0,0 +1,131 @@
1
+ import { checkAgentDocs } from '../check/check-agent-docs.js';
2
+ import { LLMS_FILE } from '../consts.js';
3
+ import { AgentDocsError } from '../core/errors.js';
4
+ import { LIMIT_DEFAULTS } from '../defaults.js';
5
+ import { ExportPlacement, planLlms } from '../llms/plan.js';
6
+ import { findStaleFiles, writeLlms } from '../llms/sync.js';
7
+ /** The process exit codes the CLI returns. */
8
+ export const ExitCode = {
9
+ /** Everything passed or was written. */
10
+ Ok: 0,
11
+ /** At least one problem, or a usage error. */
12
+ Failed: 1,
13
+ };
14
+ const USAGE = [
15
+ 'Usage: agent-docs <command> [options]',
16
+ '',
17
+ 'Commands:',
18
+ ' llms Write llms.txt (and any generated export pages) in the current folder.',
19
+ ' llms --check Exit 1 if llms.txt or an export page is missing or stale. For CI.',
20
+ ' llms --stdout Print what llms would write, and write nothing.',
21
+ ' llms --base-url <url> Add a "Base URL:" line, for a copy served from a site.',
22
+ ' check Check the package against the agent docs standard. Changes nothing.',
23
+ ' help Print this message.',
24
+ ].join('\n');
25
+ /**
26
+ * Runs one CLI command against a package.
27
+ *
28
+ * @param argv - The arguments after the program name.
29
+ * @param cwd - The package root.
30
+ * @param output - Where to print.
31
+ * @returns The exit code: 1 with one line per problem, 0 otherwise.
32
+ */
33
+ export function runCli(argv, cwd, output) {
34
+ const [command, ...rest] = argv;
35
+ try {
36
+ if (command === 'llms') {
37
+ return runLlms(rest, cwd, output);
38
+ }
39
+ if (command === 'check') {
40
+ return runCheck(rest, cwd, output);
41
+ }
42
+ const isHelp = command === 'help' || command === '--help' || command === '-h';
43
+ if (isHelp) {
44
+ output.out(USAGE);
45
+ return ExitCode.Ok;
46
+ }
47
+ output.err(command === undefined ? 'agent-docs: name a command.' : `agent-docs: unknown command "${command}".`);
48
+ output.err(USAGE);
49
+ return ExitCode.Failed;
50
+ }
51
+ catch (error) {
52
+ if (error instanceof AgentDocsError) {
53
+ const prefix = command === 'llms' ? 'agent-docs llms' : 'agent-docs';
54
+ for (const problem of error.problems) {
55
+ output.err(`${prefix}: ${problem}`);
56
+ }
57
+ return ExitCode.Failed;
58
+ }
59
+ throw error;
60
+ }
61
+ }
62
+ /**
63
+ * `agent-docs llms`: writes, checks or prints llms.txt.
64
+ *
65
+ * @param args - The options after `llms`.
66
+ * @param cwd - The package root.
67
+ * @param output - Where to print.
68
+ * @returns The exit code.
69
+ * @throws {@link AgentDocsError} If an option is wrong or the docs can't be indexed.
70
+ */
71
+ function runLlms(args, cwd, output) {
72
+ const known = new Set(['--check', '--stdout', '--base-url']);
73
+ const baseUrlIndex = args.indexOf('--base-url');
74
+ const baseUrl = baseUrlIndex === -1 ? undefined : args[baseUrlIndex + 1];
75
+ const isBaseUrlValue = (index) => baseUrlIndex !== -1 && index === baseUrlIndex + 1;
76
+ const unknown = args.filter((arg, index) => known.has(arg) === false && isBaseUrlValue(index) === false);
77
+ const problems = unknown.map((arg) => `unknown option "${arg}": see "agent-docs help".`);
78
+ const lacksBaseUrl = baseUrlIndex !== -1 && (baseUrl === undefined || baseUrl.startsWith('--'));
79
+ if (lacksBaseUrl) {
80
+ problems.push('--base-url needs a URL after it.');
81
+ }
82
+ if (problems.length > 0) {
83
+ throw new AgentDocsError(problems);
84
+ }
85
+ const plan = planLlms({ root: cwd, baseUrl });
86
+ if (args.includes('--stdout')) {
87
+ for (const file of plan.files) {
88
+ output.out(plan.files.length > 1 ? `==> ${file.path} <==\n${file.content}` : file.content);
89
+ }
90
+ return ExitCode.Ok;
91
+ }
92
+ const pageCount = plan.files.length - 1;
93
+ const pagesNote = plan.placement === ExportPlacement.Pages ? ` and ${pageCount} export pages` : '';
94
+ if (args.includes('--check')) {
95
+ const stale = findStaleFiles(cwd, plan);
96
+ if (stale.length > 0) {
97
+ throw new AgentDocsError(stale);
98
+ }
99
+ output.out(`agent-docs llms: ${LLMS_FILE}${pagesNote} up to date.`);
100
+ return ExitCode.Ok;
101
+ }
102
+ writeLlms(cwd, plan);
103
+ output.out(`agent-docs llms: wrote ${LLMS_FILE}${pagesNote}.`);
104
+ if (plan.placement === ExportPlacement.Pages) {
105
+ output.out(`agent-docs llms: the export index is over ${LIMIT_DEFAULTS.llmsLimitKb} KB, so it went to its own pages.`);
106
+ }
107
+ if (plan.undocumented.length > 0) {
108
+ output.out(`agent-docs llms: no doc comment on ${plan.undocumented.join(', ')}.`);
109
+ }
110
+ return ExitCode.Ok;
111
+ }
112
+ /**
113
+ * `agent-docs check`: checks the package against the standard.
114
+ *
115
+ * @param args - The options after `check`; there are none.
116
+ * @param cwd - The package root.
117
+ * @param output - Where to print.
118
+ * @returns The exit code.
119
+ * @throws {@link AgentDocsError} If an option is given, or with one line per problem.
120
+ */
121
+ function runCheck(args, cwd, output) {
122
+ if (args.length > 0) {
123
+ throw new AgentDocsError([`check takes no options, got "${args.join(' ')}".`]);
124
+ }
125
+ const { problems, pageCount } = checkAgentDocs(cwd);
126
+ if (problems.length > 0) {
127
+ throw new AgentDocsError(problems);
128
+ }
129
+ output.out(`agent-docs: ${pageCount} pages, each within ${LIMIT_DEFAULTS.pageLimitKb} KB; every link resolves.`);
130
+ return ExitCode.Ok;
131
+ }
@@ -0,0 +1,16 @@
1
+ /** Bytes in one kilobyte, as the size limits count them. */
2
+ export declare const BYTES_PER_KB = 1024;
3
+ /** This package's name, as messages tell a reader what to run. */
4
+ export declare const PACKAGE_NAME = "@cubicecho/agent-docs";
5
+ /** The command that regenerates llms.txt, quoted in every "stale" message. */
6
+ export declare const LLMS_COMMAND = "npx @cubicecho/agent-docs llms";
7
+ /** The generated index, relative to the package root. */
8
+ export declare const LLMS_FILE = "llms.txt";
9
+ /** The optional overrides file both commands read, relative to the package root. */
10
+ export declare const CONFIG_FILE = "_agents/llms.json";
11
+ /** Text the README's hidden pointer comment must contain. */
12
+ export declare const POINTER_TEXT = "AI agents:";
13
+ /** The whole pointer line, as a failing check suggests it. */
14
+ export declare const POINTER_LINE = "<!-- AI agents: read llms.txt and _agents/docs/ for the full, version-matched API. -->";
15
+ /** What every page this package generates starts with, so a rerun can tell its own pages from hand-written ones. */
16
+ export declare const GENERATED_MARKER = "<!-- Generated by @cubicecho/agent-docs";
package/dist/consts.js ADDED
@@ -0,0 +1,16 @@
1
+ /** Bytes in one kilobyte, as the size limits count them. */
2
+ export const BYTES_PER_KB = 1024;
3
+ /** This package's name, as messages tell a reader what to run. */
4
+ export const PACKAGE_NAME = '@cubicecho/agent-docs';
5
+ /** The command that regenerates llms.txt, quoted in every "stale" message. */
6
+ export const LLMS_COMMAND = 'npx @cubicecho/agent-docs llms';
7
+ /** The generated index, relative to the package root. */
8
+ export const LLMS_FILE = 'llms.txt';
9
+ /** The optional overrides file both commands read, relative to the package root. */
10
+ export const CONFIG_FILE = '_agents/llms.json';
11
+ /** Text the README's hidden pointer comment must contain. */
12
+ export const POINTER_TEXT = 'AI agents:';
13
+ /** The whole pointer line, as a failing check suggests it. */
14
+ export const POINTER_LINE = '<!-- AI agents: read llms.txt and _agents/docs/ for the full, version-matched API. -->';
15
+ /** What every page this package generates starts with, so a rerun can tell its own pages from hand-written ones. */
16
+ export const GENERATED_MARKER = '<!-- Generated by @cubicecho/agent-docs';
@@ -0,0 +1,31 @@
1
+ /** `_agents/llms.json`, the overrides both commands share, with its defaults filled in. */
2
+ export interface LlmsConfig {
3
+ /** Replaces the manifest's name as the llms.txt title. */
4
+ title?: string;
5
+ /** Replaces the manifest's description as the llms.txt summary. */
6
+ summary?: string;
7
+ /** Heading text per docs subfolder name, replacing the one made from the folder name. */
8
+ sections: Record<string, string>;
9
+ /** Markdown appended after the generated sections. */
10
+ extra?: string;
11
+ /**
12
+ * The pages' folder, relative to the package root, with `/` separators.
13
+ *
14
+ * @defaultValue `LAYOUT_DEFAULTS.docsDir`
15
+ */
16
+ docsDir: string;
17
+ /**
18
+ * Whether llms.txt indexes the package's exports.
19
+ *
20
+ * @defaultValue `true`
21
+ */
22
+ exports: boolean;
23
+ }
24
+ /**
25
+ * Reads `_agents/llms.json`, or the defaults when it is absent.
26
+ *
27
+ * @param root - Package root.
28
+ * @returns The config, every field checked.
29
+ * @throws {@link AgentDocsError} If the file is not JSON or a field has the wrong type.
30
+ */
31
+ export declare function loadLlmsConfig(root: string): LlmsConfig;