Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,10 @@ goals. Things worth discussing up front:
### Scoring changes

`SCORING.md` carries a scoring version, separate from the package version and
the spec version. Bump it whenever a change alters what a site would score
without the site changing:
the spec version. The same version is the `SCORING_VERSION` constant in
`src/constants.ts`, which reports carry as `scoring.scoringVersion`; a test
fails if the two differ. Bump both whenever a change alters what a site would
score without the site changing:

- adding or removing a check (the denominator changes)
- changing a weight tier, warn coefficient, threshold, cap, or the formula
Expand Down
2 changes: 1 addition & 1 deletion docs/reference/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ While a run is in progress, each check writes a numbered progress line to stderr

- **`text`** is the default. Shows per-check pass/warn/fail/skip results. Add `--verbose` for per-page details and `--fixes` for fix suggestions. Useful when iterating on individual check fixes.
- **`scorecard`** includes the overall score, per-category scores, interaction diagnostics, and fix suggestions for every failing check. This is the best starting point for understanding your site's agent-friendliness.
- **`json`** produces machine-readable output for scripting and automation. Add `--score` to include scoring data and fix suggestions.
- **`json`** produces machine-readable output for scripting and automation. Add `--score` to include scoring data and fix suggestions. Alongside the `results` array, the report includes a `checkDefinitions` map (each check's description and spec link, keyed by check ID) and a `categories` map (each category's display name, keyed by category ID), so dashboards built on the JSON can label checks without a hardcoded list. The report also records the `afdocsVersion` and `specVersion` that produced it, and with `--score`, `scoring.scoringVersion`. See [Label checks and categories](/reference/programmatic-api#label-checks-and-categories).

### Config file

Expand Down
68 changes: 68 additions & 0 deletions docs/reference/programmatic-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,58 @@ for (const result of report.results) {

- `url` — the URL that was checked
- `timestamp` — when the check ran
- `afdocsVersion` — the version of AFDocs that produced the report (e.g. `0.23.0`)
- `specVersion` — the version of the [Agent-Friendly Documentation Spec](https://agentdocsspec.com/spec/web/) the checks implement (e.g. `v0.6.0`)
- `results` — array of `CheckResult` objects (one per check)
- `summary` — counts by status (pass, warn, fail, skip, error)
- `checkDefinitions` — what each check in `results` looks for, keyed by check ID: a one-sentence `description` and the `specUrl` of the check's section in the spec. See [Label checks and categories](#label-checks-and-categories)
- `categories` — the display `name` and sort `order` of each category that appears in `results`, keyed by category ID
- `testedPages` — number of pages tested by page-level checks (present when page discovery ran)
- `samplingStrategy` — the sampling strategy used (`random`, `deterministic`, `curated`, or `none`)
- `requestSummary` — aggregate of every HTTP request the run made: `requests`, `stalledBodies`, `challengePages`, `fetchErrors`, `failed`, and `failureRate` (0–100). Feeds the [bot protection scan-reliability diagnostic](/interaction-diagnostics#bot-protection-degrading-scan-reliability)
- `networkContext` — where the scan ran from: `developer-machine`, `ci`, or `cloud`, with `source` set to `environment` (classified from environment variables, with the `indicator` variable that matched) or `option` (the `networkContext` runner option). Never includes an IP address

## Label checks and categories

Each entry in `results` identifies its check and category by ID (`markdown-url-support`, `markdown-availability`). The report carries the human-readable text for those IDs in two maps, so a dashboard or custom report doesn't need its own hardcoded list:

```json
{
"results": [
{
"id": "markdown-url-support",
"category": "markdown-availability",
"status": "pass",
"message": "..."
}
],
"checkDefinitions": {
"markdown-url-support": {
"description": "Whether appending .md to page URLs returns valid markdown",
"specUrl": "https://agentdocsspec.com/spec/web/markdown-availability/#markdown-url-support"
}
},
"categories": {
"markdown-availability": { "name": "Markdown Availability", "order": 2 }
}
}
```

Look up each result's `id` in `checkDefinitions` and its `category` in `categories`:

```ts
const rows = report.results.map((result) => ({
...result,
description: report.checkDefinitions?.[result.id]?.description,
specUrl: report.checkDefinitions?.[result.id]?.specUrl,
categoryName: report.categories?.[result.category]?.name,
}));
```

Both maps describe exactly the checks and categories in `results`. A run limited with `checkIds` gets a correspondingly smaller map, and checks that were skipped are included because they still appear in `results`. The same maps appear in the CLI's `--format json` output.

These fields, along with `afdocsVersion` and `specVersion`, are optional in the `ReportResult` type. Reports saved by AFDocs versions before these fields were added don't have them, so code that reads stored reports should handle their absence.

## Run with options

Pass a second argument to configure sampling, concurrency, and thresholds:
Expand Down Expand Up @@ -129,6 +174,27 @@ for (const check of sorted) {
}
```

## List categories

`CATEGORIES` lists every check category in display order. Each entry has the category `id` that check results and definitions refer to, a human-readable `name`, and a 1-based `order`:

```ts
import { CATEGORIES } from 'afdocs';

for (const category of CATEGORIES) {
console.log(`${category.order}. ${category.name} (${category.id})`);
}
// 1. Content Discoverability (content-discoverability)
// 2. Markdown Availability (markdown-availability)
// 3. Page Size and Truncation Risk (page-size)
// 4. Content Structure (content-structure)
// 5. URL Stability and Redirects (url-stability)
// 6. Observability and Content Health (observability)
// 7. Authentication and Access (authentication)
```

Use `getAllChecks` and `CATEGORIES` when you need the full catalog. To label the results of one run, the [maps on the report](#label-checks-and-categories) are simpler.

## Validate options

Both `runChecks` and `createContext` validate options and throw on invalid input. If you want to check options before calling either function (for example, to show validation errors in a UI or dry-run mode), use `validateRunnerOptions`:
Expand Down Expand Up @@ -174,6 +240,8 @@ import type {
CheckResult,
CheckStatus, // 'pass' | 'warn' | 'fail' | 'skip' | 'error'
ReportResult,
CheckDefinitionInfo, // entry in report.checkDefinitions
CategoryInfo, // entry in report.categories
RunnerOptions,
CheckOptions,
CheckProgressEvent, // CheckProgressStartEvent | CheckProgressCompleteEvent
Expand Down
21 changes: 11 additions & 10 deletions docs/reference/scoring-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,16 +35,17 @@ This is the same function; the subpath is provided for consumers who want a narr

`computeScore` returns a `ScoreResult` with these fields:

| Field | Type | Description |
| ---------------- | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| `overall` | `number` | The overall score (0-100) |
| `grade` | `Grade` | Letter grade (`A+`, `A`, `B`, `C`, `D`, `F`) |
| `categoryScores` | `Record<string, CategoryScore>` | Per-category score and grade. `score` and `grade` are `null` when all checks in the category are `notApplicable` (insufficient data). |
| `checkScores` | `Record<string, CheckScore>` | Per-check scoring details (weight, coefficient, proportion, earned score, scoreDisplayMode) |
| `diagnostics` | `Diagnostic[]` | Interaction diagnostics that fired |
| `cap` | `ScoreCap` | Score cap that was applied (present only when a cap reduced the score) |
| `resolutions` | `Record<string, string>` | Fix suggestions keyed by check ID |
| `tagScores` | `Record<string, TagScore>` | Per-tag aggregate scores (present when curated pages have tags) |
| Field | Type | Description |
| ---------------- | ------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `scoringVersion` | `string` | The version of the [scoring method](/agent-score-calculation) that produced the score. Scores from different scoring versions are not comparable, so check this before comparing stored scores. |
| `overall` | `number` | The overall score (0-100) |
| `grade` | `Grade` | Letter grade (`A+`, `A`, `B`, `C`, `D`, `F`) |
| `categoryScores` | `Record<string, CategoryScore>` | Per-category score and grade. `score` and `grade` are `null` when all checks in the category are `notApplicable` (insufficient data). |
| `checkScores` | `Record<string, CheckScore>` | Per-check scoring details (weight, coefficient, proportion, earned score, scoreDisplayMode) |
| `diagnostics` | `Diagnostic[]` | Interaction diagnostics that fired |
| `cap` | `ScoreCap` | Score cap that was applied (present only when a cap reduced the score) |
| `resolutions` | `Record<string, string>` | Fix suggestions keyed by check ID |
| `tagScores` | `Record<string, TagScore>` | Per-tag aggregate scores (present when curated pages have tags) |

Each `CheckScore` includes a `scoreDisplayMode` field (`"numeric"` or `"notApplicable"`). When automatic page discovery finds fewer than 5 pages, page-level checks are marked `"notApplicable"` and excluded from overall and category score calculations. See [Insufficient data](/agent-score-calculation#insufficient-data) for details.

Expand Down
2 changes: 1 addition & 1 deletion src/checks/authentication/bot-protection-interference.ts
Original file line number Diff line number Diff line change
Expand Up @@ -365,7 +365,7 @@ registerCheck({
id: 'bot-protection-interference',
category: 'authentication',
description:
'Whether bot-protection systems interfere with automated fetching of documentation content',
'Whether bot-protection systems (CDN bot management, web application firewalls, rate limiting) interfered with fetching documentation during the run',
dependsOn: [],
run: check,
});
2 changes: 1 addition & 1 deletion src/checks/content-discoverability/llms-txt-exists.ts
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,7 @@ async function checkLlmsTxtExists(ctx: CheckContext): Promise<CheckResult> {
registerCheck({
id: 'llms-txt-exists',
category: 'content-discoverability',
description: 'Whether llms.txt is discoverable at any of the candidate locations',
description: 'Whether the site has an llms.txt file at a discoverable location',
dependsOn: [],
run: checkLlmsTxtExists,
});
3 changes: 2 additions & 1 deletion src/checks/content-structure/section-header-quality.ts
Original file line number Diff line number Diff line change
Expand Up @@ -380,7 +380,8 @@ async function check(ctx: CheckContext): Promise<CheckResult> {
registerCheck({
id: 'section-header-quality',
category: 'content-structure',
description: 'Whether headers in tabbed sections include variant context',
description:
'Whether headers in tabbed sections carry enough context to make sense without the surrounding UI',
// No hard dependency: we read from previousResults if available,
// but the check handles missing data gracefully (returns skip).
dependsOn: [],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ async function check(ctx: CheckContext): Promise<CheckResult> {
registerCheck({
id: 'tabbed-content-serialization',
category: 'content-structure',
description: 'Whether tabbed/accordion content serializes into oversized output',
description: 'Whether tabbed or accordion content becomes oversized output when serialized',
dependsOn: [],
run: check,
});
2 changes: 1 addition & 1 deletion src/checks/markdown-availability/content-negotiation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ async function check(ctx: CheckContext): Promise<CheckResult> {
registerCheck({
id: 'content-negotiation',
category: 'markdown-availability',
description: 'Whether the server responds to Accept: text/markdown',
description: 'Whether the server returns markdown when a request sends Accept: text/markdown',
dependsOn: [],
run: check,
});
3 changes: 2 additions & 1 deletion src/checks/observability/cache-header-hygiene.ts
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,8 @@ async function check(ctx: CheckContext): Promise<CheckResult> {
registerCheck({
id: 'cache-header-hygiene',
category: 'observability',
description: 'Whether cache headers allow timely updates',
description:
'Whether cache headers on llms.txt and sampled documentation pages allow timely updates',
dependsOn: [],
run: check,
});
2 changes: 1 addition & 1 deletion src/checks/page-size/content-start-position.ts
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,7 @@ async function check(ctx: CheckContext): Promise<CheckResult> {
registerCheck({
id: 'content-start-position',
category: 'page-size',
description: 'How far into content the actual documentation begins',
description: 'How far into the response the actual documentation content begins',
dependsOn: [],
run: check,
});
2 changes: 1 addition & 1 deletion src/checks/page-size/page-size-html.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ async function check(ctx: CheckContext): Promise<CheckResult> {
registerCheck({
id: 'page-size-html',
category: 'page-size',
description: 'Character count of HTML response and post-conversion size',
description: 'Character count of the HTML response and its size after conversion to markdown',
dependsOn: [],
run: check,
});
3 changes: 2 additions & 1 deletion src/checks/page-size/page-size-transfer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,8 @@ async function check(ctx: CheckContext): Promise<CheckResult> {
registerCheck({
id: 'page-size-transfer',
category: 'page-size',
description: 'Served byte size of the HTML document after transfer decoding',
description:
'How many bytes an agent downloads to read one page, measured as the size of the HTML document after decompression',
dependsOn: [],
run: check,
});
2 changes: 1 addition & 1 deletion src/checks/page-size/single-fetch-completeness.ts
Original file line number Diff line number Diff line change
Expand Up @@ -358,7 +358,7 @@ registerCheck({
id: 'single-fetch-completeness',
category: 'page-size',
description:
'Whether markdown responses are complete in one fetch or declare a working continuation',
'Whether a markdown response delivers its complete content in one fetch or, when it does not, links to the rest in a way agents can follow',
dependsOn: [['markdown-url-support', 'content-negotiation', 'llms-txt-links-markdown']],
run: check,
});
2 changes: 1 addition & 1 deletion src/checks/url-stability/redirect-behavior.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ async function check(ctx: CheckContext): Promise<CheckResult> {
registerCheck({
id: 'redirect-behavior',
category: 'url-stability',
description: 'Whether redirects are same-host HTTP redirects',
description: 'Whether redirects use standard HTTP redirects and stay on the same host',
dependsOn: [],
run: check,
});
7 changes: 2 additions & 5 deletions src/cli/index.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,14 @@
import { createRequire } from 'node:module';
import { Command } from 'commander';
import { registerCheckCommand } from './commands/check.js';

const require = createRequire(import.meta.url);
const { version } = require('../../package.json') as { version: string };
import { AFDOCS_VERSION } from '../version.js';

export function run(argv: string[]): void {
const program = new Command();

program
.name('afdocs')
.description('Test your documentation site against the Agent-Friendly Documentation Spec')
.version(version);
.version(AFDOCS_VERSION);

registerCheckCommand(program);

Expand Down
6 changes: 6 additions & 0 deletions src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,3 +111,9 @@ export function specCheckUrl(category: string, checkId: string): string {

/** Version of the Agent-Friendly Documentation Spec implemented by this release. */
export const SPEC_VERSION = 'v0.6.0';

/**
* Version of the scoring method, as stated at the top of SCORING.md. Scores
* from different scoring versions are not comparable. Bump the two together.
*/
export const SCORING_VERSION = '0.2.0';
4 changes: 4 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ export type {
CheckProgressCompleteEvent,
RunnerOptions,
ReportResult,
CheckDefinitionInfo,
CategoryInfo,
AgentDocsConfig,
DiscoveredFile,
SizeThresholds,
Expand All @@ -32,7 +34,9 @@ export {
CATEGORIES,
VALID_SAMPLING_STRATEGIES,
SPEC_VERSION,
SCORING_VERSION,
} from './constants.js';
export { AFDOCS_VERSION } from './version.js';
export { validateRunnerOptions } from './validation.js';
export type { ValidationResult, ValidationIssue } from './validation.js';
export { createContext, normalizeUrl, runChecks } from './runner.js';
Expand Down
35 changes: 33 additions & 2 deletions src/runner.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,19 @@
import type { CheckContext, CheckResult, RunnerOptions, ReportResult } from './types.js';
import { DEFAULT_OPTIONS, SPEC_BASE_URL } from './constants.js';
import type {
CategoryInfo,
CheckContext,
CheckDefinitionInfo,
CheckResult,
RunnerOptions,
ReportResult,
} from './types.js';
import {
CATEGORIES,
DEFAULT_OPTIONS,
SPEC_BASE_URL,
SPEC_VERSION,
specCheckUrl,
} from './constants.js';
import { AFDOCS_VERSION } from './version.js';
import { createHttpClient } from './http.js';
import { getChecksSorted } from './checks/registry.js';
import { validateRunnerOptions } from './validation.js';
Expand Down Expand Up @@ -235,6 +249,19 @@ export async function runChecks(
error: results.filter((r) => r.status === 'error').length,
};

// Describe exactly the checks and categories that appear in results, so a
// consumer can label them without a hardcoded map of IDs.
const checkDefinitions: Record<string, CheckDefinitionInfo> = {};
const categories: Record<string, CategoryInfo> = {};
for (const check of selectedChecks) {
checkDefinitions[check.id] = {
description: check.description,
specUrl: specCheckUrl(check.category, check.id),
};
const category = CATEGORIES.find((c) => c.id === check.category);
if (category) categories[category.id] = { name: category.name, order: category.order };
}

const urlTags = ctx._sampledPages?.urlTags;
const discoverySources = ctx._sampledPages?.sources;
const testedPages = ctx._sampledPages?.urls.length;
Expand All @@ -244,8 +271,12 @@ export async function runChecks(
url: baseUrl,
timestamp: new Date().toISOString(),
specUrl: SPEC_BASE_URL,
afdocsVersion: AFDOCS_VERSION,
specVersion: SPEC_VERSION,
results,
summary,
checkDefinitions,
categories,
...(urlTags && { urlTags }),
...(discoverySources && { discoverySources }),
...(testedPages !== undefined && { testedPages }),
Expand Down
Loading