@cubicecho/agent-docs 0.0.0-stage → 0.1.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 (52) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +52 -2
  3. package/_agents/docs/01-install.md +53 -0
  4. package/_agents/docs/checks.md +15 -0
  5. package/_agents/docs/ci.md +30 -0
  6. package/_agents/docs/cli.md +39 -0
  7. package/_agents/docs/common-mistakes.md +49 -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 +22 -0
  12. package/dist/check/check-agent-docs.js +254 -0
  13. package/dist/cli/run.d.ts +24 -0
  14. package/dist/cli/run.js +131 -0
  15. package/dist/consts.d.ts +16 -0
  16. package/dist/consts.js +16 -0
  17. package/dist/core/config.d.ts +31 -0
  18. package/dist/core/config.js +69 -0
  19. package/dist/core/errors.d.ts +17 -0
  20. package/dist/core/errors.js +21 -0
  21. package/dist/core/files.d.ts +28 -0
  22. package/dist/core/files.js +67 -0
  23. package/dist/core/json.d.ts +26 -0
  24. package/dist/core/json.js +44 -0
  25. package/dist/core/package-manifest.d.ts +36 -0
  26. package/dist/core/package-manifest.js +45 -0
  27. package/dist/defaults.d.ts +26 -0
  28. package/dist/defaults.js +14 -0
  29. package/dist/exports/entry-points.d.ts +30 -0
  30. package/dist/exports/entry-points.js +119 -0
  31. package/dist/exports/export-index.d.ts +44 -0
  32. package/dist/exports/export-index.js +233 -0
  33. package/dist/exports/module-source.d.ts +74 -0
  34. package/dist/exports/module-source.js +161 -0
  35. package/dist/exports/scan.d.ts +29 -0
  36. package/dist/exports/scan.js +156 -0
  37. package/dist/exports/summary.d.ts +36 -0
  38. package/dist/exports/summary.js +84 -0
  39. package/dist/index.d.ts +16 -0
  40. package/dist/index.js +16 -0
  41. package/dist/llms/identity.d.ts +21 -0
  42. package/dist/llms/identity.js +67 -0
  43. package/dist/llms/plan.d.ts +53 -0
  44. package/dist/llms/plan.js +318 -0
  45. package/dist/llms/sync.d.ts +16 -0
  46. package/dist/llms/sync.js +36 -0
  47. package/dist/markdown/anchors.d.ts +35 -0
  48. package/dist/markdown/anchors.js +66 -0
  49. package/dist/markdown/page.d.ts +20 -0
  50. package/dist/markdown/page.js +57 -0
  51. package/llms.txt +42 -0
  52. package/package.json +65 -4
@@ -0,0 +1,318 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { BYTES_PER_KB, GENERATED_MARKER, LLMS_FILE, PACKAGE_NAME } from '../consts.js';
4
+ import { loadLlmsConfig } from '../core/config.js';
5
+ import { AgentDocsError } from '../core/errors.js';
6
+ import { compareWalkOrder, hasTypeScript, markdownFiles } from '../core/files.js';
7
+ import { readPackageManifest } from '../core/package-manifest.js';
8
+ import { LAYOUT_DEFAULTS, LIMIT_DEFAULTS } from '../defaults.js';
9
+ import { findEntryPoints } from '../exports/entry-points.js';
10
+ import { buildExportIndex } from '../exports/export-index.js';
11
+ import { describePage } from '../markdown/page.js';
12
+ import { packageIdentity } from './identity.js';
13
+ /** Where the export index went. */
14
+ export const ExportPlacement = {
15
+ /** The package has no TypeScript source, or `"exports": false` turned the index off. */
16
+ None: 'none',
17
+ /** One `##` section per entry point, inside llms.txt. */
18
+ Inline: 'inline',
19
+ /** One generated page per entry point under the docs folder, which llms.txt links like any other page. */
20
+ Pages: 'pages',
21
+ };
22
+ const { exportsFolder, sourceDir, topLevelSection } = LAYOUT_DEFAULTS;
23
+ /** Stands in for a ` (part N of M)` title suffix while a page's parts are still being counted. */
24
+ const PART_SUFFIX_ROOM = ' (part 99 of 99)';
25
+ /**
26
+ * Works out llms.txt, and the export pages when there are any, without writing anything.
27
+ *
28
+ * @param options - The package root, and an optional base URL and limits.
29
+ * @returns The files to write and the ones to delete.
30
+ * @throws {@link AgentDocsError} With one line per problem: a page with no title or summary, a missing manifest
31
+ * field, an export that can't be traced, or a result over the size limit.
32
+ *
33
+ * @remarks
34
+ * Each page in the docs folder becomes one link, under `## Docs` or a section named after its subfolder. When the
35
+ * package has TypeScript in `src/`, each package.json `exports` entry adds a `## Exports: <import path>` section.
36
+ * If that would take llms.txt over `llmsLimitKb`, the sections become generated pages in `<docsDir>/exports/`
37
+ * instead, and llms.txt links them.
38
+ */
39
+ export function planLlms(options) {
40
+ const { root, baseUrl } = options;
41
+ const { llmsLimitKb, pageLimitKb } = { ...LIMIT_DEFAULTS, ...options.limits };
42
+ const config = loadLlmsConfig(root);
43
+ const manifest = readPackageManifest(root);
44
+ const identity = packageIdentity(root, config);
45
+ const entries = exportIndexFor(root, config, manifest);
46
+ const generatedDir = `${config.docsDir}/${exportsFolder}`;
47
+ const { pages, previouslyGenerated } = readPages(root, config, generatedDir, entries.length > 0);
48
+ const hasExports = entries.length > 0;
49
+ const intro = introLines(identity.title, config.docsDir, hasExports, manifest);
50
+ const head = [`# ${identity.title}`, '', `> ${identity.summary}`, ''];
51
+ if (baseUrl) {
52
+ head.push(`Base URL: ${baseUrl}`, '');
53
+ }
54
+ head.push(...intro);
55
+ const render = (linked, inline) => {
56
+ const out = [...head, ...pageSections(linked, config)];
57
+ for (const entry of inline) {
58
+ out.push(`## ${entryTitle(entry)}`, '', ...(entry.summary ? [entry.summary, ''] : []), ...exportLines(entry), '');
59
+ }
60
+ if (config.extra) {
61
+ out.push(config.extra.trim(), '');
62
+ }
63
+ return out.join('\n');
64
+ };
65
+ const limitBytes = llmsLimitKb * BYTES_PER_KB;
66
+ const inlined = render(pages, entries);
67
+ const fitsInline = Buffer.byteLength(inlined) <= limitBytes;
68
+ const undocumented = entries.flatMap((entry) => entry.exports.filter((e) => e.summary === '').map((e) => `${e.name} (${entry.importPath})`));
69
+ if (hasExports === false || fitsInline) {
70
+ return {
71
+ files: [{ path: LLMS_FILE, content: inlined }],
72
+ obsolete: previouslyGenerated,
73
+ placement: hasExports ? ExportPlacement.Inline : ExportPlacement.None,
74
+ undocumented,
75
+ };
76
+ }
77
+ const pageLimitBytes = pageLimitKb * BYTES_PER_KB;
78
+ const generated = entries.flatMap((entry, index) => entryPages(entry, generatedDir, index + 1, pageLimitBytes));
79
+ const problems = generated.flatMap((page) => {
80
+ const clashes = pages.some((existing) => existing.path === page.path);
81
+ const size = Buffer.byteLength(page.text);
82
+ return [
83
+ ...(clashes
84
+ ? [`${page.path} was written by hand, where the export index goes: move it out of ${generatedDir}/.`]
85
+ : []),
86
+ ...(size > pageLimitBytes
87
+ ? [
88
+ `${page.path} would be ${Math.round(size / BYTES_PER_KB)} KB, over ${pageLimitKb} KB: shorten the first sentence of its longest doc comments.`,
89
+ ]
90
+ : []),
91
+ ];
92
+ });
93
+ const linked = [...pages, ...generated].sort((a, b) => compareWalkOrder(a.path, b.path));
94
+ const content = render(linked, []);
95
+ const size = Buffer.byteLength(content);
96
+ if (size > limitBytes) {
97
+ problems.push(`${LLMS_FILE} would be ${Math.round(size / BYTES_PER_KB)} KB, over ${llmsLimitKb} KB even with the export index on its own pages: shorten the page summaries or merge small pages.`);
98
+ }
99
+ if (problems.length > 0) {
100
+ throw new AgentDocsError(problems);
101
+ }
102
+ const generatedPaths = new Set(generated.map((page) => page.path));
103
+ return {
104
+ files: [{ path: LLMS_FILE, content }, ...generated.map((page) => ({ path: page.path, content: page.text }))],
105
+ obsolete: previouslyGenerated.filter((path) => generatedPaths.has(path) === false),
106
+ placement: ExportPlacement.Pages,
107
+ undocumented,
108
+ };
109
+ }
110
+ /**
111
+ * The export index, when the package has TypeScript source and the config leaves it on.
112
+ *
113
+ * @param root - Package root.
114
+ * @param config - `_agents/llms.json`.
115
+ * @param manifest - package.json, if any.
116
+ * @returns One index per entry point; empty when there is nothing to index.
117
+ * @throws {@link AgentDocsError} If an entry point or a re-export can't be traced to its source.
118
+ */
119
+ function exportIndexFor(root, config, manifest) {
120
+ const isIndexed = config.exports && manifest?.name !== undefined && hasTypeScript(root, sourceDir);
121
+ if (isIndexed === false || manifest?.name === undefined) {
122
+ return [];
123
+ }
124
+ const { entries, problems } = findEntryPoints(root, manifest.name, manifest.exports);
125
+ if (problems.length > 0) {
126
+ throw new AgentDocsError(problems);
127
+ }
128
+ return buildExportIndex(root, entries);
129
+ }
130
+ /**
131
+ * The pages on disk, apart from the export pages a previous run generated.
132
+ *
133
+ * @param root - Package root.
134
+ * @param config - `_agents/llms.json`, for the docs folder.
135
+ * @param generatedDir - Where generated export pages live.
136
+ * @param mayBeEmpty - Whether a missing docs folder is allowed, as it is when the export index fills llms.txt.
137
+ * @returns The hand-written pages and the paths of the generated ones.
138
+ * @throws {@link AgentDocsError} If the docs folder is missing and nothing else would fill llms.txt.
139
+ */
140
+ function readPages(root, config, generatedDir, mayBeEmpty) {
141
+ const paths = markdownFiles(root, config.docsDir);
142
+ const isMissing = paths.length === 0 && mayBeEmpty === false;
143
+ if (isMissing) {
144
+ throw new AgentDocsError([`${config.docsDir}/ has no pages: write the agent docs there first.`]);
145
+ }
146
+ const pages = [];
147
+ const previouslyGenerated = [];
148
+ for (const path of paths) {
149
+ const text = readFileSync(join(root, path), 'utf8');
150
+ const isGenerated = path.startsWith(`${generatedDir}/`) && text.startsWith(GENERATED_MARKER);
151
+ if (isGenerated) {
152
+ previouslyGenerated.push(path);
153
+ }
154
+ else {
155
+ pages.push({ path, text });
156
+ }
157
+ }
158
+ return { pages, previouslyGenerated };
159
+ }
160
+ /**
161
+ * The `##` sections that link the pages: top-level pages under `## Docs`, each subfolder under its own heading.
162
+ *
163
+ * @param pages - Pages in walk order.
164
+ * @param config - `_agents/llms.json`, for the docs folder and the section names.
165
+ * @returns The lines, each section followed by a blank line.
166
+ * @throws {@link AgentDocsError} With a line for each page that has no title or no summary.
167
+ */
168
+ function pageSections(pages, config) {
169
+ const sections = new Map();
170
+ const problems = [];
171
+ for (const { path, text } of pages) {
172
+ const folders = path
173
+ .slice(config.docsDir.length + 1)
174
+ .split('/')
175
+ .slice(0, -1);
176
+ const heading = folders.length > 0 ? folderHeading(folders[0], config) : topLevelSection;
177
+ try {
178
+ const { title, note } = describePage(path, text);
179
+ sections.set(heading, [...(sections.get(heading) ?? []), `- [${title}](${path}): ${note}`]);
180
+ }
181
+ catch (error) {
182
+ if (error instanceof AgentDocsError) {
183
+ problems.push(...error.problems);
184
+ }
185
+ else {
186
+ throw error;
187
+ }
188
+ }
189
+ }
190
+ if (problems.length > 0) {
191
+ throw new AgentDocsError(problems);
192
+ }
193
+ return [...sections].flatMap(([heading, links]) => [`## ${heading}`, '', ...links, '']);
194
+ }
195
+ /**
196
+ * Turns a folder name into a heading: `getting-started` → `Getting started`.
197
+ *
198
+ * @param folder - The subfolder's name.
199
+ * @param config - `_agents/llms.json`, whose `sections` names win.
200
+ * @returns The heading text.
201
+ */
202
+ function folderHeading(folder, config) {
203
+ const named = config.sections[folder];
204
+ if (named) {
205
+ return named;
206
+ }
207
+ const words = folder.replace(/^\d+[-_]/, '').replace(/[-_]/g, ' ');
208
+ return words.charAt(0).toUpperCase() + words.slice(1);
209
+ }
210
+ /**
211
+ * The paragraph under the summary that says what llms.txt indexes and where it comes from.
212
+ *
213
+ * @param title - The package's title.
214
+ * @param docsDir - The docs folder.
215
+ * @param hasExports - Whether the export index is part of it.
216
+ * @param manifest - package.json, for the Node range and peers.
217
+ * @returns The lines, each paragraph followed by a blank line.
218
+ */
219
+ function introLines(title, docsDir, hasExports, manifest) {
220
+ if (hasExports === false) {
221
+ return [
222
+ `Agent-facing docs for ${title}, one task or concept per page. Generated from ${docsDir}/ by ${PACKAGE_NAME}; edit the pages, not this file.`,
223
+ '',
224
+ ];
225
+ }
226
+ const lines = [
227
+ `Agent-facing docs for ${title}: one task or concept per page, then what each package.json "exports" entry exports. Generated from ${docsDir}/ and the doc comments in ${sourceDir}/ by ${PACKAGE_NAME}; edit those, not this file.`,
228
+ '',
229
+ ];
230
+ const requirements = [];
231
+ if (manifest?.nodeRange) {
232
+ requirements.push(`Requires Node ${manifest.nodeRange}.`);
233
+ }
234
+ const peers = (manifest?.peers ?? []).map((peer) => `\`${peer.name}\` ${peer.range}${peer.isOptional ? ' (optional)' : ''}`);
235
+ if (peers.length > 0) {
236
+ requirements.push(`Peer dependencies: ${peers.join(', ')}.`);
237
+ }
238
+ if (requirements.length > 0) {
239
+ lines.push(requirements.join(' '), '');
240
+ }
241
+ return lines;
242
+ }
243
+ /**
244
+ * The heading an entry point's exports go under.
245
+ *
246
+ * @param entry - One entry's index.
247
+ * @returns `Exports: <import path>`.
248
+ */
249
+ function entryTitle(entry) {
250
+ return `Exports: ${entry.importPath}`;
251
+ }
252
+ /**
253
+ * One list line per export, then one per package the entry re-exports from.
254
+ *
255
+ * @param entry - One entry's index.
256
+ * @returns The lines.
257
+ */
258
+ function exportLines(entry) {
259
+ const own = entry.exports.map((item) => {
260
+ const label = item.isType ? `\`${item.name}\` (type)` : `\`${item.name}\``;
261
+ return item.summary ? `- ${label}: ${item.summary}` : `- ${label}`;
262
+ });
263
+ const foreign = entry.foreign.map((item) => {
264
+ const names = item.names.includes('*') ? 'everything it exports' : item.names.map((n) => `\`${n}\``).join(', ');
265
+ return `- Re-exported unchanged from \`${item.specifier}\`, which documents them: ${names}.`;
266
+ });
267
+ return [...own, ...foreign];
268
+ }
269
+ /**
270
+ * The file name stem of an entry's generated page.
271
+ *
272
+ * @param entry - One entry's index.
273
+ * @returns `index` for the root entry, else the subpath with `/` turned to `-`.
274
+ */
275
+ function entryFileStem(entry) {
276
+ const subpath = entry.importPath.split('/').slice(entry.importPath.startsWith('@') ? 2 : 1);
277
+ return subpath.length === 0 ? 'index' : subpath.join('-').replace(/[^\w.-]+/g, '-');
278
+ }
279
+ /**
280
+ * The generated pages for one entry point: one page, or numbered parts when one would pass the page limit.
281
+ *
282
+ * @param entry - One entry's index.
283
+ * @param generatedDir - Where generated pages go.
284
+ * @param position - The entry's 1-based place in `exports`, which prefixes its file names.
285
+ * @param limitBytes - The largest a page may be.
286
+ * @returns The pages, each starting with the generated marker.
287
+ */
288
+ function entryPages(entry, generatedDir, position, limitBytes) {
289
+ const stem = `${generatedDir}/${String(position).padStart(2, '0')}-${entryFileStem(entry)}`;
290
+ const summary = entry.summary || `What \`${entry.importPath}\` exports, with the first sentence of each doc comment.`;
291
+ const page = (title, lines) => [
292
+ `${GENERATED_MARKER} from ${entry.source}; edit its doc comments, not this page. -->`,
293
+ `# ${title}`,
294
+ '',
295
+ summary,
296
+ '',
297
+ ...lines,
298
+ '',
299
+ ].join('\n');
300
+ const parts = [[]];
301
+ for (const line of exportLines(entry)) {
302
+ const current = parts[parts.length - 1];
303
+ const wouldOverflow = Buffer.byteLength(page(`${entryTitle(entry)}${PART_SUFFIX_ROOM}`, [...current, line])) > limitBytes;
304
+ if (wouldOverflow && current.length > 0) {
305
+ parts.push([line]);
306
+ }
307
+ else {
308
+ current.push(line);
309
+ }
310
+ }
311
+ if (parts.length === 1) {
312
+ return [{ path: `${stem}.md`, text: page(entryTitle(entry), parts[0]) }];
313
+ }
314
+ return parts.map((lines, index) => ({
315
+ path: `${stem}-${index + 1}.md`,
316
+ text: page(`${entryTitle(entry)} (part ${index + 1} of ${parts.length})`, lines),
317
+ }));
318
+ }
@@ -0,0 +1,16 @@
1
+ import type { LlmsPlan } from './plan.ts';
2
+ /**
3
+ * Writes a plan's files and deletes the export pages it no longer generates.
4
+ *
5
+ * @param root - Package root.
6
+ * @param plan - What {@link planLlms} worked out for the same root.
7
+ */
8
+ export declare function writeLlms(root: string, plan: LlmsPlan): void;
9
+ /**
10
+ * Compares a plan with the files on disk, for CI.
11
+ *
12
+ * @param root - Package root.
13
+ * @param plan - What {@link planLlms} worked out for the same root.
14
+ * @returns One line per file that is missing, differs, or should have been deleted; empty when all match.
15
+ */
16
+ export declare function findStaleFiles(root: string, plan: LlmsPlan): string[];
@@ -0,0 +1,36 @@
1
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { LLMS_COMMAND } from '../consts.js';
4
+ /**
5
+ * Writes a plan's files and deletes the export pages it no longer generates.
6
+ *
7
+ * @param root - Package root.
8
+ * @param plan - What {@link planLlms} worked out for the same root.
9
+ */
10
+ export function writeLlms(root, plan) {
11
+ for (const { path, content } of plan.files) {
12
+ const full = join(root, path);
13
+ mkdirSync(dirname(full), { recursive: true });
14
+ writeFileSync(full, content);
15
+ }
16
+ for (const path of plan.obsolete) {
17
+ rmSync(join(root, path), { force: true });
18
+ }
19
+ }
20
+ /**
21
+ * Compares a plan with the files on disk, for CI.
22
+ *
23
+ * @param root - Package root.
24
+ * @param plan - What {@link planLlms} worked out for the same root.
25
+ * @returns One line per file that is missing, differs, or should have been deleted; empty when all match.
26
+ */
27
+ export function findStaleFiles(root, plan) {
28
+ const stale = plan.files
29
+ .filter(({ path, content }) => {
30
+ const full = join(root, path);
31
+ return existsSync(full) === false || readFileSync(full, 'utf8') !== content;
32
+ })
33
+ .map(({ path }) => `${path} is stale or missing: run "${LLMS_COMMAND}" and commit it.`);
34
+ const leftover = plan.obsolete.map((path) => `${path} is no longer generated: run "${LLMS_COMMAND}" to delete it, and commit that.`);
35
+ return [...stale, ...leftover];
36
+ }
@@ -0,0 +1,35 @@
1
+ /** A heading as a link can target it. */
2
+ export interface Heading {
3
+ /** Number of `#` marks, 1 to 6. */
4
+ level: number;
5
+ /** GitHub's anchor for it, with the `-1` suffix a repeat gets. */
6
+ anchor: string;
7
+ }
8
+ /**
9
+ * GitHub's heading anchor: lower case, punctuation dropped, spaces to hyphens.
10
+ *
11
+ * @param heading - Heading text without its `#` marks.
12
+ * @returns The anchor without `#`; underscores and hyphens are kept.
13
+ */
14
+ export declare function slug(heading: string): string;
15
+ /**
16
+ * The lines of a markdown text that sit outside code fences.
17
+ *
18
+ * @param text - Markdown source.
19
+ * @returns The lines in order, fence lines themselves left out.
20
+ */
21
+ export declare function proseLines(text: string): string[];
22
+ /**
23
+ * Every heading outside code fences, anchored the way GitHub anchors them.
24
+ *
25
+ * @param text - Markdown source.
26
+ * @returns The headings in order.
27
+ */
28
+ export declare function headings(text: string): Heading[];
29
+ /**
30
+ * Link targets outside code fences and code spans.
31
+ *
32
+ * @param text - Markdown source.
33
+ * @returns Each `](target)` target, in order.
34
+ */
35
+ export declare function links(text: string): string[];
@@ -0,0 +1,66 @@
1
+ const FENCE = /^\s*```/;
2
+ const HEADING = /^(#{1,6}) (.*)$/;
3
+ const LINK_TARGET = /\]\(([^)\s]+)\)/g;
4
+ const CODE_SPAN = /`[^`]*`/g;
5
+ /**
6
+ * GitHub's heading anchor: lower case, punctuation dropped, spaces to hyphens.
7
+ *
8
+ * @param heading - Heading text without its `#` marks.
9
+ * @returns The anchor without `#`; underscores and hyphens are kept.
10
+ */
11
+ export function slug(heading) {
12
+ return heading
13
+ .trim()
14
+ .toLowerCase()
15
+ .replace(/`/g, '')
16
+ .replace(/[^\p{L}\p{N}\s_-]/gu, '')
17
+ .replace(/\s/g, '-');
18
+ }
19
+ /**
20
+ * The lines of a markdown text that sit outside code fences.
21
+ *
22
+ * @param text - Markdown source.
23
+ * @returns The lines in order, fence lines themselves left out.
24
+ */
25
+ export function proseLines(text) {
26
+ const out = [];
27
+ let isFenced = false;
28
+ for (const line of text.split('\n')) {
29
+ if (FENCE.test(line)) {
30
+ isFenced = isFenced === false;
31
+ continue;
32
+ }
33
+ if (isFenced === false) {
34
+ out.push(line);
35
+ }
36
+ }
37
+ return out;
38
+ }
39
+ /**
40
+ * Every heading outside code fences, anchored the way GitHub anchors them.
41
+ *
42
+ * @param text - Markdown source.
43
+ * @returns The headings in order.
44
+ */
45
+ export function headings(text) {
46
+ const seen = new Map();
47
+ return proseLines(text).flatMap((line) => {
48
+ const match = line.match(HEADING);
49
+ if (match === null) {
50
+ return [];
51
+ }
52
+ const base = slug(match[2]);
53
+ const count = seen.get(base) ?? 0;
54
+ seen.set(base, count + 1);
55
+ return [{ level: match[1].length, anchor: count === 0 ? base : `${base}-${count}` }];
56
+ });
57
+ }
58
+ /**
59
+ * Link targets outside code fences and code spans.
60
+ *
61
+ * @param text - Markdown source.
62
+ * @returns Each `](target)` target, in order.
63
+ */
64
+ export function links(text) {
65
+ return proseLines(text).flatMap((line) => [...line.replace(CODE_SPAN, '``').matchAll(LINK_TARGET)].map((match) => match[1]));
66
+ }
@@ -0,0 +1,20 @@
1
+ /** What llms.txt says about one page. */
2
+ export interface PageSummary {
3
+ /** The page's `# H1`, the link text. */
4
+ title: string;
5
+ /** The first plain paragraph under it, on one line with its links reduced to their text. */
6
+ note: string;
7
+ }
8
+ /**
9
+ * Reads a page's title and its one-paragraph summary.
10
+ *
11
+ * @param path - The page's path, for messages.
12
+ * @param text - The page's markdown.
13
+ * @returns The title and the note.
14
+ * @throws {@link AgentDocsError} If the page has no `# Title` line or no paragraph under it.
15
+ *
16
+ * @remarks
17
+ * HTML comments, code fences, lists, quotes, tables and headings are skipped on the way to the paragraph.
18
+ * Links become their text, because a relative link from a page breaks once copied into llms.txt.
19
+ */
20
+ export declare function describePage(path: string, text: string): PageSummary;
@@ -0,0 +1,57 @@
1
+ import { AgentDocsError } from '../core/errors.js';
2
+ const H1 = /^# \S/;
3
+ const NOT_PROSE = /^(#|>|[-*|]|\d+\.|<|```)/;
4
+ const MARKDOWN_LINK = /\[([^\]]+)\]\([^)]*\)/g;
5
+ /**
6
+ * Reads a page's title and its one-paragraph summary.
7
+ *
8
+ * @param path - The page's path, for messages.
9
+ * @param text - The page's markdown.
10
+ * @returns The title and the note.
11
+ * @throws {@link AgentDocsError} If the page has no `# Title` line or no paragraph under it.
12
+ *
13
+ * @remarks
14
+ * HTML comments, code fences, lists, quotes, tables and headings are skipped on the way to the paragraph.
15
+ * Links become their text, because a relative link from a page breaks once copied into llms.txt.
16
+ */
17
+ export function describePage(path, text) {
18
+ const lines = text.split('\n');
19
+ const h1Index = lines.findIndex((line) => H1.test(line));
20
+ if (h1Index === -1) {
21
+ throw new AgentDocsError([`${path} has no "# Title" line: start the page with one.`]);
22
+ }
23
+ const title = lines[h1Index].slice(2).trim();
24
+ const paragraph = [];
25
+ let inFence = false;
26
+ let inComment = false;
27
+ for (const line of lines.slice(h1Index + 1)) {
28
+ if (line.startsWith('```')) {
29
+ inFence = inFence === false;
30
+ }
31
+ const opensComment = inFence === false && line.includes('<!--');
32
+ if (opensComment) {
33
+ inComment = true;
34
+ }
35
+ if (inComment) {
36
+ if (line.includes('-->')) {
37
+ inComment = false;
38
+ }
39
+ if (paragraph.length > 0) {
40
+ break;
41
+ }
42
+ continue;
43
+ }
44
+ const trimmed = line.trim();
45
+ const isProse = inFence === false && trimmed !== '' && NOT_PROSE.test(trimmed) === false;
46
+ if (isProse) {
47
+ paragraph.push(trimmed);
48
+ }
49
+ else if (paragraph.length > 0) {
50
+ break;
51
+ }
52
+ }
53
+ if (paragraph.length === 0) {
54
+ throw new AgentDocsError([`${path} needs a one-paragraph summary under its title.`]);
55
+ }
56
+ return { title, note: paragraph.join(' ').replace(MARKDOWN_LINK, '$1') };
57
+ }
package/llms.txt ADDED
@@ -0,0 +1,42 @@
1
+ # @cubicecho/agent-docs
2
+
3
+ > Generates and checks the agent docs a package ships: llms.txt from _agents/docs/ pages and each package export's doc comments, and the checks that keep README, AGENTS.md and the package contents to the standard.
4
+
5
+ Agent-facing docs for @cubicecho/agent-docs: one task or concept per page, then what each package.json "exports" entry exports. Generated from _agents/docs/ and the doc comments in src/ by @cubicecho/agent-docs; edit those, not this file.
6
+
7
+ Requires Node >=22.
8
+
9
+ ## Docs
10
+
11
+ - [Install and wire up](_agents/docs/01-install.md): Add `@cubicecho/agent-docs` as a dev dependency, then give the package three npm scripts: `llms` writes `llms.txt`, `llms:check` fails when it is stale, and `docs:check` checks the rest of the agent docs standard.
12
+ - [What check enforces](_agents/docs/checks.md): `agent-docs check` holds a package to nine rules and prints one line per broken one, saying what to change. A private workspace root (`private: true` with `workspaces`) is held to the repo-level rules only: links, CLAUDE.md and `.agents/`.
13
+ - [CI](_agents/docs/ci.md): Run `llms --check` and `check` wherever the repo already runs its checks, and check what `npm pack` would ship after the build.
14
+ - [The agent-docs command](_agents/docs/cli.md): `agent-docs llms` writes or checks `llms.txt`, and `agent-docs check` checks the package against the agent docs standard. Each prints one line per problem and exits 1 when there is any; otherwise it exits 0.
15
+ - [Common mistakes](_agents/docs/common-mistakes.md): The mistakes that make `llms` or `check` fail, or let a stale index through, each with its fix.
16
+ - [_agents/llms.json](_agents/docs/config.md): `_agents/llms.json` is the optional overrides file both commands read; without it, every field takes its default.
17
+
18
+ ## Exports: @cubicecho/agent-docs
19
+
20
+ Generates and checks the agent docs a package ships.
21
+
22
+ - `CheckResult` (type): What checkAgentDocs found.
23
+ - `checkAgentDocs`: Checks a package against the agent documentation standard, changing nothing.
24
+ - `CliOutput` (type): Where the CLI prints.
25
+ - `ExitCode`: The process exit codes the CLI returns.
26
+ - `runCli`: Runs one CLI command against a package.
27
+ - `LlmsConfig` (type): `_agents/llms.json`, the overrides both commands share, with its defaults filled in.
28
+ - `loadLlmsConfig`: Reads `_agents/llms.json`, or the defaults when it is absent.
29
+ - `AgentDocsError`: The docs or the package can't be read or generated as they stand.
30
+ - `LAYOUT_DEFAULTS`: The layout the agent docs standard and the cubicecho build use.
31
+ - `LayoutSettings` (type): Where the docs and the source they index are found.
32
+ - `LIMIT_DEFAULTS`: The limits the agent docs standard sets.
33
+ - `LimitSettings` (type): The size limits both commands hold the docs to.
34
+ - `firstSentence`: The first sentence of a paragraph.
35
+ - `summarize`: The one-line summary a doc comment gives the index.
36
+ - `ExportPlacement`: Where the export index went.
37
+ - `GeneratedFile` (type): One file the plan writes.
38
+ - `LlmsOptions` (type): What planLlms reads.
39
+ - `LlmsPlan` (type): Everything one run of `llms` writes, before anything is written.
40
+ - `planLlms`: Works out llms.txt, and the export pages when there are any, without writing anything.
41
+ - `findStaleFiles`: Compares a plan with the files on disk, for CI.
42
+ - `writeLlms`: Writes a plan's files and deletes the export pages it no longer generates.
package/package.json CHANGED
@@ -1,6 +1,67 @@
1
1
  {
2
2
  "name": "@cubicecho/agent-docs",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Generates and checks the agent docs a package ships: llms.txt from _agents/docs/ pages and each package export's doc comments, and the checks that keep README, AGENTS.md and the package contents to the standard.",
5
+ "keywords": [
6
+ "llms.txt",
7
+ "agents",
8
+ "documentation",
9
+ "tsdoc",
10
+ "ci",
11
+ "typescript"
12
+ ],
13
+ "license": "MIT",
14
+ "author": "Benjamin Van Treese <vantreeseba@gmail.com>",
15
+ "type": "module",
16
+ "engines": {
17
+ "node": ">=22"
18
+ },
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/cubicecho/agent-docs.git"
22
+ },
23
+ "homepage": "https://github.com/cubicecho/agent-docs#readme",
24
+ "bugs": {
25
+ "url": "https://github.com/cubicecho/agent-docs/issues"
26
+ },
27
+ "bin": {
28
+ "agent-docs": "dist/bin.js"
29
+ },
30
+ "exports": {
31
+ ".": {
32
+ "types": "./dist/index.d.ts",
33
+ "import": "./dist/index.js"
34
+ }
35
+ },
36
+ "files": [
37
+ "dist",
38
+ "llms.txt",
39
+ "_agents/docs"
40
+ ],
41
+ "publishConfig": {
42
+ "access": "public"
43
+ },
44
+ "scripts": {
45
+ "build": "tsc -p tsconfig.build.json",
46
+ "prepack": "npm run build",
47
+ "check": "npm run check:biome && npm run check:types && npm run llms:check && npm run docs:check",
48
+ "check:biome": "biome check --write .",
49
+ "check:types": "tsc --noEmit",
50
+ "test": "vitest run",
51
+ "test:watch": "vitest",
52
+ "llms": "node src/bin.ts llms",
53
+ "llms:check": "node src/bin.ts llms --check",
54
+ "docs:check": "node src/bin.ts check",
55
+ "coverage": "vitest run --coverage"
56
+ },
57
+ "devDependencies": {
58
+ "@biomejs/biome": "2.5.12",
59
+ "@semantic-release/changelog": "^7.0.0",
60
+ "@semantic-release/git": "^11.0.1",
61
+ "@types/node": "^26.6.11",
62
+ "@vitest/coverage-v8": "^4.1.12",
63
+ "semantic-release": "^25.0.9",
64
+ "typescript": "^7.0.2",
65
+ "vitest": "^4.1.12"
66
+ }
67
+ }