From 01656ecadf4dc61f901140a00c1cae38356d948c Mon Sep 17 00:00:00 2001 From: Te-Shu Wang Date: Mon, 7 Sep 2026 03:42:57 +0800 Subject: [PATCH 1/5] feat: add evidence-backed page audit --- CHANGELOG.md | 11 + README.md | 20 ++ docs/methodology.md | 13 + src/cli/index.ts | 72 ++++- src/core/__tests__/audit.test.ts | 137 +++++++++ src/core/audit.ts | 511 +++++++++++++++++++++++++++++++ src/core/index.ts | 1 + src/core/scanner.ts | 139 +++++++-- src/core/types.ts | 48 +++ 9 files changed, 926 insertions(+), 26 deletions(-) create mode 100644 src/core/__tests__/audit.test.ts create mode 100644 src/core/audit.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 11787f6..576b1b0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,17 @@ All notable user-visible changes will be documented here. The project follows Semantic Versioning after the v0.6 evidence baseline is released. +## Unreleased + +### Added + +- Added an evidence-backed `audit` command for one URL or HTML/Markdown file, with versioned `PASS`, `WARNING`, `FAIL`, and `N/A` checks. +- Added structured observations, remediation, validation guidance, and explicit limitations for HTTP, metadata, headings, canonical, robots directives, links, images, and JSON-LD. + +### Compatibility + +- Kept the v0.6 readiness score and existing `scan --json` contract unchanged. + ## 0.6.2 ### Fixed diff --git a/README.md b/README.md index c64ba4b..5683974 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,7 @@ npm install --save-dev aeoptimize npx aeoptimize scan https://example.com npx aeoptimize scan ./dist --dir npx aeoptimize scan ./dist --dir --json +npx aeoptimize audit https://example.com --json ``` Example output: @@ -58,6 +59,25 @@ Two often-promoted AEO signals are deliberately excluded from the score: Every rule, its evidence class, and known false-positive boundary is documented in [docs/methodology.md](docs/methodology.md) and exercised by the [versioned public fixture corpus](fixtures/v0.6/rule-corpus.ts). +## Evidence-backed page audit + +`audit` inspects one public URL or one local HTML/Markdown file. It is a separate, versioned contract and does not change the v0.6 readiness score or `scan --json` output. + +```bash +npx aeoptimize audit https://example.com +npx aeoptimize audit ./dist/index.html --json +``` + +The first audit contract checks: + +- HTTP status, final URL, and redirect evidence for URL targets; +- document title, meta description, headings, language, canonical, and page-level robots directives; +- discovered links, image alt attributes, and JSON-LD structural validity. + +Each check returns `PASS`, `WARNING`, `FAIL`, or `N/A`, the observed evidence, an explanation, an optional remediation, and a validation step. `PASS` is bounded to the inspected evidence. It does not establish ranking, indexing, rich-result display, traffic, conversion, or AI citation. + +The command intentionally reports unavailable site-wide and external measurements as limitations. It does not infer robots.txt policy, sitemap membership, hreflang reciprocity, broken-link status, Core Web Vitals, analytics, or actual search-engine index state from one page. + ## How it compares | | aeoptimize | Lighthouse-style SEO audits | Hosted AEO/GEO platforms | diff --git a/docs/methodology.md b/docs/methodology.md index 3d420f2..af483e7 100644 --- a/docs/methodology.md +++ b/docs/methodology.md @@ -66,6 +66,19 @@ A scoring-rule change must include: The v0.6 fixture corpus is published in [`fixtures/v0.6/rule-corpus.ts`](../fixtures/v0.6/rule-corpus.ts) and is enforced by the release-contract tests. Outcome research, if added later, will be reported separately from the readiness score. +## Evidence-backed audit contract + +The `audit` command is separate from the v0.6 score contract. It reports one of four statuses for each bounded check: + +| Status | Meaning | +| --- | --- | +| `PASS` | The inspected evidence satisfies the check's documented condition. This is not an external-outcome guarantee. | +| `WARNING` | A deterministic observation needs contextual review or may be intentional. | +| `FAIL` | The inspected evidence confirms a structural or retrieval failure within the check's scope. | +| `N/A` | The required evidence is unavailable or the check does not apply to this source type. | + +Each check includes observed evidence, an explanation, optional remediation, and a validation step. The contract does not derive robots.txt policy, sitemap membership, hreflang reciprocity, site-wide duplication, orphan status, Core Web Vitals, analytics, or search-engine index state from a single document. + ## Primary sources - [Google Search: AI features and your website](https://developers.google.com/search/docs/appearance/ai-features) diff --git a/src/cli/index.ts b/src/cli/index.ts index 7119f28..16c92ff 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -5,10 +5,11 @@ import chalk from 'chalk'; import { readFile, writeFile, mkdir, stat } from 'node:fs/promises'; import { join, extname } from 'node:path'; import { scan, scanDirectory, parseHtml, parseMarkdown, scanUrl } from '../core/scanner.js'; +import { audit } from '../core/audit.js'; import { generate } from '../core/generator.js'; import { detectAvailableCLIs, scoreWithAllAvailable } from '../core/external-scorers.js'; import { mergeScores } from '../core/merger.js'; -import type { ScanReport, MultiAiReport, DimensionScores, ScanTarget, SiteInfo, AiScorerResult } from '../core/types.js'; +import type { AuditReport, AuditStatus, ScanReport, MultiAiReport, DimensionScores, ScanTarget, SiteInfo, AiScorerResult } from '../core/types.js'; const HOOK_BEGIN_MARKER = '# BEGIN aeoptimize'; const HOOK_END_MARKER = '# END aeoptimize'; @@ -61,6 +62,32 @@ program } }); +// ── audit command ───────────────────────────────────────────────── + +program + .command('audit ') + .description('Audit one URL or HTML/Markdown file with evidence-backed checks') + .option('--json', 'Output the versioned audit JSON contract') + .action(async (target: string, options: { json?: boolean }) => { + try { + if (!target || target.trim().length === 0) { + console.error(chalk.red('Error: Please provide a URL or HTML/Markdown file.')); + process.exit(1); + } + + const auditTarget = resolveTarget(target); + const report = await audit(auditTarget); + if (options.json) { + console.log(JSON.stringify(report, null, 2)); + } else { + printAuditReport(report); + } + } catch (err) { + console.error(chalk.red(`Error: ${(err as Error).message}`)); + process.exit(1); + } + }); + // ── generate command ─────────────────────────────────────────────── program @@ -441,6 +468,49 @@ function printReport(report: ScanReport): void { } } +function auditStatusColor(status: AuditStatus): (value: string) => string { + switch (status) { + case 'PASS': return chalk.green; + case 'WARNING': return chalk.yellow; + case 'FAIL': return chalk.red; + case 'N/A': return chalk.gray; + } +} + +function printAuditReport(report: AuditReport): void { + console.log(''); + console.log(chalk.bold(' Evidence-backed Page Audit')); + console.log(chalk.dim(` Contract ${report.contractVersion} | ${report.timestamp}`)); + console.log(chalk.dim(` ${report.target.finalUrl ?? report.target.input}`)); + console.log(''); + console.log( + ` ${chalk.green(`PASS ${report.summary.PASS}`)} ` + + `${chalk.yellow(`WARNING ${report.summary.WARNING}`)} ` + + `${chalk.red(`FAIL ${report.summary.FAIL}`)} ` + + `${chalk.gray(`N/A ${report.summary['N/A']}`)}`, + ); + console.log(''); + + for (const check of report.checks) { + const color = auditStatusColor(check.status); + console.log(` ${color(`[${check.status}]`)} ${chalk.bold(check.label)} ${chalk.dim(`(${check.id})`)}`); + console.log(` ${check.explanation}`); + for (const item of check.evidence) { + const observed = JSON.stringify(item.observed); + console.log(chalk.dim(` Evidence ${item.source}: ${observed}`)); + } + if (check.remediation) console.log(` ${chalk.cyan('Fix:')} ${check.remediation}`); + console.log(chalk.dim(` Validate: ${check.validation}`)); + console.log(''); + } + + console.log(chalk.bold(' Limits')); + for (const limitation of report.limitations) { + console.log(chalk.dim(` - ${limitation}`)); + } + console.log(''); +} + function printDimensionBar(label: string, score: number, max: number): void { const pct = score / max; const barWidth = 20; diff --git a/src/core/__tests__/audit.test.ts b/src/core/__tests__/audit.test.ts new file mode 100644 index 0000000..349ceba --- /dev/null +++ b/src/core/__tests__/audit.test.ts @@ -0,0 +1,137 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { audit, auditDocument } from '../audit.js'; +import { parseHtml, parseMarkdown } from '../scanner.js'; + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe('auditDocument', () => { + it('reports evidence-backed checks without a score', () => { + const html = ` + + + Evidence guide + + + + + +
+

Evidence guide

+

Checks

+

This page describes deterministic checks with enough visible content for parsing.

+ Details + Audit data flow +
+ + `; + const doc = parseHtml(html, 'https://example.com/guide'); + const report = auditDocument(doc, { + target: { type: 'file', input: 'guide.html' }, + rendering: 'local-html', + }); + + expect(report.contractVersion).toBe('1.0'); + expect(report.checks).toHaveLength(10); + expect(report.summary.FAIL).toBe(0); + expect(report.summary.WARNING).toBe(1); + expect(report.summary.PASS).toBe(8); + expect(report.summary['N/A']).toBe(1); + expect(report).not.toHaveProperty('score'); + expect(report).not.toHaveProperty('overall'); + expect(report.checks.every((check) => check.evidence.length > 0)).toBe(true); + expect(report.checks.every((check) => check.validation.length > 0)).toBe(true); + expect(Object.keys(report).sort()).toEqual([ + 'checks', + 'contractVersion', + 'limitations', + 'rendering', + 'summary', + 'target', + 'timestamp', + ]); + expect(Object.keys(report.summary).sort()).toEqual(['FAIL', 'N/A', 'PASS', 'WARNING']); + for (const check of report.checks) { + expect(Object.keys(check).sort()).toEqual([ + 'evidence', + 'explanation', + 'id', + 'label', + 'remediation', + 'status', + 'validation', + ]); + expect(['PASS', 'WARNING', 'FAIL', 'N/A']).toContain(check.status); + } + }); + + it('distinguishes confirmed failures, review warnings, and unavailable checks', () => { + const html = ` + + +

Visible copy for the audit fixture.

`; + const document = parseHtml(html, 'fixture.html'); + const report = auditDocument(document, { + target: { type: 'file', input: 'fixture.html' }, + rendering: 'local-html', + }); + + expect(document.jsonLdErrors).toHaveLength(2); + expect(report.checks.find((check) => check.id === 'document-title')?.status).toBe('FAIL'); + expect(report.checks.find((check) => check.id === 'heading-structure')?.status).toBe('FAIL'); + expect(report.checks.find((check) => check.id === 'json-ld-structure')?.status).toBe('FAIL'); + expect(report.checks.find((check) => check.id === 'document-language')?.status).toBe('WARNING'); + expect(report.checks.find((check) => check.id === 'canonical-link')?.status).toBe('WARNING'); + expect(report.checks.find((check) => check.id === 'image-alternatives')?.status).toBe('WARNING'); + expect(report.checks.find((check) => check.id === 'http-status')?.status).toBe('N/A'); + }); + + it('does not claim rendered metadata for Markdown source files', () => { + const report = auditDocument(parseMarkdown('# Guide\n\nSee [details](/details).', 'guide.md'), { + target: { type: 'file', input: 'guide.md' }, + rendering: 'markdown', + }); + + expect(report.checks.find((check) => check.id === 'meta-description')?.status).toBe('N/A'); + expect(report.checks.find((check) => check.id === 'document-language')?.status).toBe('N/A'); + expect(report.checks.find((check) => check.id === 'canonical-link')?.status).toBe('N/A'); + expect(report.checks.find((check) => check.id === 'link-discovery')?.status).toBe('PASS'); + }); +}); + +describe('audit', () => { + it('records redirect, final URL, status, and X-Robots-Tag evidence', async () => { + const fetchMock = vi.fn(async (input: string | URL, init?: RequestInit) => { + const url = input.toString(); + expect(init?.redirect).toBe('manual'); + if (url === 'https://example.com/') { + return new Response(null, { status: 301, headers: { location: '/guide' } }); + } + if (url === 'https://example.com/guide') { + return new Response( + 'Guide

Guide

Home', + { status: 200, headers: { 'content-type': 'text/html', 'x-robots-tag': 'noindex' } }, + ); + } + throw new Error(`Unexpected fetch: ${url}`); + }); + vi.stubGlobal('fetch', fetchMock); + + const report = await audit({ type: 'url', path: 'https://example.com/' }); + + expect(report.target.finalUrl).toBe('https://example.com/guide'); + expect(report.rendering).toBe('response-html'); + expect(report.checks.find((check) => check.id === 'http-status')).toMatchObject({ status: 'PASS' }); + expect(report.checks.find((check) => check.id === 'robots-directives')).toMatchObject({ status: 'WARNING' }); + const httpEvidence = report.checks.find((check) => check.id === 'http-status')?.evidence[0].observed; + expect(httpEvidence).toMatchObject({ status: 200, redirectCount: 1, contentType: 'text/html' }); + expect(fetchMock).toHaveBeenCalledTimes(2); + }); + + it('rejects directory targets until a bounded crawl contract exists', async () => { + await expect(audit({ type: 'directory', path: './dist' })).rejects.toThrow( + 'currently supports one URL or one HTML/Markdown file', + ); + }); +}); diff --git a/src/core/audit.ts b/src/core/audit.ts new file mode 100644 index 0000000..832ed15 --- /dev/null +++ b/src/core/audit.ts @@ -0,0 +1,511 @@ +import { readFile, stat } from 'node:fs/promises'; +import { extname } from 'node:path'; +import { fetchUrlResource, parseHtml, parseMarkdown, type RedirectHop } from './scanner.js'; +import type { + AuditCheck, + AuditEvidence, + AuditEvidenceSource, + AuditReport, + AuditStatus, + ParsedDocument, + ScanTarget, +} from './types.js'; + +const AUDIT_CONTRACT_VERSION = '1.0' as const; +const MAX_FILE_SIZE = 5 * 1024 * 1024; + +export interface AuditContext { + target: AuditReport['target']; + rendering: AuditReport['rendering']; + http?: { + status: number; + statusText: string; + redirects: RedirectHop[]; + contentType: string | null; + xRobotsTag: string | null; + }; +} + +function evidence( + source: AuditEvidenceSource, + observed: AuditEvidence['observed'], +): AuditEvidence { + return { source, observed }; +} + +function sourceFor(context: AuditContext): AuditEvidenceSource { + return context.rendering === 'markdown' ? 'markdown' : 'html'; +} + +function makeCheck( + id: string, + label: string, + status: AuditStatus, + checkEvidence: AuditEvidence[], + explanation: string, + remediation: string | null, + validation: string, +): AuditCheck { + return { + id, + label, + status, + evidence: checkEvidence, + explanation, + remediation, + validation, + }; +} + +function checkHttp(context: AuditContext): AuditCheck { + if (!context.http) { + return makeCheck( + 'http-status', + 'HTTP status and redirects', + 'N/A', + [evidence('derived', { reason: 'Local files have no HTTP response.' })], + 'No network request was made for this local document.', + null, + 'Serve the built page over HTTP and audit its public or staging URL.', + ); + } + + const { status, statusText, redirects, contentType } = context.http; + const statusResult: AuditStatus = status >= 200 && status < 300 ? 'PASS' : 'FAIL'; + const redirectChain = redirects.map((hop) => `${hop.status} ${hop.from} -> ${hop.to}`); + + return makeCheck( + 'http-status', + 'HTTP status and redirects', + statusResult, + [evidence('http', { + status, + statusText, + finalUrl: context.target.finalUrl ?? context.target.input, + redirectCount: redirects.length, + redirectChain, + contentType, + })], + statusResult === 'PASS' + ? `The final response returned HTTP ${status}. Redirects are reported as observed facts and are not scored.` + : `The final response returned HTTP ${status}, so the page was not retrieved as a successful document.`, + statusResult === 'PASS' + ? null + : 'Restore a successful final response or intentionally return the correct removal status, then update links and sitemaps that still reference this URL.', + 'Request the URL again with redirects disabled and confirm every hop plus the final status.', + ); +} + +function checkTitle(doc: ParsedDocument, context: AuditContext): AuditCheck { + const observedTitle = context.rendering === 'markdown' ? doc.title : (doc.documentTitle ?? ''); + const status: AuditStatus = observedTitle.trim() ? 'PASS' : 'FAIL'; + + return makeCheck( + 'document-title', + 'Document title', + status, + [evidence(sourceFor(context), { title: observedTitle || null })], + status === 'PASS' + ? 'A document title was found. This check does not impose a fixed character count.' + : 'No document title was found in the HTML title element or Markdown title source.', + status === 'PASS' + ? null + : 'Add a concise, page-specific title that accurately describes the visible content.', + 'Inspect the rendered document title and verify that it remains page-specific after the build.', + ); +} + +function checkDescription(doc: ParsedDocument, context: AuditContext): AuditCheck { + const frontmatterDescription = typeof doc.frontmatter?.description === 'string' + ? doc.frontmatter.description + : ''; + const description = doc.metaTags.description || frontmatterDescription; + + if (!description && context.rendering === 'markdown') { + return makeCheck( + 'meta-description', + 'Meta description', + 'N/A', + [evidence('markdown', { description: null })], + 'The source Markdown has no description field. Its final HTML template was not inspected.', + null, + 'Audit the rendered HTML and inspect its meta description.', + ); + } + + const status: AuditStatus = description ? 'PASS' : 'WARNING'; + return makeCheck( + 'meta-description', + 'Meta description', + status, + [evidence(sourceFor(context), { description: description || null })], + status === 'PASS' + ? 'A page-specific description candidate is present. Search engines may still choose another snippet.' + : 'No meta description was found. This is a review item, not proof of a search-performance problem.', + status === 'PASS' + ? null + : 'Add an accurate page-specific description when the template should provide one. Do not pad it to a fixed length.', + 'Inspect the built HTML and compare the description with the visible page purpose.', + ); +} + +function checkHeadings(doc: ParsedDocument, context: AuditContext): AuditCheck { + const h1Count = doc.headings.filter((heading) => heading.level === 1).length; + const skippedLevels: string[] = []; + for (let index = 1; index < doc.headings.length; index += 1) { + const previous = doc.headings[index - 1].level; + const current = doc.headings[index].level; + if (current > previous + 1) skippedLevels.push(`H${previous} -> H${current}`); + } + + let status: AuditStatus = 'PASS'; + let explanation = 'The document exposes a main heading and no skipped heading levels were detected.'; + let remediation: string | null = null; + + if (doc.headings.length === 0) { + status = 'FAIL'; + explanation = 'No headings were found in the inspected document.'; + remediation = 'Add descriptive headings that reflect the document hierarchy and visible content.'; + } else if (h1Count === 0 || skippedLevels.length > 0) { + status = 'WARNING'; + explanation = 'The heading outline needs review. Multiple H1 elements are reported as evidence but are not an automatic failure.'; + remediation = 'Review the primary heading and skipped levels, then adjust only where the visual and semantic hierarchy is unclear.'; + } + + return makeCheck( + 'heading-structure', + 'Heading structure', + status, + [evidence(sourceFor(context), { + headingCount: doc.headings.length, + h1Count, + skippedLevels, + outline: doc.headings.slice(0, 20).map((heading) => `H${heading.level}: ${heading.text}`), + })], + explanation, + remediation, + 'Inspect the rendered outline and verify that headings match the visible section hierarchy.', + ); +} + +function checkLanguage(doc: ParsedDocument, context: AuditContext): AuditCheck { + if (!doc.language && context.rendering === 'markdown') { + return makeCheck( + 'document-language', + 'Document language', + 'N/A', + [evidence('markdown', { language: null })], + 'No language field was found in Markdown frontmatter, and the rendered HTML was not inspected.', + null, + 'Audit the rendered HTML and compare its html lang value with the visible language.', + ); + } + + const status: AuditStatus = doc.language ? 'PASS' : 'WARNING'; + return makeCheck( + 'document-language', + 'Document language', + status, + [evidence(sourceFor(context), { language: doc.language ?? null })], + status === 'PASS' + ? 'An html lang or Markdown language value was found. Language-content agreement still needs human review.' + : 'The HTML document does not declare a language.', + status === 'PASS' ? null : 'Add the appropriate html lang value to the document template.', + 'Compare the declared language with the primary visible language and test representative localized pages.', + ); +} + +function resolveCanonical(value: string, baseUrl?: string): string | null { + try { + return baseUrl ? new URL(value, baseUrl).toString() : new URL(value).toString(); + } catch { + return null; + } +} + +function withoutHash(value: string): string { + const url = new URL(value); + url.hash = ''; + return url.toString(); +} + +function checkCanonical(doc: ParsedDocument, context: AuditContext): AuditCheck { + const canonicals = doc.canonicalLinks ?? []; + if (canonicals.length === 0) { + const isMarkdown = context.rendering === 'markdown'; + return makeCheck( + 'canonical-link', + 'Canonical link', + isMarkdown ? 'N/A' : 'WARNING', + [evidence(sourceFor(context), { canonicals: [] })], + isMarkdown + ? 'No canonical field was found in Markdown frontmatter, and the rendered template was not inspected.' + : 'No canonical link was found. Canonical markup is context-dependent, so absence is a review item.', + isMarkdown ? null : 'Add one canonical link when the page participates in a duplicate or URL-normalization strategy.', + 'Inspect the final HTML, resolve the canonical URL, and confirm that it matches the intended indexable URL.', + ); + } + + const baseUrl = context.target.finalUrl; + const resolved = canonicals.map((value) => resolveCanonical(value, baseUrl)); + if (canonicals.length > 1 || resolved.some((value) => value === null)) { + return makeCheck( + 'canonical-link', + 'Canonical link', + 'FAIL', + [evidence(sourceFor(context), { + canonicals, + resolved: resolved.map((value) => value ?? 'INVALID'), + })], + canonicals.length > 1 + ? 'Multiple canonical links were found, so the canonical signal is ambiguous.' + : 'The canonical value could not be resolved as a URL.', + 'Emit exactly one valid canonical link that represents the intended indexable URL.', + 'Fetch the built page and verify one canonical element plus its resolved destination.', + ); + } + + const canonical = resolved[0]!; + if (!baseUrl) { + return makeCheck( + 'canonical-link', + 'Canonical link', + 'WARNING', + [evidence(sourceFor(context), { declared: canonicals[0], resolved: canonical, finalUrl: null })], + 'One valid canonical link was found, but a local-file audit cannot compare it with the deployed final URL.', + 'Confirm that the deployed page resolves to the intended canonical URL.', + 'Audit the deployed URL and compare its final response URL with the rendered canonical element.', + ); + } + + const differsFromFinal = baseUrl ? withoutHash(canonical) !== withoutHash(baseUrl) : false; + return makeCheck( + 'canonical-link', + 'Canonical link', + differsFromFinal ? 'WARNING' : 'PASS', + [evidence(sourceFor(context), { declared: canonicals[0], resolved: canonical, finalUrl: baseUrl ?? null })], + differsFromFinal + ? 'The canonical resolves to a different URL than the final response. This can be intentional and needs review.' + : 'One valid canonical link was found and it resolves to the inspected final URL.', + differsFromFinal ? 'Confirm the intended primary URL and update the canonical or serving URL if they conflict.' : null, + 'Request both URLs, confirm their final status, and inspect the rendered canonical element.', + ); +} + +function checkRobots(doc: ParsedDocument, context: AuditContext): AuditCheck { + const metaRobots = [doc.metaTags.robots, doc.metaTags.googlebot].filter(Boolean).join(', '); + const xRobotsTag = context.http?.xRobotsTag ?? ''; + const combined = `${metaRobots}, ${xRobotsTag}`; + const blocksIndexing = /(?:^|[,\s])(?:noindex|none)(?:$|[,\s])/i.test(combined); + const blocksFollowing = /(?:^|[,\s])nofollow(?:$|[,\s])/i.test(combined); + const status: AuditStatus = blocksIndexing || blocksFollowing ? 'WARNING' : 'PASS'; + + return makeCheck( + 'robots-directives', + 'Page-level robots directives', + status, + [ + evidence(sourceFor(context), { metaRobots: metaRobots || null }), + context.http + ? evidence('http', { xRobotsTag: xRobotsTag || null }) + : evidence('derived', { xRobotsTag: null, reason: 'Local files have no HTTP response headers.' }), + ], + status === 'PASS' + ? 'No page-level noindex or nofollow directive was detected. robots.txt, authentication, CDN policy, and actual index state were not checked.' + : 'A page-level indexing or following restriction was detected. Its intent cannot be inferred automatically.', + status === 'PASS' + ? null + : 'Confirm whether the directive is intentional. Remove or narrow it only when the page should be indexable or its links should be followed.', + 'Inspect both the response headers and rendered meta robots tags, then verify the intended policy with the responsible owner.', + ); +} + +function checkLinks(doc: ParsedDocument, context: AuditContext): AuditCheck { + const links = doc.links; + const emptyText = links.filter((link) => !link.text.trim()).length; + const scriptLinks = links.filter((link) => /^javascript:/i.test(link.href)).length; + const status: AuditStatus = links.length === 0 || emptyText > 0 || scriptLinks > 0 ? 'WARNING' : 'PASS'; + + return makeCheck( + 'link-discovery', + 'Link discovery', + status, + [evidence(sourceFor(context), { + linkCount: links.length, + emptyTextCount: emptyText, + javascriptLinkCount: scriptLinks, + sample: links.slice(0, 20).map((link) => `${link.text || '[empty]'} -> ${link.href}`), + })], + links.length === 0 + ? 'No links were discovered in the inspected document.' + : 'Links were extracted from the document. Their destination status and site-graph role were not fetched in this single-page audit.', + status === 'PASS' + ? null + : 'Review missing link text and script-only navigation. Add crawlable links when they match the intended navigation and content relationships.', + 'Fetch link destinations separately and compare the rendered navigation with the extracted link sample.', + ); +} + +function checkImages(doc: ParsedDocument, context: AuditContext): AuditCheck { + const images = doc.images ?? []; + if (images.length === 0) { + return makeCheck( + 'image-alternatives', + 'Image alternative text', + 'N/A', + [evidence(sourceFor(context), { imageCount: 0 })], + 'No images were found in the inspected document.', + null, + 'Inspect representative rendered templates if images are inserted after build or hydration.', + ); + } + + const missingAlt = images.filter((image) => image.alt === undefined).length; + const emptyAlt = images.filter((image) => image.alt === '').length; + const status: AuditStatus = missingAlt > 0 ? 'WARNING' : 'PASS'; + + return makeCheck( + 'image-alternatives', + 'Image alternative text', + status, + [evidence(sourceFor(context), { + imageCount: images.length, + missingAltAttributeCount: missingAlt, + emptyAltCount: emptyAlt, + sample: images.slice(0, 20).map((image) => `${image.src || '[missing src]'} | alt=${image.alt ?? '[missing]'}`), + })], + status === 'PASS' + ? 'Every discovered image has an alt attribute. Empty alt values can be correct for decorative images and need contextual review.' + : 'One or more images lack an alt attribute. The audit does not infer the correct description from pixels.', + status === 'PASS' + ? null + : 'Add accurate alt text for informative images and an explicit empty alt value for images that are purely decorative.', + 'Inspect each image in context with assistive-technology semantics and verify the built HTML attributes.', + ); +} + +function checkJsonLd(doc: ParsedDocument, context: AuditContext): AuditCheck { + const errors = doc.jsonLdErrors ?? []; + const missingUniversalFields = doc.jsonLd.filter((value) => !value['@context'] || !value['@type']); + + if (errors.length > 0 || missingUniversalFields.length > 0) { + return makeCheck( + 'json-ld-structure', + 'JSON-LD structure', + 'FAIL', + [evidence(sourceFor(context), { + blockCount: doc.jsonLd.length + errors.length, + parsedCount: doc.jsonLd.length, + parseErrors: errors, + missingContextOrTypeCount: missingUniversalFields.length, + })], + 'Malformed JSON-LD or a missing @context/@type field was detected. Feature-specific eligibility and visible-content agreement remain outside this structural check.', + 'Correct the JSON syntax and universal fields, then validate the specific schema type against the applicable primary documentation and visible content.', + 'Parse every JSON-LD block again and run the relevant structured-data validator for the page type.', + ); + } + + if (doc.jsonLd.length === 0) { + return makeCheck( + 'json-ld-structure', + 'JSON-LD structure', + 'N/A', + [evidence(sourceFor(context), { blockCount: 0, schemaTypes: [] })], + 'No JSON-LD was found. Structured data is optional and absence is not treated as an error.', + null, + 'Add structured data only for a defined feature or entity need, then validate it against visible content.', + ); + } + + return makeCheck( + 'json-ld-structure', + 'JSON-LD structure', + 'PASS', + [evidence(sourceFor(context), { + blockCount: doc.jsonLd.length, + schemaTypes: doc.jsonLd.map((value) => value['@type'] || '[unknown]'), + })], + 'Every parsed JSON-LD object includes @context and @type. This does not establish feature eligibility or guarantee rich results.', + null, + 'Compare each structured-data field with visible content and the current documentation for its intended feature.', + ); +} + +export function auditDocument(doc: ParsedDocument, context: AuditContext): AuditReport { + const checks = [ + checkHttp(context), + checkTitle(doc, context), + checkDescription(doc, context), + checkHeadings(doc, context), + checkLanguage(doc, context), + checkCanonical(doc, context), + checkRobots(doc, context), + checkLinks(doc, context), + checkImages(doc, context), + checkJsonLd(doc, context), + ]; + + const summary: Record = { PASS: 0, WARNING: 0, FAIL: 0, 'N/A': 0 }; + for (const check of checks) summary[check.status] += 1; + + return { + contractVersion: AUDIT_CONTRACT_VERSION, + target: context.target, + rendering: context.rendering, + checks, + summary, + limitations: [ + 'This command reports deterministic observations from one document. It does not claim ranking, indexing, rich-result display, traffic, conversion, or citation outcomes.', + 'Destination status, robots.txt, sitemap membership, hreflang reciprocity, site-wide duplication, orphan pages, Core Web Vitals, and analytics require separate evidence.', + 'PASS means the bounded check found no issue in the inspected evidence. It is not a guarantee of search-engine behavior.', + ], + timestamp: new Date().toISOString(), + }; +} + +async function auditFile(filePath: string): Promise { + const fileStats = await stat(filePath); + if (!fileStats.isFile()) throw new Error('Audit target must be an HTML, HTM, Markdown, or MDX file.'); + if (fileStats.size > MAX_FILE_SIZE) { + throw new Error(`File too large (${(fileStats.size / 1024 / 1024).toFixed(1)}MB). Maximum is 5MB.`); + } + + const content = await readFile(filePath, 'utf8'); + const extension = extname(filePath).toLowerCase(); + if (extension === '.html' || extension === '.htm') { + return auditDocument(parseHtml(content, filePath), { + target: { type: 'file', input: filePath }, + rendering: 'local-html', + }); + } + if (extension === '.md' || extension === '.mdx') { + return auditDocument(parseMarkdown(content, filePath), { + target: { type: 'file', input: filePath }, + rendering: 'markdown', + }); + } + throw new Error(`Unsupported file type: ${extension}`); +} + +async function auditUrl(url: string): Promise { + const resource = await fetchUrlResource(url); + const doc = parseHtml(resource.html, resource.finalUrl); + return auditDocument(doc, { + target: { type: 'url', input: resource.requestedUrl, finalUrl: resource.finalUrl }, + rendering: resource.renderedWithBrowser ? 'browser' : 'response-html', + http: { + status: resource.status, + statusText: resource.statusText, + redirects: resource.redirects, + contentType: resource.contentType, + xRobotsTag: resource.xRobotsTag, + }, + }); +} + +export async function audit(target: ScanTarget): Promise { + if (target.type === 'directory') { + throw new Error('Evidence-backed audit currently supports one URL or one HTML/Markdown file.'); + } + return target.type === 'url' ? auditUrl(target.path) : auditFile(target.path); +} diff --git a/src/core/index.ts b/src/core/index.ts index 3ca63cc..ac3d002 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -1,5 +1,6 @@ export * from './types.js'; export * from './scanner.js'; +export * from './audit.js'; export * from './rules.js'; export * from './generator.js'; export * from './ai-prompt.js'; diff --git a/src/core/scanner.ts b/src/core/scanner.ts index 7efeda3..e1ec895 100644 --- a/src/core/scanner.ts +++ b/src/core/scanner.ts @@ -25,7 +25,8 @@ export function parseHtml(html: string, url: string): ParsedDocument { const $ = cheerio.load(html); // Extract title - const title = $('title').first().text().trim() || $('h1').first().text().trim() || url; + const documentTitle = $('title').first().text().trim(); + const title = documentTitle || $('h1').first().text().trim() || url; // Extract headings const headings: Heading[] = []; @@ -46,16 +47,22 @@ export function parseHtml(html: string, url: string): ParsedDocument { // Extract JSON-LD const jsonLd: JsonLdObject[] = []; - $('script[type="application/ld+json"]').each((_, el) => { + const jsonLdErrors: string[] = []; + $('script[type="application/ld+json"]').each((index, el) => { try { const parsed = JSON.parse($(el).html() || ''); - if (Array.isArray(parsed)) { - jsonLd.push(...parsed); - } else { - jsonLd.push(parsed); + const candidates = Array.isArray(parsed) ? parsed : [parsed]; + for (const [candidateIndex, candidate] of candidates.entries()) { + if (candidate && typeof candidate === 'object' && !Array.isArray(candidate)) { + jsonLd.push(candidate as JsonLdObject); + } else { + const location = Array.isArray(parsed) ? ` item ${candidateIndex + 1}` : ''; + jsonLdErrors.push(`JSON-LD block ${index + 1}${location}: expected an object`); + } } - } catch { - // Ignore malformed JSON-LD + } catch (error) { + const message = error instanceof Error ? error.message : 'Unknown JSON parse error'; + jsonLdErrors.push(`JSON-LD block ${index + 1}: ${message}`); } }); @@ -76,6 +83,17 @@ export function parseHtml(html: string, url: string): ParsedDocument { if (href) links.push({ href, text, rel }); }); + const images = $('img').map((_, el) => ({ + src: $(el).attr('src') || '', + alt: $(el).attr('alt'), + width: $(el).attr('width'), + height: $(el).attr('height'), + loading: $(el).attr('loading'), + })).get(); + + const language = $('html').attr('lang')?.trim() || undefined; + const canonicalLinks = $('link[rel~="canonical"]').map((_, el) => $(el).attr('href') || '').get(); + // Extract raw text (content area preferred) const contentArea = $('main, article, [role="main"]').first(); const rawText = (contentArea.length > 0 ? contentArea.text() : $('body').text()).replace(/\s+/g, ' ').trim(); @@ -83,12 +101,17 @@ export function parseHtml(html: string, url: string): ParsedDocument { return { url, title, + documentTitle, html, headings, paragraphs, jsonLd, + jsonLdErrors, metaTags, links, + images, + language, + canonicalLinks, rawText, }; } @@ -149,16 +172,36 @@ export function parseMarkdown(md: string, url: string): ParsedDocument { .replace(/\s+/g, ' ') .trim(); + const links: Link[] = []; + const images = []; + for (const match of content.matchAll(/(!?)\[([^\]]*)\]\(([^)\s]+)(?:\s+["'][^"']*["'])?\)/g)) { + const [, imageMarker, text, href] = match; + if (imageMarker) { + images.push({ src: href, alt: text }); + } else { + links.push({ href, text }); + } + } + + const canonicalValue = frontmatter.canonical; + const canonicalLinks = typeof canonicalValue === 'string' ? [canonicalValue] : []; + const languageValue = frontmatter.lang ?? frontmatter.language; + const language = typeof languageValue === 'string' ? languageValue : undefined; + return { url, title: finalTitle, + documentTitle: typeof frontmatter.title === 'string' ? frontmatter.title : undefined, markdown: md, frontmatter: frontmatter as Record, headings, paragraphs, jsonLd: [], metaTags: {}, - links: [], + links, + images, + language, + canonicalLinks, rawText, }; } @@ -280,13 +323,36 @@ function isBlockedHostname(hostname: string): boolean { return blocked.test(hostname); } -async function fetchWithSafeRedirects(input: string | URL, init?: RequestInit, maxRedirects = 10): Promise { +export interface RedirectHop { + from: string; + to: string; + status: number; +} + +export interface UrlResource { + requestedUrl: string; + finalUrl: string; + status: number; + statusText: string; + redirects: RedirectHop[]; + contentType: string | null; + xRobotsTag: string | null; + html: string; + renderedWithBrowser: boolean; +} + +async function fetchWithSafeRedirects( + input: string | URL, + init?: RequestInit, + maxRedirects = 10, +): Promise<{ response: Response; finalUrl: string; redirects: RedirectHop[] }> { let currentUrl = typeof input === 'string' ? validateUrl(input) : validateUrl(input.toString()); + const redirects: RedirectHop[] = []; for (let redirectCount = 0; redirectCount <= maxRedirects; redirectCount += 1) { const response = await fetch(currentUrl, { ...init, redirect: 'manual' }); if (response.status < 300 || response.status >= 400) { - return response; + return { response, finalUrl: currentUrl.toString(), redirects }; } if (redirectCount === maxRedirects) { @@ -298,7 +364,13 @@ async function fetchWithSafeRedirects(input: string | URL, init?: RequestInit, m throw new Error(`Redirect response from ${currentUrl.toString()} missing Location header`); } - currentUrl = validateUrl(new URL(location, currentUrl).toString()); + const nextUrl = validateUrl(new URL(location, currentUrl).toString()); + redirects.push({ + from: currentUrl.toString(), + to: nextUrl.toString(), + status: response.status, + }); + currentUrl = nextUrl; } throw new Error(`Too many redirects while fetching ${currentUrl.toString()}`); @@ -349,30 +421,47 @@ function isSpaLikely(html: string): boolean { return contentTags < 10 && scripts > 3; } -export async function scanUrl(url: string): Promise { +export async function fetchUrlResource(url: string): Promise { validateUrl(url); - const response = await fetchWithSafeRedirects(url); - if (!response.ok) { - throw new Error(`Failed to fetch ${url}: ${response.status} ${response.statusText}`); - } + const { response, finalUrl, redirects } = await fetchWithSafeRedirects(url); let html = await response.text(); let renderedWithBrowser = false; - // If page looks like an SPA, try puppeteer for full rendering - if (isSpaLikely(html)) { - const result = await fetchWithPuppeteer(url); + if (response.ok && isSpaLikely(html)) { + const result = await fetchWithPuppeteer(finalUrl); if (result.rendered) { html = result.html; renderedWithBrowser = true; - } else { - console.warn('[aeoptimize] This page appears to be a JavaScript-rendered SPA.'); - console.warn('[aeoptimize] Install Chrome/Chromium for accurate scoring of JS-rendered sites.'); - console.warn('[aeoptimize] Without a browser, scores may be lower than actual content quality.\n'); } } - const doc = parseHtml(html, url); + return { + requestedUrl: url, + finalUrl, + status: response.status, + statusText: response.statusText, + redirects, + contentType: response.headers.get('content-type'), + xRobotsTag: response.headers.get('x-robots-tag'), + html, + renderedWithBrowser, + }; +} + +export async function scanUrl(url: string): Promise { + const resource = await fetchUrlResource(url); + if (resource.status < 200 || resource.status >= 300) { + throw new Error(`Failed to fetch ${url}: ${resource.status} ${resource.statusText}`); + } + + if (isSpaLikely(resource.html) && !resource.renderedWithBrowser) { + console.warn('[aeoptimize] This page appears to be a JavaScript-rendered SPA.'); + console.warn('[aeoptimize] Install Chrome/Chromium for accurate scoring of JS-rendered sites.'); + console.warn('[aeoptimize] Without a browser, scores may be lower than actual content quality.\n'); + } + + const doc = parseHtml(resource.html, url); const analysis = scanDocument(doc); diff --git a/src/core/types.ts b/src/core/types.ts index 56868ec..0ed0e7c 100644 --- a/src/core/types.ts +++ b/src/core/types.ts @@ -48,6 +48,14 @@ export interface Link { rel?: string; } +export interface ImageReference { + src: string; + alt?: string; + width?: string; + height?: string; + loading?: string; +} + export interface JsonLdObject { '@type'?: string; '@context'?: string; @@ -57,17 +65,57 @@ export interface JsonLdObject { export interface ParsedDocument { url: string; title: string; + documentTitle?: string; html?: string; markdown?: string; frontmatter?: Record; headings: Heading[]; paragraphs: string[]; jsonLd: JsonLdObject[]; + jsonLdErrors?: string[]; metaTags: Record; links: Link[]; + images?: ImageReference[]; + language?: string; + canonicalLinks?: string[]; rawText: string; } +export type AuditStatus = 'PASS' | 'WARNING' | 'FAIL' | 'N/A'; + +export type AuditEvidenceSource = 'http' | 'html' | 'markdown' | 'derived'; + +export type AuditEvidenceValue = string | number | boolean | null | string[]; + +export interface AuditEvidence { + source: AuditEvidenceSource; + observed: Record; +} + +export interface AuditCheck { + id: string; + label: string; + status: AuditStatus; + evidence: AuditEvidence[]; + explanation: string; + remediation: string | null; + validation: string; +} + +export interface AuditReport { + contractVersion: '1.0'; + target: { + type: 'url' | 'file'; + input: string; + finalUrl?: string; + }; + rendering: 'response-html' | 'browser' | 'local-html' | 'markdown'; + checks: AuditCheck[]; + summary: Record; + limitations: string[]; + timestamp: string; +} + export interface RuleResult { score: number; maxScore: number; From 5039ceedc41727e7b3ac4b203b9f08db83e36372 Mon Sep 17 00:00:00 2001 From: Te-Shu Wang Date: Mon, 7 Sep 2026 03:44:50 +0800 Subject: [PATCH 2/5] feat: audit static builds with evidence and opt-in CI gates --- CHANGELOG.md | 1 + README.md | 37 +++ src/cli/index.ts | 36 +++ src/core/__tests__/static-audit.test.ts | 388 ++++++++++++++++++++++++ src/core/index.ts | 1 + src/core/static-audit.ts | 244 +++++++++++++++ 6 files changed, 707 insertions(+) create mode 100644 src/core/__tests__/static-audit.test.ts create mode 100644 src/core/static-audit.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 576b1b0..5389c3f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ All notable user-visible changes will be documented here. The project follows Se ### Added +- Added `audit-build` for local HTML directories with cross-page title/canonical review, syntax checks and optional `--expect-indexable --fail-on-error` CI gates. - Added an evidence-backed `audit` command for one URL or HTML/Markdown file, with versioned `PASS`, `WARNING`, `FAIL`, and `N/A` checks. - Added structured observations, remediation, validation guidance, and explicit limitations for HTTP, metadata, headings, canonical, robots directives, links, images, and JSON-LD. diff --git a/README.md b/README.md index 5683974..415ae39 100644 --- a/README.md +++ b/README.md @@ -121,6 +121,43 @@ The Action exposes `score` and `report` outputs in both modes. Its release is re A copyable advisory workflow and controlled input are available in the [end-to-end Action sample](examples/github-action-sample/README.md). +## Audit built HTML before deployment + +The `audit-build` command checks a local HTML file or build directory and reports evidence, +remediation and validation for each finding. It leaves the existing `scan` score and +JSON contract unchanged. + +```bash +npx aeoptimize audit-build ./dist --json +npx aeoptimize audit-build ./dist --base-url https://example.com/ --expect-indexable --fail-on-error --json > audit.json +``` + +Malformed JSON-LD and invalid or multiple canonical declarations produce `FAIL`. +HTML `noindex` and `none` are warnings unless `--expect-indexable` is supplied. +Missing or repeated titles/descriptions and cross-page title/canonical reuse are +advisory. Shared canonicals can be intentional; they are never automatically rewritten. + +`--fail-on-error` exits with code 1 when a `FAIL` is present, while still writing the +complete report. Input errors also exit 1. Without it, a completed audit is advisory. +Use `--expect-indexable` only for pages intended for standalone search indexing. + +This command reads source HTML without fetching URLs or launching a browser. +HTTP headers, robots.txt and actual indexing are explicitly unassessed. JSON-LD +checks cover JSON syntax and root shape; schema semantics and visible-content +consistency require separate validation. Missing JSON-LD is `N/A`. + +For a file, `--base-url` is its deployed page URL. For a directory, it is the +deployment root; relative file paths are appended without inferring hosting rewrites. +An HTML `base` element is respected. Relative canonicals without a resolvable base +are `N/A`. Hidden entries, `node_modules` and symlinks are excluded from traversal; +an explicit symlink input is rejected. Unreadable files and files over 5 MB stop +the audit instead of silently dropping pages. + +Rules follow the [robots meta specification](https://developers.google.com/search/docs/crawling-indexing/robots-meta-tag) +and [canonical URL guidance](https://developers.google.com/search/docs/crawling-indexing/consolidate-duplicate-urls). +A syntax pass does not establish eligibility under the +[structured-data policies](https://developers.google.com/search/docs/appearance/structured-data/sd-policies). + ## Optional generators ```bash diff --git a/src/cli/index.ts b/src/cli/index.ts index 16c92ff..07e3575 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -9,6 +9,7 @@ import { audit } from '../core/audit.js'; import { generate } from '../core/generator.js'; import { detectAvailableCLIs, scoreWithAllAvailable } from '../core/external-scorers.js'; import { mergeScores } from '../core/merger.js'; +import { auditPath } from '../core/static-audit.js'; import type { AuditReport, AuditStatus, ScanReport, MultiAiReport, DimensionScores, ScanTarget, SiteInfo, AiScorerResult } from '../core/types.js'; const HOOK_BEGIN_MARKER = '# BEGIN aeoptimize'; @@ -88,6 +89,41 @@ program } }); +program + .command('audit-build ') + .description('Audit local built HTML with evidence and optional CI failure on errors') + .option('--json', 'Output the versioned static audit report as JSON') + .option('--base-url ', 'Deployed page URL, or deployment root for a directory') + .option('--expect-indexable', 'Treat HTML noindex/none as a failure for this target') + .option('--fail-on-error', 'Exit 1 when the audit contains FAIL checks; warnings remain advisory') + .action(async (path: string, options: { + json?: boolean; baseUrl?: string; expectIndexable?: boolean; failOnError?: boolean; + }) => { + try { + const report = await auditPath(path, options); + if (options.json) { + console.log(JSON.stringify(report, null, 2)); + } else { + console.log('Static HTML Audit'); + console.log(`${report.pages.length} pages | ${report.summary.FAIL} failed | ${report.summary.WARNING} warnings | ${report.summary.PASS} passed | ${report.summary['N/A']} not assessed`); + for (const page of report.pages) { + console.log(`\n${page.target}`); + for (const check of page.checks) { + console.log(` [${check.status}] ${check.id}: ${check.message}`); + for (const evidence of check.evidence) console.log(` Evidence: ${evidence}`); + if (check.remediation) console.log(` Fix: ${check.remediation}`); + console.log(` Verify: ${check.validation}`); + } + } + console.log(`\nScope: ${report.limitations.join(' ')}`); + } + if (options.failOnError && report.summary.FAIL > 0) process.exitCode = 1; + } catch (error) { + console.error(`Error: ${(error as Error).message}`); + process.exitCode = 1; + } + }); + // ── generate command ─────────────────────────────────────────────── program diff --git a/src/core/__tests__/static-audit.test.ts b/src/core/__tests__/static-audit.test.ts new file mode 100644 index 0000000..1d004f4 --- /dev/null +++ b/src/core/__tests__/static-audit.test.ts @@ -0,0 +1,388 @@ +import { afterEach, describe, expect, it } from 'vitest'; +import { mkdtemp, mkdir, rm, symlink, writeFile } from 'node:fs/promises'; +import { basename, join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { auditHtml, auditPath } from '../static-audit.js'; + +type StaticPageAudit = ReturnType; +type StaticAuditCheck = StaticPageAudit['checks'][number]; + +const checkIds = [ + 'document-title', + 'meta-description', + 'canonical', + 'indexing-directives', + 'jsonld-syntax', + 'http-indexing', +] as const; + +let ownedTempDir: string | undefined; + +afterEach(async () => { + if (ownedTempDir) { + const path = ownedTempDir; + ownedTempDir = undefined; + await rm(path, { recursive: true, force: true }); + } +}); + +function getCheck(page: StaticPageAudit, id: string): StaticAuditCheck { + const check = page.checks.find((candidate) => candidate.id === id); + if (!check) throw new Error(`Missing static audit check: ${id}`); + return check; +} + +function findCheck(page: StaticPageAudit, id: string): StaticAuditCheck | undefined { + return page.checks.find((candidate) => candidate.id === id); +} + +function expectCheckContract(check: StaticAuditCheck): void { + expect(['PASS', 'WARNING', 'FAIL', 'N/A']).toContain(check.status); + expect(Array.isArray(check.evidence)).toBe(true); + expect(check.evidence.every((item) => typeof item === 'string')).toBe(true); + expect(typeof check.message).toBe('string'); + expect(check.message.length).toBeGreaterThan(0); + expect(check.remediation === null || typeof check.remediation === 'string').toBe(true); + expect(typeof check.validation).toBe('string'); +} + +function expectPageContract(page: StaticPageAudit, target: string): void { + expect(page.target).toBe(target); + expect(page.checks).toHaveLength(checkIds.length); + expect(new Set(page.checks.map((check) => check.id))).toEqual(new Set(checkIds)); + page.checks.forEach(expectCheckContract); +} + +function htmlPage({ + title = 'A static page', + description = 'A page-specific description.', + canonical = 'https://example.test/page', + robots = 'index,follow', + jsonLd = '', + body = '

Readable page content.

', +}: { + title?: string; + description?: string | null; + canonical?: string | null; + robots?: string | null; + jsonLd?: string; + body?: string; +} = {}): string { + const descriptionTag = description === null ? '' : ``; + const canonicalTag = canonical === null ? '' : ``; + const robotsTag = robots === null ? '' : ``; + return `${title}${descriptionTag}${canonicalTag}${robotsTag}${jsonLd}${body}`; +} + +async function makeTempDir(): Promise { + ownedTempDir = await mkdtemp(join(tmpdir(), 'aeoptimize-static-audit-')); + return ownedTempDir; +} + +async function writeHtmlFile(path: string, html = htmlPage()): Promise { + await writeFile(path, html, 'utf8'); +} + +function jsonLdScript(payload: string): string { + return ``; +} + +describe('auditHtml', () => { + it('returns the stable page contract for a complete static page', () => { + const target = 'https://example.test/guide'; + const page = auditHtml( + htmlPage({ + title: 'A useful guide', + description: 'A concise description for the guide.', + canonical: target, + robots: 'index,follow', + jsonLd: jsonLdScript('{"@context":"https://schema.org","@type":"Article"}'), + }), + target, + ); + + expectPageContract(page, target); + expect(getCheck(page, 'document-title').status).toBe('PASS'); + expect(getCheck(page, 'meta-description').status).toBe('PASS'); + expect(getCheck(page, 'canonical').status).toBe('PASS'); + expect(getCheck(page, 'indexing-directives').status).toBe('PASS'); + expect(getCheck(page, 'jsonld-syntax').status).toBe('PASS'); + expect(getCheck(page, 'http-indexing').status).toBe('N/A'); + }); + + it.each([ + ['missing title', ''], + ['empty title', ' '], + ['multiple titles', 'FirstSecond'], + ])('warns when the document has %s', (_caseName, head) => { + const page = auditHtml(`${head}Content`, 'missing-title.html'); + expect(getCheck(page, 'document-title').status).toBe('WARNING'); + }); + + it.each([ + ['no description', 'Page'], + ['an empty description', 'Page'], + [ + 'multiple descriptions', + 'Page', + ], + ])('warns when the page has %s', (_caseName, head) => { + const page = auditHtml(`${head}Content`, 'missing-description.html'); + expect(getCheck(page, 'meta-description').status).toBe('WARNING'); + }); + + it('distinguishes a missing canonical from an invalid or duplicated canonical', () => { + const missing = auditHtml(htmlPage({ canonical: null }), 'missing-canonical.html'); + expect(getCheck(missing, 'canonical').status).toBe('WARNING'); + + const duplicate = auditHtml( + 'Page', + 'duplicate-canonical.html', + ); + expect(getCheck(duplicate, 'canonical').status).toBe('FAIL'); + }); + + it.each([ + ['empty', ''], + ['invalid', 'https://[not-a-valid-url'], + ['non-http', 'javascript:alert(1)'], + ])('fails for an %s canonical URL', (_caseName, canonical) => { + const page = auditHtml(htmlPage({ canonical }), 'invalid-canonical.html'); + expect(getCheck(page, 'canonical').status).toBe('FAIL'); + }); + + it('treats a relative canonical as N/A without a base URL and resolves it with one', () => { + const relative = auditHtml(htmlPage({ canonical: '../canonical' }), 'relative.html'); + expect(getCheck(relative, 'canonical').status).toBe('N/A'); + + const resolved = auditHtml(htmlPage({ canonical: '../canonical' }), 'relative.html', { + baseUrl: 'https://example.test/docs/index.html', + }); + expect(getCheck(resolved, 'canonical').status).toBe('PASS'); + }); + + it('detects case-insensitive robots and googlebot noindex across repeated tags, with noindex taking precedence', () => { + const html = 'PageContent'; + const page = auditHtml(html, 'directives.html'); + const check = getCheck(page, 'indexing-directives'); + + expect(check.status).toBe('WARNING'); + expect(check.evidence.join(' ')).toMatch(/noindex/i); + + const expectedIndexable = auditHtml(html, 'directives.html', { expectIndexable: true }); + expect(getCheck(expectedIndexable, 'indexing-directives').status).toBe('FAIL'); + }); + + it('passes an observed index directive even when page text contains the word noindex', () => { + const page = auditHtml( + htmlPage({ + robots: 'INDEX,FOLLOW', + body: '

This page explains the word noindex in a documentation example.

', + }), + 'observed-directives.html', + { expectIndexable: true }, + ); + + expect(getCheck(page, 'indexing-directives').status).toBe('PASS'); + }); + + it('does not treat max-image-preview:none as the standalone none directive', () => { + const page = auditHtml( + htmlPage({ robots: 'index,follow,max-image-preview:none' }), + 'image-preview-directive.html', + { expectIndexable: true }, + ); + + expect(getCheck(page, 'indexing-directives').status).toBe('PASS'); + }); + + it('keeps spaced parameter values distinct from a standalone none token', () => { + const preview = auditHtml(htmlPage({ robots: 'max-image-preview: none' }), 'page.html', { expectIndexable: true }); + expect(getCheck(preview, 'indexing-directives').status).toBe('PASS'); + const blocked = auditHtml(htmlPage({ robots: 'none' }), 'page.html', { expectIndexable: true }); + expect(getCheck(blocked, 'indexing-directives').status).toBe('FAIL'); + }); + + it('resolves HTML base href without inventing a deployment origin', () => { + const html = ''; + expect(getCheck(auditHtml(html, 'page.html'), 'canonical').status).toBe('N/A'); + const resolved = auditHtml(html, 'page.html', { baseUrl: 'https://example.test/page.html' }); + expect(getCheck(resolved, 'canonical').evidence).toEqual(['https://example.test/docs/guide']); + }); + + it('does not let an unusable HTML base invalidate an absolute canonical', () => { + const html = ''; + expect(getCheck(auditHtml(html, 'page.html'), 'canonical').status).toBe('PASS'); + }); + + it('reports N/A when no schema block is present', () => { + const page = auditHtml(htmlPage({ jsonLd: '' }), 'https://example.test/page'); + + expect(getCheck(page, 'jsonld-syntax').status).toBe('N/A'); + }); + + it('keeps HTTP indexing out of scope for local HTML', () => { + const page = auditHtml(htmlPage(), 'https://example.test/page', { expectIndexable: true }); + + expect(getCheck(page, 'http-indexing').status).toBe('N/A'); + }); + + it('fails when any JSON-LD block is malformed', () => { + const page = auditHtml(htmlPage({ jsonLd: jsonLdScript('{"@context":') }), 'malformed-jsonld.html'); + expect(getCheck(page, 'jsonld-syntax').status).toBe('FAIL'); + }); + + it.each([ + ['a null root', 'null'], + ['a numeric root', '42'], + ['a string root', '"text"'], + ['an array containing a primitive', '[{"@type":"Thing"},1]'], + ['an array containing null', '[null]'], + ])('fails for JSON-LD with %s', (_caseName, payload) => { + const page = auditHtml(htmlPage({ jsonLd: jsonLdScript(payload) }), 'primitive-jsonld.html'); + expect(getCheck(page, 'jsonld-syntax').status).toBe('FAIL'); + }); + + it('passes JSON-LD objects, arrays of objects, and @graph without checking rich-result eligibility', () => { + const jsonLd = [ + jsonLdScript('{"name":"A structurally valid object"}'), + jsonLdScript('[{"@type":"Thing"},{"@type":"WebPage"}]'), + jsonLdScript('{"@context":"https://schema.org","@type":"NotARealSchemaType","@graph":[{"name":"Nested object"}]}'), + ].join(''); + const page = auditHtml(htmlPage({ jsonLd }), 'valid-jsonld.html'); + + expect(getCheck(page, 'jsonld-syntax').status).toBe('PASS'); + }); +}); + +describe('auditPath', () => { + it('audits .html and .htm files while rejecting unsupported file types', async () => { + const root = await makeTempDir(); + const htmlPath = join(root, 'index.html'); + const htmPath = join(root, 'legacy.htm'); + const textPath = join(root, 'notes.txt'); + await Promise.all([ + writeHtmlFile(htmlPath), + writeHtmlFile(htmPath), + writeFile(textPath, 'not HTML', 'utf8'), + ]); + + const htmlReport = await auditPath(htmlPath); + const htmReport = await auditPath(htmPath); + expect(htmlReport.pages).toHaveLength(1); + expect(htmReport.pages).toHaveLength(1); + expect(htmlReport.pages[0].target).toBe(htmlPath); + expect(htmReport.pages[0].target).toBe(htmPath); + expect(htmlReport.source).toBe('local-html'); + expect(htmlReport.contractVersion).toBe('1.0'); + await expect(auditPath(textPath)).rejects.toThrow(); + }); + + it('recurses in deterministic path order and skips node_modules, dot directories, and symlinks', async () => { + const root = await makeTempDir(); + const nested = join(root, 'a'); + const deep = join(root, 'z'); + await mkdir(nested, { recursive: true }); + await mkdir(deep, { recursive: true }); + await mkdir(join(root, 'node_modules', 'dependency'), { recursive: true }); + await mkdir(join(root, '.hidden'), { recursive: true }); + + const expectedFiles = [ + join(nested, 'first.htm'), + join(nested, 'second.html'), + join(root, 'root.html'), + join(deep, 'last.html'), + ]; + await Promise.all(expectedFiles.map((path) => writeHtmlFile(path))); + await writeHtmlFile(join(root, 'node_modules', 'dependency', 'ignored.html')); + await writeHtmlFile(join(root, '.hidden', 'ignored.html')); + const realFile = join(root, 'real.html'); + const symlinkPath = join(root, 'linked.html'); + await writeHtmlFile(realFile); + await symlink(realFile, symlinkPath, 'file'); + + const report = await auditPath(root); + expect(report.pages.map((page) => page.target)).toEqual([...expectedFiles, realFile].sort()); + expect(report.pages.some((page) => page.target.includes(`${join(root, 'node_modules')}/`))).toBe(false); + expect(report.pages.some((page) => page.target.includes(`${join(root, '.hidden')}/`))).toBe(false); + expect(report.pages.some((page) => page.target === symlinkPath)).toBe(false); + await expect(auditPath(symlinkPath)).rejects.toThrow(); + }); + + it('rejects a directory that contains no HTML files', async () => { + const root = await makeTempDir(); + await mkdir(join(root, 'nested'), { recursive: true }); + await writeFile(join(root, 'nested', 'notes.md'), 'No HTML here', 'utf8'); + + await expect(auditPath(root)).rejects.toThrow(); + }); + + it('reports duplicate titles and canonical URLs only on affected directory pages', async () => { + const root = await makeTempDir(); + const pages = [ + [ + 'title-a.html', + htmlPage({ title: ' Shared Topic ', canonical: 'https://example.test/title-a' }), + ], + [ + 'title-b.html', + htmlPage({ title: 'shared topic', canonical: 'https://example.test/title-b' }), + ], + [ + 'canonical-a.html', + htmlPage({ title: 'Canonical A', canonical: 'https://example.test/guide?topic=seo#first' }), + ], + [ + 'canonical-b.html', + htmlPage({ title: 'Canonical B', canonical: '/guide?topic=seo#second' }), + ], + [ + 'canonical-different-query.html', + htmlPage({ title: 'Canonical C', canonical: '/guide?topic=other#fragment' }), + ], + ] as const; + await Promise.all(pages.map(([name, html]) => writeHtmlFile(join(root, name), html))); + + const report = await auditPath(root, { baseUrl: 'https://example.test/' }); + const pageByName = new Map(report.pages.map((page) => [basename(page.target), page])); + const titleA = pageByName.get('title-a.html'); + const titleB = pageByName.get('title-b.html'); + const canonicalA = pageByName.get('canonical-a.html'); + const canonicalB = pageByName.get('canonical-b.html'); + const differentQuery = pageByName.get('canonical-different-query.html'); + + expect(titleA && findCheck(titleA, 'duplicate-document-title')?.status).toBe('WARNING'); + expect(titleB && findCheck(titleB, 'duplicate-document-title')?.status).toBe('WARNING'); + expect(canonicalA && findCheck(canonicalA, 'duplicate-canonical')?.status).toBe('WARNING'); + expect(canonicalB && findCheck(canonicalB, 'duplicate-canonical')?.status).toBe('WARNING'); + expect(differentQuery && findCheck(differentQuery, 'duplicate-canonical')).toBeUndefined(); + expect(differentQuery && findCheck(differentQuery, 'duplicate-document-title')).toBeUndefined(); + + const summary = report.pages.flatMap((page) => page.checks).reduce>((counts, check) => { + counts[check.status] = (counts[check.status] ?? 0) + 1; + return counts; + }, {}); + expect(report.summary).toEqual({ + PASS: summary.PASS ?? 0, + WARNING: summary.WARNING ?? 0, + FAIL: summary.FAIL ?? 0, + 'N/A': summary['N/A'] ?? 0, + }); + expect(report.limitations).toEqual(expect.any(Array)); + expect(Number.isNaN(Date.parse(report.timestamp))).toBe(false); + }); + + it('keeps same-page duplicate canonical tags in the canonical check without adding a directory duplicate', async () => { + const root = await makeTempDir(); + const pagePath = join(root, 'same-page.html'); + await writeHtmlFile( + pagePath, + 'One pageContent', + ); + + const report = await auditPath(root); + expect(report.pages).toHaveLength(1); + expect(getCheck(report.pages[0], 'canonical').status).toBe('FAIL'); + expect(findCheck(report.pages[0], 'duplicate-canonical')).toBeUndefined(); + }); +}); diff --git a/src/core/index.ts b/src/core/index.ts index ac3d002..2d33302 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -6,3 +6,4 @@ export * from './generator.js'; export * from './ai-prompt.js'; export * from './external-scorers.js'; export * from './merger.js'; +export * from './static-audit.js'; diff --git a/src/core/static-audit.ts b/src/core/static-audit.ts new file mode 100644 index 0000000..6f5cfe6 --- /dev/null +++ b/src/core/static-audit.ts @@ -0,0 +1,244 @@ +import * as cheerio from 'cheerio'; +import { lstat, readFile, readdir } from 'node:fs/promises'; +import { extname, join, relative, resolve, sep } from 'node:path'; + +export type StaticAuditStatus = 'PASS' | 'WARNING' | 'FAIL' | 'N/A'; + +export interface StaticAuditOptions { + expectIndexable?: boolean; + /** Absolute deployed page URL, or deployment root when auditing a directory. */ + baseUrl?: string; +} + +export interface StaticAuditCheck { + id: string; + status: StaticAuditStatus; + evidence: string[]; + message: string; + remediation: string | null; + validation: string; +} + +export interface StaticPageAudit { + target: string; + checks: StaticAuditCheck[]; +} + +export interface StaticAuditReport { + contractVersion: '1.0'; + source: 'local-html'; + pages: StaticPageAudit[]; + summary: Record; + limitations: string[]; + timestamp: string; +} + +function httpUrl(value: string, base?: string): URL { + if (/[\u0000-\u0020\u007f]/.test(value)) throw new Error('URL contains whitespace or control characters'); + const url = new URL(value, base); + if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) { + throw new Error('Expected an HTTP(S) URL without credentials'); + } + return url; +} + +/** Audits observed source HTML only; it neither fetches URLs nor changes the readiness score. */ +export function auditHtml(html: string, target: string, options: StaticAuditOptions = {}): StaticPageAudit { + const $ = cheerio.load(html); + const checks: StaticAuditCheck[] = []; + const add = (id: string, status: StaticAuditStatus, evidence: string[], message: string, + remediation: string | null, validation: string) => { + checks.push({ id, status, evidence, message, remediation, validation }); + }; + + const pageUrl = options.baseUrl ? httpUrl(options.baseUrl).href : undefined; + const titles = $('title').map((_, el) => $(el).text().trim()).get(); + const titleOk = titles.length === 1 && titles[0].length > 0; + add('document-title', titleOk ? 'PASS' : 'WARNING', titles, + titleOk ? 'One non-empty title element found.' : 'Expected one non-empty title element.', + titleOk ? null : 'Write one descriptive title in the document head; remove duplicate title elements.', + 'Rebuild and inspect the title element in the generated HTML.'); + + const descriptions = $('meta').filter((_, el) => + ($(el).attr('name') || '').trim().toLowerCase() === 'description') + .map((_, el) => $(el).attr('content')?.trim() || '').get(); + const descriptionOk = descriptions.length === 1 && descriptions[0].length > 0; + add('meta-description', descriptionOk ? 'PASS' : 'WARNING', descriptions, + descriptionOk ? 'One non-empty meta description found.' : 'Expected one non-empty meta description.', + descriptionOk ? null : 'Write a page-specific description and remove duplicate description tags.', + 'Inspect the rebuilt meta description; search engines may select a different snippet.'); + + const canonicals = $('link').filter((_, el) => + ($(el).attr('rel') || '').toLowerCase().split(/\s+/).includes('canonical')) + .map((_, el) => $(el).attr('href')?.trim() || '').get(); + const canonicalValidation = 'Rebuild and check the canonical URL, then verify its HTTP response and indexability on the deployed site.'; + if (canonicals.length === 0) { + add('canonical', 'WARNING', [], 'No HTML canonical declaration found; HTTP canonical headers were not checked.', + 'Review the intended canonical URL and declare it in HTML or the HTTP Link header where appropriate.', canonicalValidation); + } else if (canonicals.length > 1 || !canonicals[0]) { + add('canonical', 'FAIL', canonicals, 'Canonical declarations are multiple or empty.', + 'Emit one non-empty canonical declaration for the intended page.', canonicalValidation); + } else { + const href = canonicals[0]; + let base = pageUrl; + const htmlBase = $('base[href]').first().attr('href'); + try { + const isAbsolute = /^[a-z][a-z\d+.-]*:/i.test(href); + if (htmlBase !== undefined && !isAbsolute) { + const baseValue = htmlBase.trim(); + if (!pageUrl && !/^[a-z][a-z\d+.-]*:/i.test(baseValue)) { + httpUrl(baseValue, 'https://audit.invalid/'); + } else { + base = httpUrl(baseValue, pageUrl).href; + } + } + if (!isAbsolute && !base) { + // Validate the reference shape without inventing the deployed origin. + httpUrl(href, 'https://audit.invalid/'); + add('canonical', 'N/A', [href], 'A relative canonical needs the deployed page URL for resolution.', + 'Supply --base-url or emit an absolute canonical URL.', canonicalValidation); + } else { + const url = httpUrl(href, base); + const hadFragment = Boolean(url.hash); + url.hash = ''; + add('canonical', hadFragment ? 'WARNING' : 'PASS', [url.href], + hadFragment ? 'Canonical contains a fragment.' : 'One HTTP(S) canonical URL resolves; its destination was not fetched.', + hadFragment ? 'Use a canonical URL without a fragment.' : null, canonicalValidation); + } + } catch { + add('canonical', 'FAIL', canonicals, 'Canonical URL or HTML base cannot resolve to an HTTP(S) URL without credentials.', + 'Correct the canonical href and any HTML base href.', canonicalValidation); + } + } + + const robotTags = $('meta').filter((_, el) => + ['robots', 'googlebot'].includes(($(el).attr('name') || '').trim().toLowerCase())); + const robotEvidence: string[] = []; + let blocksIndexing = false; + robotTags.each((_, el) => { + const name = ($(el).attr('name') || '').trim().toLowerCase(); + const content = $(el).attr('content') || ''; + robotEvidence.push(`${name}: ${content}`); + // Keep parameter values attached to their directive, e.g. max-image-preview: none. + const tokens = content.toLowerCase().replace(/:\s+/g, ':').split(/[\s,]+/); + if (tokens.includes('noindex') || tokens.includes('none')) blocksIndexing = true; + }); + add('indexing-directives', blocksIndexing ? (options.expectIndexable ? 'FAIL' : 'WARNING') : 'PASS', robotEvidence, + blocksIndexing + ? 'An HTML robots or googlebot directive blocks standalone indexing; index does not override noindex.' + : 'No noindex or none token found in HTML robots/googlebot meta tags. HTTP headers and actual indexing remain unverified.', + blocksIndexing ? 'Confirm the page policy. Remove noindex/none only if this page should be indexed.' : null, + 'Inspect every robots/googlebot tag after rebuilding, then check deployed headers and Search Console URL Inspection.'); + + const blocks = $('script').filter((_, el) => + ($(el).attr('type') || '').trim().toLowerCase() === 'application/ld+json'); + const jsonEvidence: string[] = []; + let invalidJson = false; + const isObject = (value: unknown): boolean => value !== null && typeof value === 'object' && !Array.isArray(value); + blocks.each((index, el) => { + try { + const value: unknown = JSON.parse($(el).html() || ''); + if (!(isObject(value) || (Array.isArray(value) && value.every(isObject)))) { + invalidJson = true; + jsonEvidence.push(`Block ${index + 1}: expected an object or an array of objects.`); + } else { + jsonEvidence.push(`Block ${index + 1}: JSON parses with an object or object-array root.`); + } + } catch { + invalidJson = true; + jsonEvidence.push(`Block ${index + 1}: malformed JSON.`); + } + }); + add('jsonld-syntax', blocks.length === 0 ? 'N/A' : invalidJson ? 'FAIL' : 'PASS', jsonEvidence, + blocks.length === 0 ? 'No JSON-LD present; structured data is optional.' + : invalidJson ? 'JSON-LD has a syntax or root-shape error.' + : 'JSON syntax and root shape pass. Schema vocabulary, visible-content consistency and rich-result eligibility were not validated.', + invalidJson ? 'Fix the reported blocks and validate the appropriate schema against visible page content.' : null, + 'Re-run this audit, then use Schema Markup Validator and the applicable search-engine validation tool.'); + + add('http-indexing', 'N/A', [], + 'Local HTML cannot establish HTTP status, X-Robots-Tag, robots.txt access, redirects, or actual search indexing.', + 'Check the deployed response and crawler policy; use Search Console for Google indexing evidence.', + 'Inspect the deployed HTTP response and Search Console URL Inspection.'); + return { target, checks }; +} + +function markDuplicates(pages: StaticPageAudit[], sourceId: string, id: string, normalize: (value: string) => string): void { + const groups = new Map(); + for (const page of pages) { + const check = page.checks.find((item) => item.id === sourceId); + if (!check || (check.status !== 'PASS' && !(sourceId === 'canonical' && check.status === 'WARNING')) + || check.evidence.length !== 1) continue; + const value = normalize(check.evidence[0]); + if (value) groups.set(value, [...(groups.get(value) || []), page]); + } + for (const [value, matches] of groups) { + if (matches.length < 2) continue; + for (const page of matches) { + page.checks.push({ + id, status: 'WARNING', evidence: [value, ...matches.map((match) => match.target)], + message: sourceId === 'canonical' + ? 'Multiple audited files point to the same canonical. This may be an intentional consolidation.' + : 'Multiple audited files share a title. Review whether they serve distinct page purposes.', + remediation: 'Review the listed files and correct template reuse only where the duplication is unintended.', + validation: 'Rebuild and rerun the directory audit; confirm any intentional duplicates manually.', + }); + } + } +} + +/** Recursively audits local HTML files. Read/parse failures stop the run rather than silently omitting pages. */ +export async function auditPath(input: string, options: StaticAuditOptions = {}): Promise { + if (options.baseUrl) httpUrl(options.baseUrl); + const root = resolve(input); + const rootStat = await lstat(root); + if (rootStat.isSymbolicLink()) throw new Error('Symbolic link targets are not supported.'); + const files: string[] = []; + async function collect(path: string): Promise { + const info = await lstat(path); + if (info.isSymbolicLink()) return; + if (info.isDirectory()) { + const entries = await readdir(path); + for (const entry of entries.sort()) { + if (entry.startsWith('.') || entry === 'node_modules') continue; + await collect(join(path, entry)); + } + } else if (info.isFile() && ['.html', '.htm'].includes(extname(path).toLowerCase())) { + files.push(path); + } + } + if (!rootStat.isDirectory() && !['.html', '.htm'].includes(extname(root).toLowerCase())) { + throw new Error('Static audit supports .html and .htm files or directories containing HTML.'); + } + await collect(root); + if (!files.length) throw new Error('No HTML files found to audit.'); + const pages: StaticPageAudit[] = []; + for (const file of files.sort()) { + const info = await lstat(file); + if (info.isSymbolicLink() || !info.isFile()) throw new Error(`Input changed during audit: ${file}`); + if (info.size > 5 * 1024 * 1024) throw new Error(`HTML file exceeds the 5 MB audit limit: ${file}`); + let baseUrl = options.baseUrl; + if (rootStat.isDirectory() && baseUrl) { + const rootUrl = httpUrl(baseUrl); + if (rootUrl.search || rootUrl.hash) throw new Error('A directory --base-url must not contain a query or fragment.'); + if (!rootUrl.pathname.endsWith('/')) rootUrl.pathname += '/'; + const deployedPath = relative(root, file).split(sep).map(encodeURIComponent).join('/'); + baseUrl = new URL(deployedPath, rootUrl).href; + } + pages.push(auditHtml(await readFile(file, 'utf8'), file, { ...options, baseUrl })); + } + markDuplicates(pages, 'document-title', 'duplicate-document-title', (value) => value.replace(/\s+/g, ' ').trim().toLowerCase()); + markDuplicates(pages, 'canonical', 'duplicate-canonical', (value) => value); + const summary: Record = { PASS: 0, WARNING: 0, FAIL: 0, 'N/A': 0 }; + for (const page of pages) for (const check of page.checks) summary[check.status]++; + return { + contractVersion: '1.0', source: 'local-html', pages, summary, + limitations: [ + 'Source HTML only. No browser rendering, network requests, HTTP headers, robots.txt, sitemap or search-performance data were inspected.', + 'PASS applies to the named check only; it does not establish crawlability, indexing, ranking, AI citation or rich-result eligibility.', + 'Cross-page findings cover only audited files. Symbolic links, hidden entries and node_modules are excluded.', + 'Directory base URLs map relative file paths directly; hosting-specific clean-URL rewrites are not inferred.', + ], + timestamp: new Date().toISOString(), + }; +} From bbf59dd87ebdb41b68fd0970e3ef43ad8597b34c Mon Sep 17 00:00:00 2001 From: Te-Shu Wang Date: Mon, 7 Sep 2026 03:56:09 +0800 Subject: [PATCH 3/5] feat: add bounded site audit --- CHANGELOG.md | 1 + README.md | 14 + docs/methodology.md | 8 + src/cli/index.ts | 63 ++- src/core/__tests__/site-audit.test.ts | 238 +++++++++ src/core/index.ts | 1 + src/core/scanner.ts | 21 +- src/core/site-audit.ts | 742 ++++++++++++++++++++++++++ src/core/types.ts | 44 ++ 9 files changed, 1128 insertions(+), 4 deletions(-) create mode 100644 src/core/__tests__/site-audit.test.ts create mode 100644 src/core/site-audit.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 5389c3f..abdb1ec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ All notable user-visible changes will be documented here. The project follows Se - Added `audit-build` for local HTML directories with cross-page title/canonical review, syntax checks and optional `--expect-indexable --fail-on-error` CI gates. - Added an evidence-backed `audit` command for one URL or HTML/Markdown file, with versioned `PASS`, `WARNING`, `FAIL`, and `N/A` checks. - Added structured observations, remediation, validation guidance, and explicit limitations for HTTP, metadata, headings, canonical, robots directives, links, images, and JSON-LD. +- Added a bounded, same-origin `audit-site` command for robots-aware page discovery, sitemap comparison, HTTP failures, redirect chains, internal-link targets, canonical conflicts, orphan candidates, and duplicate titles. ### Compatibility diff --git a/README.md b/README.md index 415ae39..f080d81 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,7 @@ npx aeoptimize scan https://example.com npx aeoptimize scan ./dist --dir npx aeoptimize scan ./dist --dir --json npx aeoptimize audit https://example.com --json +npx aeoptimize audit-site https://example.com --max-pages 20 --json ``` Example output: @@ -78,6 +79,19 @@ Each check returns `PASS`, `WARNING`, `FAIL`, or `N/A`, the observed evidence, a The command intentionally reports unavailable site-wide and external measurements as limitations. It does not infer robots.txt policy, sitemap membership, hreflang reciprocity, broken-link status, Core Web Vitals, analytics, or actual search-engine index state from one page. +## Bounded site audit + +`audit-site` follows same-origin links in deterministic order and stops at an explicit page limit. It reads robots.txt before subsequent page requests, discovers same-origin sitemap files, and uses response HTML without browser rendering. + +```bash +npx aeoptimize audit-site https://example.com +npx aeoptimize audit-site https://example.com --max-pages 50 --json +``` + +The site contract reports bounded crawl coverage, robots policy, page status, redirect chains, internal link targets, canonical consistency, sitemap discrepancies, sitemap-only orphan candidates, and duplicate titles. Sitemap-only pages remain candidates until a sufficiently complete crawl or server-log evidence confirms their discovery state. + +The default limit is 20 page requests and the accepted range is 1–200. Cross-origin page links are recorded only as counts, and subsequent redirects outside the audited origin are not followed. JavaScript-inserted links, actual search-engine crawl/index state, rankings, traffic, and conversions remain outside this contract. + ## How it compares | | aeoptimize | Lighthouse-style SEO audits | Hosted AEO/GEO platforms | diff --git a/docs/methodology.md b/docs/methodology.md index af483e7..3edebb8 100644 --- a/docs/methodology.md +++ b/docs/methodology.md @@ -79,6 +79,14 @@ The `audit` command is separate from the v0.6 score contract. It reports one of Each check includes observed evidence, an explanation, optional remediation, and a validation step. The contract does not derive robots.txt policy, sitemap membership, hreflang reciprocity, site-wide duplication, orphan status, Core Web Vitals, analytics, or search-engine index state from a single document. +### Bounded site audit + +The `audit-site` contract uses a same-origin, sequential queue with an explicit 1–200 page limit. It processes links in discovery order before sitemap-only seeds, reads applicable `aeoptimize` or wildcard robots rules, and does not follow subsequent redirects outside the audited origin. + +The crawler uses response HTML without browser rendering. A Sitemap-only URL with no internal inlink is reported as an orphan candidate because JavaScript navigation, pages beyond the configured limit, and other discovery sources may still link to it. Broken-link findings require an observed failed response; queued but unfetched links remain warnings. + +robots.txt matching covers applicable user-agent groups, `Allow`, `Disallow`, `*` wildcards, and `$` endings. Unusual policies need manual review. An unavailable robots.txt response that is not an ordinary 404 causes conservative skipping of subsequent matching URLs. + ## Primary sources - [Google Search: AI features and your website](https://developers.google.com/search/docs/appearance/ai-features) diff --git a/src/cli/index.ts b/src/cli/index.ts index 07e3575..a1be550 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -6,11 +6,12 @@ import { readFile, writeFile, mkdir, stat } from 'node:fs/promises'; import { join, extname } from 'node:path'; import { scan, scanDirectory, parseHtml, parseMarkdown, scanUrl } from '../core/scanner.js'; import { audit } from '../core/audit.js'; +import { auditSite } from '../core/site-audit.js'; import { generate } from '../core/generator.js'; import { detectAvailableCLIs, scoreWithAllAvailable } from '../core/external-scorers.js'; import { mergeScores } from '../core/merger.js'; import { auditPath } from '../core/static-audit.js'; -import type { AuditReport, AuditStatus, ScanReport, MultiAiReport, DimensionScores, ScanTarget, SiteInfo, AiScorerResult } from '../core/types.js'; +import type { AuditReport, AuditStatus, SiteAuditReport, ScanReport, MultiAiReport, DimensionScores, ScanTarget, SiteInfo, AiScorerResult } from '../core/types.js'; const HOOK_BEGIN_MARKER = '# BEGIN aeoptimize'; const HOOK_END_MARKER = '# END aeoptimize'; @@ -89,6 +90,29 @@ program } }); +program + .command('audit-site ') + .description('Crawl one origin with bounded evidence-backed site checks') + .option('--max-pages ', 'Maximum page requests from 1 to 200', '20') + .option('--json', 'Output the versioned site-audit JSON contract') + .action(async (target: string, options: { maxPages: string; json?: boolean }) => { + try { + const resolved = resolveTarget(target); + if (resolved.type !== 'url') { + throw new Error('Site audit requires an http or https URL.'); + } + const report = await auditSite(resolved.path, { maxPages: Number(options.maxPages) }); + if (options.json) { + console.log(JSON.stringify(report, null, 2)); + } else { + printSiteAuditReport(report); + } + } catch (err) { + console.error(chalk.red(`Error: ${(err as Error).message}`)); + process.exit(1); + } + }); + program .command('audit-build ') .description('Audit local built HTML with evidence and optional CI failure on errors') @@ -547,6 +571,43 @@ function printAuditReport(report: AuditReport): void { console.log(''); } +function printSiteAuditReport(report: SiteAuditReport): void { + console.log(''); + console.log(chalk.bold(' Bounded Site Audit')); + console.log(chalk.dim(` Contract ${report.contractVersion} | ${report.timestamp}`)); + console.log(chalk.dim(` ${report.startUrl} | ${report.crawledPages}/${report.maxPages} pages`)); + console.log(''); + console.log( + ` ${chalk.green(`PASS ${report.summary.PASS}`)} ` + + `${chalk.yellow(`WARNING ${report.summary.WARNING}`)} ` + + `${chalk.red(`FAIL ${report.summary.FAIL}`)} ` + + `${chalk.gray(`N/A ${report.summary['N/A']}`)}`, + ); + console.log(''); + + for (const item of report.checks) { + const color = auditStatusColor(item.status); + console.log(` ${color(`[${item.status}]`)} ${chalk.bold(item.label)} ${chalk.dim(`(${item.id})`)}`); + console.log(` ${item.explanation}`); + for (const itemEvidence of item.evidence) { + console.log(chalk.dim(` Evidence ${itemEvidence.source}: ${JSON.stringify(itemEvidence.observed)}`)); + } + if (item.remediation) console.log(` ${chalk.cyan('Fix:')} ${item.remediation}`); + console.log(chalk.dim(` Validate: ${item.validation}`)); + console.log(''); + } + + console.log(chalk.bold(' Pages')); + for (const page of report.pages) { + const status = page.status >= 200 && page.status < 300 ? chalk.green(String(page.status)) : chalk.red(String(page.status)); + console.log(` ${status} ${page.requestedUrl}${page.finalUrl !== page.requestedUrl ? ` -> ${page.finalUrl}` : ''}`); + } + console.log(''); + console.log(chalk.bold(' Limits')); + for (const limitation of report.limitations) console.log(chalk.dim(` - ${limitation}`)); + console.log(''); +} + function printDimensionBar(label: string, score: number, max: number): void { const pct = score / max; const barWidth = 20; diff --git a/src/core/__tests__/site-audit.test.ts b/src/core/__tests__/site-audit.test.ts new file mode 100644 index 0000000..9a57cac --- /dev/null +++ b/src/core/__tests__/site-audit.test.ts @@ -0,0 +1,238 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { auditSite, parseRobotsTxt, parseSitemapDocument, robotsAllows } from '../site-audit.js'; + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe('robots policy', () => { + it('selects the most specific user-agent group and applies longest-match precedence', () => { + const policy = parseRobotsTxt(` + User-agent: * + Disallow: /private + Allow: /private/public$ + Sitemap: https://example.com/sitemap.xml + + User-agent: aeoptimize + Disallow: /preview + Allow: /preview/public + `); + + expect(policy.sitemapUrls).toEqual(['https://example.com/sitemap.xml']); + expect(robotsAllows('https://example.com/private', policy)).toBe(true); + expect(robotsAllows('https://example.com/preview/draft', policy)).toBe(false); + expect(robotsAllows('https://example.com/preview/public', policy)).toBe(true); + }); + + it('uses wildcard rules when no specific product token matches', () => { + const policy = parseRobotsTxt(` + User-agent: * + Disallow: /private + Allow: /private/public$ + `, 'another-crawler'); + + expect(robotsAllows('https://example.com/private', policy)).toBe(false); + expect(robotsAllows('https://example.com/private/public', policy)).toBe(true); + expect(robotsAllows('https://example.com/private/public/child', policy)).toBe(false); + }); +}); + +describe('sitemap parsing', () => { + it('parses URL sets and sitemap indexes without inferring other XML links', () => { + expect(parseSitemapDocument(` + + https://example.com/ + https://example.com/about + + `)).toEqual({ + kind: 'urlset', + urls: ['https://example.com/', 'https://example.com/about'], + }); + + expect(parseSitemapDocument(` + + https://example.com/pages.xml + + `)).toEqual({ kind: 'index', urls: ['https://example.com/pages.xml'] }); + }); +}); + +describe('auditSite', () => { + it('reports broken links, sitemap-only pages, duplicate titles, and robots skips', async () => { + const fetchMock = vi.fn(async (input: string | URL, init?: RequestInit) => { + const url = input.toString(); + expect(init?.redirect).toBe('manual'); + expect(new Headers(init?.headers).get('user-agent')).toBe('aeoptimize-site-audit'); + + if (url === 'https://example.com/') { + return new Response(` + Home +

Home

AboutMissingPrivateOutside + `, { status: 200, headers: { 'content-type': 'text/html' } }); + } + if (url === 'https://example.com/robots.txt') { + return new Response('User-agent: *\nDisallow: /private\nSitemap: https://example.com/sitemap.xml\n', { status: 200 }); + } + if (url === 'https://example.com/sitemap.xml') { + return new Response(` + + https://example.com/ + https://example.com/about + https://example.com/orphan + https://example.com/missing + + `, { status: 200, headers: { 'content-type': 'application/xml' } }); + } + if (url === 'https://example.com/about') { + return new Response(` + Shared title +

About

Home + `, { status: 200, headers: { 'content-type': 'text/html' } }); + } + if (url === 'https://example.com/orphan') { + return new Response(` + Shared title +

Orphan candidate

+ `, { status: 200, headers: { 'content-type': 'text/html' } }); + } + if (url === 'https://example.com/missing') { + return new Response('MissingGone', { + status: 404, + headers: { 'content-type': 'text/html' }, + }); + } + throw new Error(`Unexpected fetch: ${url}`); + }); + vi.stubGlobal('fetch', fetchMock); + + const report = await auditSite('https://example.com/', { maxPages: 10 }); + + expect(report.contractVersion).toBe('1.0'); + expect(report.crawledPages).toBe(4); + expect(report.truncated).toBe(false); + expect(Object.keys(report).sort()).toEqual([ + 'checks', + 'contractVersion', + 'crawledPages', + 'limitations', + 'maxPages', + 'origin', + 'pages', + 'robots', + 'sitemaps', + 'startUrl', + 'summary', + 'timestamp', + 'truncated', + ]); + expect(Object.values(report.summary).reduce((sum, count) => sum + count, 0)).toBe(report.checks.length); + expect(Object.keys(report.pages[0]).sort()).toEqual([ + 'canonicalLinks', + 'contentType', + 'discoveredFrom', + 'externalLinkCount', + 'finalUrl', + 'internalLinkCount', + 'language', + 'redirects', + 'requestedUrl', + 'status', + 'statusText', + 'title', + ]); + expect(report.robots.skippedUrls).toEqual(['https://example.com/private']); + expect(report.pages.map((page) => page.requestedUrl)).toEqual([ + 'https://example.com/', + 'https://example.com/about', + 'https://example.com/missing', + 'https://example.com/orphan', + ]); + expect(report.checks.find((check) => check.id === 'site-http-status')?.status).toBe('FAIL'); + expect(report.checks.find((check) => check.id === 'internal-link-targets')?.status).toBe('FAIL'); + expect(report.checks.find((check) => check.id === 'canonical-consistency')?.status).toBe('PASS'); + expect(report.checks.find((check) => check.id === 'sitemap-consistency')?.status).toBe('FAIL'); + expect(report.checks.find((check) => check.id === 'orphan-candidates')).toMatchObject({ status: 'WARNING' }); + expect(report.checks.find((check) => check.id === 'duplicate-titles')).toMatchObject({ status: 'WARNING' }); + expect(fetchMock.mock.calls.some(([url]) => url.toString() === 'https://example.com/private')).toBe(false); + expect(fetchMock.mock.calls.some(([url]) => url.toString() === 'https://outside.example/')).toBe(false); + }); + + it('marks queued internal targets unchecked when the page limit is reached', async () => { + const fetchMock = vi.fn(async (input: string | URL) => { + const url = input.toString(); + if (url === 'https://example.com/') { + return new Response('Home

Home

AB', { + status: 200, + headers: { 'content-type': 'text/html' }, + }); + } + if (url === 'https://example.com/robots.txt' || url === 'https://example.com/sitemap.xml') { + return new Response('', { status: 404 }); + } + throw new Error(`Unexpected fetch: ${url}`); + }); + vi.stubGlobal('fetch', fetchMock); + + const report = await auditSite('https://example.com/', { maxPages: 1 }); + + expect(report.crawledPages).toBe(1); + expect(report.truncated).toBe(true); + expect(report.checks.find((check) => check.id === 'crawl-coverage')?.status).toBe('WARNING'); + expect(report.checks.find((check) => check.id === 'internal-link-targets')?.status).toBe('WARNING'); + }); + + it('does not follow a subsequent cross-origin redirect', async () => { + const fetchMock = vi.fn(async (input: string | URL) => { + const url = input.toString(); + if (url === 'https://example.com/') { + return new Response('Home

Home

Leave', { + status: 200, + headers: { 'content-type': 'text/html' }, + }); + } + if (url === 'https://example.com/robots.txt' || url === 'https://example.com/sitemap.xml') { + return new Response('', { status: 404 }); + } + if (url === 'https://example.com/leave') { + return new Response(null, { status: 302, headers: { location: 'https://outside.example/' } }); + } + throw new Error(`Unexpected fetch: ${url}`); + }); + vi.stubGlobal('fetch', fetchMock); + + const report = await auditSite('https://example.com/', { maxPages: 5 }); + + expect(report.pages.find((page) => page.requestedUrl.endsWith('/leave'))).toMatchObject({ status: 0 }); + expect(fetchMock.mock.calls.some(([url]) => url.toString() === 'https://outside.example/')).toBe(false); + }); + + it('stops subsequent page crawling when robots policy is temporarily unavailable', async () => { + const fetchMock = vi.fn(async (input: string | URL) => { + const url = input.toString(); + if (url === 'https://example.com/') { + return new Response('Home

Home

Next', { + status: 200, + headers: { 'content-type': 'text/html' }, + }); + } + if (url === 'https://example.com/robots.txt') return new Response('', { status: 503 }); + if (url === 'https://example.com/sitemap.xml') return new Response('', { status: 404 }); + throw new Error(`Unexpected fetch: ${url}`); + }); + vi.stubGlobal('fetch', fetchMock); + + const report = await auditSite('https://example.com/', { maxPages: 5 }); + + expect(report.crawledPages).toBe(0); + expect(report.robots.status).toBe(503); + expect(report.robots.skippedUrls).toEqual(['https://example.com/']); + expect(report.checks.find((check) => check.id === 'robots-policy')?.status).toBe('WARNING'); + expect(fetchMock.mock.calls.some(([url]) => url.toString() === 'https://example.com/next')).toBe(false); + }); + + it('validates the maximum page boundary', async () => { + await expect(auditSite('https://example.com/', { maxPages: 0 })).rejects.toThrow('--max-pages'); + await expect(auditSite('https://example.com/', { maxPages: 201 })).rejects.toThrow('--max-pages'); + await expect(auditSite('https://example.com/', { maxPages: 1.5 })).rejects.toThrow('--max-pages'); + }); +}); diff --git a/src/core/index.ts b/src/core/index.ts index 2d33302..5a7c6a6 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -1,6 +1,7 @@ export * from './types.js'; export * from './scanner.js'; export * from './audit.js'; +export * from './site-audit.js'; export * from './rules.js'; export * from './generator.js'; export * from './ai-prompt.js'; diff --git a/src/core/scanner.ts b/src/core/scanner.ts index e1ec895..6bf7a93 100644 --- a/src/core/scanner.ts +++ b/src/core/scanner.ts @@ -341,10 +341,17 @@ export interface UrlResource { renderedWithBrowser: boolean; } +export interface UrlFetchOptions { + render?: boolean; + init?: RequestInit; + allowedOrigin?: string; +} + async function fetchWithSafeRedirects( input: string | URL, init?: RequestInit, maxRedirects = 10, + allowedOrigin?: string, ): Promise<{ response: Response; finalUrl: string; redirects: RedirectHop[] }> { let currentUrl = typeof input === 'string' ? validateUrl(input) : validateUrl(input.toString()); const redirects: RedirectHop[] = []; @@ -365,6 +372,9 @@ async function fetchWithSafeRedirects( } const nextUrl = validateUrl(new URL(location, currentUrl).toString()); + if (allowedOrigin && nextUrl.origin !== allowedOrigin) { + throw new Error(`Redirect left the allowed origin: ${nextUrl.origin}`); + } redirects.push({ from: currentUrl.toString(), to: nextUrl.toString(), @@ -421,14 +431,19 @@ function isSpaLikely(html: string): boolean { return contentTags < 10 && scripts > 3; } -export async function fetchUrlResource(url: string): Promise { +export async function fetchUrlResource(url: string, options: UrlFetchOptions = {}): Promise { validateUrl(url); - const { response, finalUrl, redirects } = await fetchWithSafeRedirects(url); + const { response, finalUrl, redirects } = await fetchWithSafeRedirects( + url, + options.init, + 10, + options.allowedOrigin, + ); let html = await response.text(); let renderedWithBrowser = false; - if (response.ok && isSpaLikely(html)) { + if (options.render !== false && response.ok && isSpaLikely(html)) { const result = await fetchWithPuppeteer(finalUrl); if (result.rendered) { html = result.html; diff --git a/src/core/site-audit.ts b/src/core/site-audit.ts new file mode 100644 index 0000000..b5c7264 --- /dev/null +++ b/src/core/site-audit.ts @@ -0,0 +1,742 @@ +import * as cheerio from 'cheerio'; +import { fetchUrlResource, parseHtml, type UrlResource } from './scanner.js'; +import type { + AuditCheck, + AuditEvidence, + AuditStatus, + ParsedDocument, + SiteAuditPage, + SiteAuditReport, + SiteAuditSitemap, +} from './types.js'; + +const SITE_AUDIT_CONTRACT_VERSION = '1.0' as const; +const DEFAULT_MAX_PAGES = 20; +const MAX_ALLOWED_PAGES = 200; +const MAX_SITEMAPS = 5; +const REQUEST_TIMEOUT_MS = 15_000; + +export interface SiteAuditOptions { + maxPages?: number; +} + +interface RobotsRule { + directive: 'allow' | 'disallow'; + pattern: string; +} + +export interface RobotsPolicy { + rules: RobotsRule[]; + sitemapUrls: string[]; +} + +interface RobotsGroup { + agents: string[]; + rules: RobotsRule[]; +} + +interface SitemapParseResult { + kind: SiteAuditSitemap['kind']; + urls: string[]; +} + +interface CrawledPage { + output: SiteAuditPage; + document: ParsedDocument | null; + internalTargets: string[]; + blocksIndexing: boolean; +} + +function normalizeUrl(value: string, base?: string): string { + const url = base ? new URL(value, base) : new URL(value); + if (url.protocol !== 'http:' && url.protocol !== 'https:') { + throw new Error(`Unsupported scheme: ${url.protocol}`); + } + url.hash = ''; + return url.toString(); +} + +function escapeRegExp(value: string): string { + return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function ruleMatches(rule: RobotsRule, pathAndQuery: string): boolean { + if (!rule.pattern) return false; + const anchored = rule.pattern.endsWith('$'); + const body = anchored ? rule.pattern.slice(0, -1) : rule.pattern; + const expression = body.split('*').map(escapeRegExp).join('.*'); + return new RegExp(`^${expression}${anchored ? '$' : ''}`).test(pathAndQuery); +} + +export function robotsAllows(urlValue: string, policy: RobotsPolicy): boolean { + const url = new URL(urlValue); + const pathAndQuery = `${url.pathname}${url.search}`; + const matches = policy.rules + .filter((rule) => ruleMatches(rule, pathAndQuery)) + .sort((left, right) => { + const specificity = (rule: RobotsRule) => rule.pattern.replace(/[\*$]/g, '').length; + const difference = specificity(right) - specificity(left); + if (difference !== 0) return difference; + return left.directive === 'allow' ? -1 : 1; + }); + if (matches.length === 0) return true; + return matches[0].directive === 'allow'; +} + +export function parseRobotsTxt(text: string, userAgent = 'aeoptimize'): RobotsPolicy { + const groups: RobotsGroup[] = []; + const sitemapUrls: string[] = []; + let current: RobotsGroup | null = null; + + for (const rawLine of text.split(/\r?\n/)) { + const line = rawLine.replace(/#.*$/, '').trim(); + if (!line) continue; + const separator = line.indexOf(':'); + if (separator < 0) continue; + const field = line.slice(0, separator).trim().toLowerCase(); + const value = line.slice(separator + 1).trim(); + + if (field === 'sitemap') { + if (value) sitemapUrls.push(value); + continue; + } + + if (field === 'user-agent') { + if (!current || current.rules.length > 0) { + current = { agents: [], rules: [] }; + groups.push(current); + } + if (value) current.agents.push(value.toLowerCase()); + continue; + } + + if ((field === 'allow' || field === 'disallow') && current) { + if (field === 'disallow' && value === '') continue; + current.rules.push({ directive: field, pattern: value }); + } + } + + const normalizedAgent = userAgent.toLowerCase(); + const specificGroups = groups.filter((group) => + group.agents.some((agent) => agent !== '*' && normalizedAgent.includes(agent)), + ); + let selectedGroups: RobotsGroup[]; + if (specificGroups.length > 0) { + const longestMatch = Math.max(...specificGroups.flatMap((group) => + group.agents + .filter((agent) => agent !== '*' && normalizedAgent.includes(agent)) + .map((agent) => agent.length), + )); + selectedGroups = specificGroups.filter((group) => + group.agents.some((agent) => agent !== '*' && normalizedAgent.includes(agent) && agent.length === longestMatch), + ); + } else { + selectedGroups = groups.filter((group) => group.agents.includes('*')); + } + + return { + rules: selectedGroups.flatMap((group) => group.rules), + sitemapUrls: [...new Set(sitemapUrls)], + }; +} + +export function parseSitemapDocument(xml: string): SitemapParseResult { + const $ = cheerio.load(xml, { xmlMode: true }); + if ($('sitemapindex').length > 0) { + return { + kind: 'index', + urls: $('sitemap > loc').map((_, element) => $(element).text().trim()).get().filter(Boolean), + }; + } + if ($('urlset').length > 0) { + return { + kind: 'urlset', + urls: $('url > loc').map((_, element) => $(element).text().trim()).get().filter(Boolean), + }; + } + return { kind: 'unknown', urls: [] }; +} + +function observed(source: AuditEvidence['source'], values: AuditEvidence['observed']): AuditEvidence { + return { source, observed: values }; +} + +function check( + id: string, + label: string, + status: AuditStatus, + values: AuditEvidence['observed'], + explanation: string, + remediation: string | null, + validation: string, + source: AuditEvidence['source'] = 'derived', +): AuditCheck { + return { + id, + label, + status, + evidence: [observed(source, values)], + explanation, + remediation, + validation, + }; +} + +function isHtmlResource(resource: UrlResource): boolean { + return resource.contentType?.toLowerCase().includes('html') === true || + /^\s*(?: { + return fetchUrlResource(url, { + render: false, + init: { + headers: { 'user-agent': 'aeoptimize-site-audit' }, + signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), + }, + allowedOrigin, + }); +} + +async function loadRobots(origin: string): Promise<{ + url: string; + status: number; + policy: RobotsPolicy; +}> { + const url = `${origin}/robots.txt`; + try { + const resource = await fetchForSite(url, origin); + if (resource.status === 200) { + return { url, status: 200, policy: parseRobotsTxt(resource.html) }; + } + if (resource.status === 401 || resource.status === 403 || resource.status === 429 || resource.status >= 500) { + return { + url, + status: resource.status, + policy: { rules: [{ directive: 'disallow', pattern: '/' }], sitemapUrls: [] }, + }; + } + return { url, status: resource.status, policy: { rules: [], sitemapUrls: [] } }; + } catch { + return { + url, + status: 0, + policy: { rules: [{ directive: 'disallow', pattern: '/' }], sitemapUrls: [] }, + }; + } +} + +async function loadSitemaps(origin: string, initialUrls: string[]): Promise<{ + reports: SiteAuditSitemap[]; + pageUrls: string[]; +}> { + const reports: SiteAuditSitemap[] = []; + const pageUrls: string[] = []; + const queue = initialUrls.length > 0 ? [...initialUrls] : [`${origin}/sitemap.xml`]; + const visited = new Set(); + + while (queue.length > 0 && visited.size < MAX_SITEMAPS) { + const rawUrl = queue.shift()!; + let url: string; + try { + url = normalizeUrl(rawUrl, `${origin}/`); + } catch { + continue; + } + if (new URL(url).origin !== origin || visited.has(url)) continue; + visited.add(url); + + try { + const resource = await fetchForSite(url, origin); + if (resource.status !== 200) { + reports.push({ url, status: resource.status, kind: 'unknown', urlCount: 0 }); + continue; + } + const parsed = parseSitemapDocument(resource.html); + reports.push({ url, status: resource.status, kind: parsed.kind, urlCount: parsed.urls.length }); + for (const location of parsed.urls) { + try { + const normalized = normalizeUrl(location, url); + if (new URL(normalized).origin !== origin) continue; + if (parsed.kind === 'index') queue.push(normalized); + if (parsed.kind === 'urlset') pageUrls.push(normalized); + } catch { + // Invalid sitemap locations are ignored and surfaced through the unknown/missing coverage checks. + } + } + } catch { + reports.push({ url, status: 0, kind: 'unknown', urlCount: 0 }); + } + } + + return { reports, pageUrls: [...new Set(pageUrls)] }; +} + +function validateMaxPages(value: number | undefined): number { + const maxPages = value ?? DEFAULT_MAX_PAGES; + if (!Number.isInteger(maxPages) || maxPages < 1 || maxPages > MAX_ALLOWED_PAGES) { + throw new Error(`--max-pages must be an integer from 1 to ${MAX_ALLOWED_PAGES}.`); + } + return maxPages; +} + +export async function auditSite(startUrl: string, options: SiteAuditOptions = {}): Promise { + const maxPages = validateMaxPages(options.maxPages); + const requestedStartUrl = normalizeUrl(startUrl); + const startResource = await fetchForSite(requestedStartUrl); + const origin = new URL(startResource.finalUrl).origin; + const normalizedStartUrl = normalizeUrl(startResource.finalUrl); + + const robotsResult = await loadRobots(origin); + const sitemapResult = await loadSitemaps(origin, robotsResult.policy.sitemapUrls); + const sitemapUrls = new Set(sitemapResult.pageUrls); + const discoverySources = new Map>(); + const inlinks = new Map>(); + const allInternalTargets = new Set(); + const robotsSkipped = new Set(); + const visited = new Set(); + const linkQueue: string[] = []; + const sitemapQueue = [...sitemapUrls]; + const linkScheduled = new Set(); + const pages: CrawledPage[] = []; + + const addSource = (url: string, source: string): void => { + const sources = discoverySources.get(url) ?? new Set(); + sources.add(source); + discoverySources.set(url, sources); + }; + + addSource(normalizedStartUrl, 'start'); + for (const url of sitemapUrls) addSource(url, 'sitemap'); + + const scheduleLink = (url: string, from: string): void => { + addSource(url, `link:${from}`); + const sources = inlinks.get(url) ?? new Set(); + sources.add(from); + inlinks.set(url, sources); + allInternalTargets.add(url); + if (!visited.has(url) && !linkScheduled.has(url)) { + linkScheduled.add(url); + linkQueue.push(url); + } + }; + + const processResource = (requestedUrl: string, resource: UrlResource): void => { + visited.add(requestedUrl); + visited.add(normalizeUrl(resource.finalUrl)); + const htmlDocument = resource.status >= 200 && resource.status < 300 && isHtmlResource(resource) + ? parseHtml(resource.html, resource.finalUrl) + : null; + const internalTargets: string[] = []; + let externalLinkCount = 0; + + if (htmlDocument) { + for (const link of htmlDocument.links) { + const internal = internalUrl(link.href, resource.finalUrl, origin); + if (internal) { + internalTargets.push(internal); + scheduleLink(internal, normalizeUrl(resource.finalUrl)); + } else { + try { + const target = new URL(link.href, resource.finalUrl); + if (target.protocol === 'http:' || target.protocol === 'https:') externalLinkCount += 1; + } catch { + // Non-URL link targets are omitted from the external count. + } + } + } + } + + const combinedSources = new Set([ + ...(discoverySources.get(requestedUrl) ?? []), + ...(discoverySources.get(normalizeUrl(resource.finalUrl)) ?? []), + ]); + pages.push({ + output: { + requestedUrl, + finalUrl: resource.finalUrl, + status: resource.status, + statusText: resource.statusText, + redirects: resource.redirects.map((hop) => `${hop.status} ${hop.from} -> ${hop.to}`), + contentType: resource.contentType, + title: htmlDocument?.documentTitle || null, + language: htmlDocument?.language || null, + canonicalLinks: htmlDocument?.canonicalLinks ?? [], + internalLinkCount: internalTargets.length, + externalLinkCount, + discoveredFrom: [...combinedSources].sort(), + }, + document: htmlDocument, + internalTargets, + blocksIndexing: htmlDocument ? blocksIndexing(htmlDocument, resource.xRobotsTag) : false, + }); + }; + + if (robotsAllows(normalizedStartUrl, robotsResult.policy)) { + processResource(normalizedStartUrl, startResource); + } else { + robotsSkipped.add(normalizedStartUrl); + } + + while (pages.length < maxPages) { + let nextUrl: string | undefined; + while (linkQueue.length > 0 && !nextUrl) { + const candidate = linkQueue.shift()!; + if (!visited.has(candidate)) nextUrl = candidate; + } + while (!nextUrl && sitemapQueue.length > 0) { + const candidate = sitemapQueue.shift()!; + if (!visited.has(candidate)) nextUrl = candidate; + } + if (!nextUrl) break; + + if (!robotsAllows(nextUrl, robotsResult.policy)) { + robotsSkipped.add(nextUrl); + visited.add(nextUrl); + continue; + } + + try { + const resource = await fetchForSite(nextUrl, origin); + processResource(nextUrl, resource); + } catch (error) { + visited.add(nextUrl); + pages.push({ + output: { + requestedUrl: nextUrl, + finalUrl: nextUrl, + status: 0, + statusText: error instanceof Error ? error.message : 'Request failed', + redirects: [], + contentType: null, + title: null, + language: null, + canonicalLinks: [], + internalLinkCount: 0, + externalLinkCount: 0, + discoveredFrom: [...(discoverySources.get(nextUrl) ?? [])].sort(), + }, + document: null, + internalTargets: [], + blocksIndexing: false, + }); + } + } + + for (const page of pages) { + const sources = new Set([ + ...(discoverySources.get(page.output.requestedUrl) ?? []), + ...(discoverySources.get(normalizeUrl(page.output.finalUrl)) ?? []), + ]); + page.output.discoveredFrom = [...sources].sort(); + } + + const remainingUrls = [...linkQueue, ...sitemapQueue] + .filter((url) => !visited.has(url) && robotsAllows(url, robotsResult.policy)); + const truncated = remainingUrls.length > 0; + const pageLookup = new Map(); + for (const page of pages) { + pageLookup.set(page.output.requestedUrl, page); + pageLookup.set(normalizeUrl(page.output.finalUrl), page); + } + + const failedPages = pages.filter((page) => page.output.status === 0 || page.output.status >= 400); + const longRedirectChains = pages.filter((page) => page.output.redirects.length > 1); + const brokenInternalTargets = [...allInternalTargets].filter((url) => { + const page = pageLookup.get(url); + return page ? page.output.status === 0 || page.output.status >= 400 : false; + }); + const uncheckedInternalTargets = [...allInternalTargets].filter((url) => + !pageLookup.has(url) && !robotsSkipped.has(url), + ); + + const htmlPages = pages.filter((page) => page.document !== null); + const missingCanonicals: string[] = []; + const malformedCanonicals: string[] = []; + const nonSelfCanonicals: string[] = []; + const canonicalOwners = new Map(); + for (const page of htmlPages) { + const canonicals = page.document!.canonicalLinks ?? []; + if (canonicals.length === 0) { + missingCanonicals.push(page.output.finalUrl); + continue; + } + if (canonicals.length > 1) malformedCanonicals.push(page.output.finalUrl); + for (const value of canonicals) { + try { + const resolved = normalizeUrl(value, page.output.finalUrl); + const owners = canonicalOwners.get(resolved) ?? []; + owners.push(page.output.finalUrl); + canonicalOwners.set(resolved, owners); + if (resolved !== normalizeUrl(page.output.finalUrl)) { + nonSelfCanonicals.push(`${page.output.finalUrl} -> ${resolved}`); + } + } catch { + malformedCanonicals.push(`${page.output.finalUrl} -> ${value}`); + } + } + } + const duplicateCanonicals = [...canonicalOwners.entries()] + .filter(([, owners]) => new Set(owners).size > 1) + .map(([canonical, owners]) => `${canonical} <= ${[...new Set(owners)].join(', ')}`); + + const titleOwners = new Map(); + for (const page of htmlPages) { + const title = page.output.title?.trim(); + if (!title) continue; + const owners = titleOwners.get(title.toLocaleLowerCase()) ?? []; + owners.push(page.output.finalUrl); + titleOwners.set(title.toLocaleLowerCase(), owners); + } + const duplicateTitles = [...titleOwners.entries()] + .filter(([, owners]) => new Set(owners).size > 1) + .map(([title, owners]) => `${title} <= ${[...new Set(owners)].join(', ')}`); + + const brokenSitemapPages = [...sitemapUrls].filter((url) => { + const page = pageLookup.get(url); + return page ? page.output.status === 0 || page.output.status >= 400 : false; + }); + const failedSitemaps = sitemapResult.reports.filter((sitemap) => + sitemap.status !== 200 && sitemap.status !== 404, + ); + const indexableCrawledUrls = pages + .filter((page) => page.document && page.output.status >= 200 && page.output.status < 300 && !page.blocksIndexing) + .map((page) => normalizeUrl(page.output.finalUrl)); + const missingFromSitemap = sitemapUrls.size > 0 + ? indexableCrawledUrls.filter((url) => !sitemapUrls.has(url)) + : []; + const orphanCandidates = [...sitemapUrls].filter((url) => { + if (url === normalizedStartUrl || robotsSkipped.has(url)) return false; + const sources = [...(inlinks.get(url) ?? [])].filter((source) => source !== url); + return sources.length === 0; + }); + + const robotsStatus: AuditStatus = robotsResult.status === 200 + ? 'PASS' + : robotsResult.status === 404 + ? 'N/A' + : 'WARNING'; + const canonicalStatus: AuditStatus = htmlPages.length === 0 + ? 'N/A' + : malformedCanonicals.length > 0 + ? 'FAIL' + : missingCanonicals.length > 0 || nonSelfCanonicals.length > 0 || duplicateCanonicals.length > 0 + ? 'WARNING' + : 'PASS'; + const sitemapStatus: AuditStatus = sitemapUrls.size === 0 && failedSitemaps.length === 0 + ? 'N/A' + : failedSitemaps.length > 0 || brokenSitemapPages.length > 0 + ? 'FAIL' + : missingFromSitemap.length > 0 + ? 'WARNING' + : 'PASS'; + + const checks: AuditCheck[] = [ + check( + 'crawl-coverage', + 'Bounded crawl coverage', + pages.length === 0 ? 'FAIL' : truncated ? 'WARNING' : 'PASS', + { crawledPages: pages.length, maxPages, queuedButUnchecked: remainingUrls.slice(0, 20), truncated }, + truncated + ? 'The page limit was reached while same-origin URLs remained in the deterministic queue.' + : 'The deterministic queue completed within the configured page limit.', + truncated ? 'Increase --max-pages only after reviewing the queued URL patterns and crawl cost.' : null, + 'Repeat the audit with the same start URL and limit, then compare the queue and page count.', + ), + check( + 'robots-policy', + 'robots.txt policy', + robotsStatus, + { + url: robotsResult.url, + status: robotsResult.status, + applicableRules: robotsResult.policy.rules.map((rule) => `${rule.directive}: ${rule.pattern}`), + skippedUrls: [...robotsSkipped].slice(0, 20), + }, + robotsResult.status === 200 + ? 'Applicable aeoptimize or wildcard rules were evaluated before subsequent page requests.' + : robotsResult.status === 404 + ? 'No robots.txt file was found. Absence is not an error.' + : 'robots.txt could not be used reliably, so the crawler conservatively avoided matching subsequent URLs.', + robotsStatus === 'WARNING' ? 'Restore a readable robots.txt response and review the intended crawler policy.' : null, + 'Fetch robots.txt directly and compare the applicable user-agent group with the skipped URL sample.', + 'http', + ), + check( + 'site-http-status', + 'Page HTTP status', + failedPages.length > 0 ? 'FAIL' : pages.length > 0 ? 'PASS' : 'N/A', + { + failedCount: failedPages.length, + failedPages: failedPages.slice(0, 20).map((page) => `${page.output.status} ${page.output.requestedUrl}`), + }, + failedPages.length > 0 + ? 'One or more crawled URLs failed to return a successful final response.' + : 'Every crawled page returned a successful final response.', + failedPages.length > 0 ? 'Repair, remove, or intentionally retire failed URLs and update links or sitemap entries that reference them.' : null, + 'Request each failed URL with redirects disabled and confirm the intended final status.', + 'http', + ), + check( + 'redirect-chains', + 'Redirect chains', + pages.length === 0 ? 'N/A' : longRedirectChains.length > 0 ? 'WARNING' : 'PASS', + { + longChainCount: longRedirectChains.length, + samples: longRedirectChains.slice(0, 20).map((page) => page.output.redirects.join(' | ')), + }, + longRedirectChains.length > 0 + ? 'One or more requested URLs required multiple redirect hops.' + : 'No multi-hop redirect chain was observed among crawled pages.', + longRedirectChains.length > 0 ? 'Update internal links and redirect rules to target the final URL directly where appropriate.' : null, + 'Request each sample with redirects disabled and verify every hop plus the final destination.', + 'http', + ), + check( + 'internal-link-targets', + 'Internal link targets', + brokenInternalTargets.length > 0 + ? 'FAIL' + : uncheckedInternalTargets.length > 0 + ? 'WARNING' + : allInternalTargets.size > 0 + ? 'PASS' + : 'N/A', + { + discoveredTargetCount: allInternalTargets.size, + brokenTargets: brokenInternalTargets.slice(0, 20), + uncheckedTargets: uncheckedInternalTargets.slice(0, 20), + }, + brokenInternalTargets.length > 0 + ? 'Confirmed internal link targets returned a failed response.' + : uncheckedInternalTargets.length > 0 + ? 'Some discovered internal targets were not fetched within the current crawl boundary.' + : 'Every discovered internal target within the crawl boundary returned a successful response.', + brokenInternalTargets.length > 0 + ? 'Update links to a valid destination or restore the intended page.' + : uncheckedInternalTargets.length > 0 + ? 'Review the unchecked URL patterns before increasing the page limit.' + : null, + 'Re-run the bounded crawl and request each reported target independently.', + ), + check( + 'canonical-consistency', + 'Canonical consistency', + canonicalStatus, + { + htmlPageCount: htmlPages.length, + missingCanonicals: missingCanonicals.slice(0, 20), + malformedCanonicals: malformedCanonicals.slice(0, 20), + nonSelfCanonicals: nonSelfCanonicals.slice(0, 20), + duplicateCanonicals: duplicateCanonicals.slice(0, 20), + }, + canonicalStatus === 'PASS' + ? 'Each inspected HTML page exposes one valid self-referencing canonical.' + : canonicalStatus === 'N/A' + ? 'No successful HTML page was available for canonical inspection.' + : 'Canonical observations require repair or contextual review. A non-self canonical can be intentional.', + canonicalStatus === 'FAIL' + ? 'Emit one valid canonical URL per page.' + : canonicalStatus === 'WARNING' + ? 'Review missing, shared, and non-self canonicals against the intended URL strategy.' + : null, + 'Fetch each affected final URL and compare its rendered canonical with the intended indexable URL.', + 'html', + ), + check( + 'sitemap-consistency', + 'Sitemap consistency', + sitemapStatus, + { + sitemapCount: sitemapResult.reports.length, + sitemapUrlCount: sitemapUrls.size, + failedSitemaps: failedSitemaps.map((sitemap) => `${sitemap.status} ${sitemap.url}`).slice(0, 20), + brokenSitemapPages: brokenSitemapPages.slice(0, 20), + crawledButMissing: missingFromSitemap.slice(0, 20), + }, + sitemapStatus === 'N/A' + ? 'No readable sitemap URL set was discovered. A sitemap is optional for small sites.' + : sitemapStatus === 'PASS' + ? 'No failed sitemap page or crawled indexable URL omission was observed within this bounded sample.' + : 'Sitemap fetches, listed pages, or bounded crawl coverage contain discrepancies.', + sitemapStatus === 'FAIL' + ? 'Repair unreadable sitemap files and remove or restore failed listed URLs.' + : sitemapStatus === 'WARNING' + ? 'Review whether the omitted crawled URLs belong in the sitemap and keep canonical URL forms consistent.' + : null, + 'Fetch every reported sitemap, validate its XML, and request affected page URLs independently.', + 'http', + ), + check( + 'orphan-candidates', + 'Sitemap-only orphan candidates', + sitemapUrls.size === 0 ? 'N/A' : orphanCandidates.length > 0 ? 'WARNING' : 'PASS', + { candidateCount: orphanCandidates.length, candidates: orphanCandidates.slice(0, 20) }, + sitemapUrls.size === 0 + ? 'A sitemap/link comparison was unavailable.' + : orphanCandidates.length > 0 + ? 'These sitemap URLs received no internal inlink in the bounded crawl. They are candidates, not confirmed orphan pages.' + : 'Every sitemap URL in the bounded sample received an internal inlink or was the start URL.', + orphanCandidates.length > 0 ? 'Confirm the intended page value and add a relevant crawlable link, merge it, or remove it from the sitemap.' : null, + 'Run a larger crawl and compare sitemap, rendered navigation, and server-log discovery before confirming orphan status.', + ), + check( + 'duplicate-titles', + 'Duplicate document titles', + htmlPages.length === 0 ? 'N/A' : duplicateTitles.length > 0 ? 'WARNING' : 'PASS', + { duplicateGroupCount: duplicateTitles.length, groups: duplicateTitles.slice(0, 20) }, + duplicateTitles.length > 0 + ? 'Multiple crawled pages expose the same non-empty document title. Shared titles need intent and template review.' + : 'No duplicate non-empty document title was found in the bounded HTML sample.', + duplicateTitles.length > 0 ? 'Give pages distinct titles when they serve different content or consolidate pages that serve the same purpose.' : null, + 'Inspect the affected pages and verify their rendered titles after the template build.', + 'html', + ), + ]; + + const summary: Record = { PASS: 0, WARNING: 0, FAIL: 0, 'N/A': 0 }; + for (const item of checks) summary[item.status] += 1; + + return { + contractVersion: SITE_AUDIT_CONTRACT_VERSION, + startUrl: requestedStartUrl, + origin, + maxPages, + crawledPages: pages.length, + truncated, + robots: { + url: robotsResult.url, + status: robotsResult.status, + applicableRules: robotsResult.policy.rules.map((rule) => `${rule.directive}: ${rule.pattern}`), + sitemapUrls: robotsResult.policy.sitemapUrls, + skippedUrls: [...robotsSkipped].sort(), + }, + sitemaps: sitemapResult.reports, + pages: pages.map((page) => page.output), + checks, + summary, + limitations: [ + 'The crawl is same-origin, sequential, response-HTML only, and bounded by --max-pages. JavaScript-inserted links are not discovered.', + 'robots.txt matching supports applicable user-agent groups, Allow, Disallow, * wildcards, and $ endings. Review unusual policies manually.', + 'Sitemap-only pages are orphan candidates until a sufficiently complete crawl or server-log evidence confirms their link discovery state.', + 'The report does not claim actual search-engine crawl, index state, ranking, traffic, conversion, or AI citation outcomes.', + ], + timestamp: new Date().toISOString(), + }; +} diff --git a/src/core/types.ts b/src/core/types.ts index 0ed0e7c..a611de5 100644 --- a/src/core/types.ts +++ b/src/core/types.ts @@ -116,6 +116,50 @@ export interface AuditReport { timestamp: string; } +export interface SiteAuditPage { + requestedUrl: string; + finalUrl: string; + status: number; + statusText: string; + redirects: string[]; + contentType: string | null; + title: string | null; + language: string | null; + canonicalLinks: string[]; + internalLinkCount: number; + externalLinkCount: number; + discoveredFrom: string[]; +} + +export interface SiteAuditSitemap { + url: string; + status: number; + kind: 'urlset' | 'index' | 'unknown'; + urlCount: number; +} + +export interface SiteAuditReport { + contractVersion: '1.0'; + startUrl: string; + origin: string; + maxPages: number; + crawledPages: number; + truncated: boolean; + robots: { + url: string; + status: number; + applicableRules: string[]; + sitemapUrls: string[]; + skippedUrls: string[]; + }; + sitemaps: SiteAuditSitemap[]; + pages: SiteAuditPage[]; + checks: AuditCheck[]; + summary: Record; + limitations: string[]; + timestamp: string; +} + export interface RuleResult { score: number; maxScore: number; From e379d8097c8788d670811ac64b371fb837e8f4eb Mon Sep 17 00:00:00 2001 From: Te-Shu Wang Date: Mon, 7 Sep 2026 07:08:37 +0800 Subject: [PATCH 4/5] fix: preserve audit evidence boundaries --- src/core/__tests__/audit.test.ts | 23 ++++++++++ src/core/__tests__/scanner.test.ts | 8 ++++ src/core/__tests__/site-audit.test.ts | 45 +++++++++++++++++++ src/core/audit.ts | 64 +++++++++++++++++++-------- src/core/scanner.ts | 23 ++++++++-- src/core/site-audit.ts | 59 +++++++++++++++++------- src/core/types.ts | 2 + 7 files changed, 185 insertions(+), 39 deletions(-) diff --git a/src/core/__tests__/audit.test.ts b/src/core/__tests__/audit.test.ts index 349ceba..e97327e 100644 --- a/src/core/__tests__/audit.test.ts +++ b/src/core/__tests__/audit.test.ts @@ -87,6 +87,29 @@ describe('auditDocument', () => { expect(report.checks.find((check) => check.id === 'http-status')?.status).toBe('N/A'); }); + it('keeps unavailable canonical evidence separate and reads every robots directive', () => { + const document = parseHtml(` + Local page + + + + + +

Local page

`, 'page.html'); + const report = auditDocument(document, { + target: { type: 'file', input: 'page.html' }, + rendering: 'local-html', + }); + + expect(document.metaTagValues).toMatchObject({ + robots: ['index,follow', 'index'], + googlebot: ['NoIndex,nofollow'], + }); + expect(report.checks.find((check) => check.id === 'canonical-link')?.status).toBe('N/A'); + expect(report.checks.find((check) => check.id === 'robots-directives')?.status).toBe('WARNING'); + expect(report.checks.find((check) => check.id === 'json-ld-structure')?.status).toBe('PASS'); + }); + it('does not claim rendered metadata for Markdown source files', () => { const report = auditDocument(parseMarkdown('# Guide\n\nSee [details](/details).', 'guide.md'), { target: { type: 'file', input: 'guide.md' }, diff --git a/src/core/__tests__/scanner.test.ts b/src/core/__tests__/scanner.test.ts index d223faf..d6678ff 100644 --- a/src/core/__tests__/scanner.test.ts +++ b/src/core/__tests__/scanner.test.ts @@ -31,6 +31,14 @@ describe('parseHtml', () => { expect(doc.paragraphs).toEqual(['This is a test paragraph with enough words.']); expect(doc.jsonLd).toEqual([]); }); + + it('preserves the v0.6 score for a non-object JSON-LD value while exposing an audit error', () => { + const doc = parseHtml('', 'test.html'); + + expect(doc.jsonLd).toEqual([42]); + expect(doc.jsonLdErrors).toHaveLength(1); + expect(scanDocument(doc).scores.schema).toBe(8); + }); }); describe('parseMarkdown', () => { diff --git a/src/core/__tests__/site-audit.test.ts b/src/core/__tests__/site-audit.test.ts index 9a57cac..2702bf8 100644 --- a/src/core/__tests__/site-audit.test.ts +++ b/src/core/__tests__/site-audit.test.ts @@ -35,6 +35,18 @@ describe('robots policy', () => { expect(robotsAllows('https://example.com/private/public', policy)).toBe(true); expect(robotsAllows('https://example.com/private/public/child', policy)).toBe(false); }); + + it('prefers the exact crawler product token over its shorter prefix', () => { + const policy = parseRobotsTxt(` + User-agent: aeoptimize + Allow: /private + + User-agent: aeoptimize-site-audit + Disallow: /private + `); + + expect(robotsAllows('https://example.com/private', policy)).toBe(false); + }); }); describe('sitemap parsing', () => { @@ -203,9 +215,42 @@ describe('auditSite', () => { const report = await auditSite('https://example.com/', { maxPages: 5 }); expect(report.pages.find((page) => page.requestedUrl.endsWith('/leave'))).toMatchObject({ status: 0 }); + expect(report.checks.find((check) => check.id === 'site-http-status')?.status).toBe('WARNING'); + const linkCheck = report.checks.find((check) => check.id === 'internal-link-targets'); + expect(linkCheck?.status).toBe('WARNING'); + expect(linkCheck?.evidence[0].observed).toMatchObject({ + brokenTargets: [], + uncheckedTargets: ['https://example.com/leave'], + }); expect(fetchMock.mock.calls.some(([url]) => url.toString() === 'https://outside.example/')).toBe(false); }); + it('reports a malformed successful sitemap response as a confirmed failure', async () => { + const fetchMock = vi.fn(async (input: string | URL) => { + const url = input.toString(); + if (url === 'https://example.com/') { + return new Response('Home

Home

', { + status: 200, + headers: { 'content-type': 'text/html' }, + }); + } + if (url === 'https://example.com/robots.txt') return new Response('', { status: 404 }); + if (url === 'https://example.com/sitemap.xml') { + return new Response('Not a sitemap', { status: 200 }); + } + throw new Error(`Unexpected fetch: ${url}`); + }); + vi.stubGlobal('fetch', fetchMock); + + const report = await auditSite('https://example.com/', { maxPages: 5 }); + const sitemapCheck = report.checks.find((check) => check.id === 'sitemap-consistency'); + + expect(sitemapCheck?.status).toBe('FAIL'); + expect(sitemapCheck?.evidence[0].observed).toMatchObject({ + invalidSitemaps: ['https://example.com/sitemap.xml'], + }); + }); + it('stops subsequent page crawling when robots policy is temporarily unavailable', async () => { const fetchMock = vi.fn(async (input: string | URL) => { const url = input.toString(); diff --git a/src/core/audit.ts b/src/core/audit.ts index 832ed15..390c2b7 100644 --- a/src/core/audit.ts +++ b/src/core/audit.ts @@ -217,7 +217,9 @@ function checkLanguage(doc: ParsedDocument, context: AuditContext): AuditCheck { function resolveCanonical(value: string, baseUrl?: string): string | null { try { - return baseUrl ? new URL(value, baseUrl).toString() : new URL(value).toString(); + const url = baseUrl ? new URL(value, baseUrl) : new URL(value); + if (url.protocol !== 'http:' && url.protocol !== 'https:') return null; + return url.toString(); } catch { return null; } @@ -247,25 +249,45 @@ function checkCanonical(doc: ParsedDocument, context: AuditContext): AuditCheck } const baseUrl = context.target.finalUrl; - const resolved = canonicals.map((value) => resolveCanonical(value, baseUrl)); - if (canonicals.length > 1 || resolved.some((value) => value === null)) { + if (canonicals.length > 1) { return makeCheck( 'canonical-link', 'Canonical link', 'FAIL', [evidence(sourceFor(context), { canonicals, - resolved: resolved.map((value) => value ?? 'INVALID'), + resolved: canonicals.map((value) => resolveCanonical(value, baseUrl) ?? 'INVALID'), })], - canonicals.length > 1 - ? 'Multiple canonical links were found, so the canonical signal is ambiguous.' - : 'The canonical value could not be resolved as a URL.', + 'Multiple canonical links were found, so the canonical signal is ambiguous.', 'Emit exactly one valid canonical link that represents the intended indexable URL.', 'Fetch the built page and verify one canonical element plus its resolved destination.', ); } - const canonical = resolved[0]!; + const declared = canonicals[0]; + const canonical = resolveCanonical(declared, baseUrl); + if (!baseUrl && declared.trim() !== '' && canonical === null && !/^[a-z][a-z\d+.-]*:/i.test(declared)) { + return makeCheck( + 'canonical-link', + 'Canonical link', + 'N/A', + [evidence(sourceFor(context), { declared, resolved: null, finalUrl: null })], + 'A relative canonical was found, but a local-file audit has no deployed base URL for resolution.', + null, + 'Audit the deployed URL and verify the resolved canonical destination.', + ); + } + if (canonical === null) { + return makeCheck( + 'canonical-link', + 'Canonical link', + 'FAIL', + [evidence(sourceFor(context), { declared, resolved: 'INVALID' })], + 'The canonical value could not be resolved to an HTTP or HTTPS URL.', + 'Emit exactly one valid canonical link that represents the intended indexable URL.', + 'Fetch the built page and verify one canonical element plus its resolved destination.', + ); + } if (!baseUrl) { return makeCheck( 'canonical-link', @@ -293,7 +315,9 @@ function checkCanonical(doc: ParsedDocument, context: AuditContext): AuditCheck } function checkRobots(doc: ParsedDocument, context: AuditContext): AuditCheck { - const metaRobots = [doc.metaTags.robots, doc.metaTags.googlebot].filter(Boolean).join(', '); + const valuesFor = (name: string): string[] => doc.metaTagValues?.[name] + ?? (doc.metaTags[name] ? [doc.metaTags[name]] : []); + const metaRobots = [...valuesFor('robots'), ...valuesFor('googlebot')].join(', '); const xRobotsTag = context.http?.xRobotsTag ?? ''; const combined = `${metaRobots}, ${xRobotsTag}`; const blocksIndexing = /(?:^|[,\s])(?:noindex|none)(?:$|[,\s])/i.test(combined); @@ -386,21 +410,23 @@ function checkImages(doc: ParsedDocument, context: AuditContext): AuditCheck { function checkJsonLd(doc: ParsedDocument, context: AuditContext): AuditCheck { const errors = doc.jsonLdErrors ?? []; - const missingUniversalFields = doc.jsonLd.filter((value) => !value['@context'] || !value['@type']); + const parsedObjects = doc.jsonLd.filter((value) => + value !== null && typeof value === 'object' && !Array.isArray(value)); + const invalidValueCount = doc.jsonLd.length - parsedObjects.length; - if (errors.length > 0 || missingUniversalFields.length > 0) { + if (errors.length > 0 || invalidValueCount > 0) { return makeCheck( 'json-ld-structure', 'JSON-LD structure', 'FAIL', [evidence(sourceFor(context), { - blockCount: doc.jsonLd.length + errors.length, - parsedCount: doc.jsonLd.length, + blockCount: doc.jsonLdBlockCount ?? doc.jsonLd.length, + parsedObjectCount: parsedObjects.length, + invalidValueCount, parseErrors: errors, - missingContextOrTypeCount: missingUniversalFields.length, })], - 'Malformed JSON-LD or a missing @context/@type field was detected. Feature-specific eligibility and visible-content agreement remain outside this structural check.', - 'Correct the JSON syntax and universal fields, then validate the specific schema type against the applicable primary documentation and visible content.', + 'Malformed JSON-LD or a non-object top-level value was detected. Feature-specific eligibility and visible-content agreement remain outside this structural check.', + 'Correct the JSON syntax and top-level structure, then validate the specific schema type against the applicable primary documentation and visible content.', 'Parse every JSON-LD block again and run the relevant structured-data validator for the page type.', ); } @@ -422,10 +448,10 @@ function checkJsonLd(doc: ParsedDocument, context: AuditContext): AuditCheck { 'JSON-LD structure', 'PASS', [evidence(sourceFor(context), { - blockCount: doc.jsonLd.length, - schemaTypes: doc.jsonLd.map((value) => value['@type'] || '[unknown]'), + blockCount: doc.jsonLdBlockCount ?? doc.jsonLd.length, + schemaTypes: parsedObjects.map((value) => value['@type'] || '[unknown]'), })], - 'Every parsed JSON-LD object includes @context and @type. This does not establish feature eligibility or guarantee rich results.', + 'Every JSON-LD value parsed to an object. Context, type, feature eligibility, and visible-content agreement require schema-specific validation.', null, 'Compare each structured-data field with visible content and the current documentation for its intended feature.', ); diff --git a/src/core/scanner.ts b/src/core/scanner.ts index 6bf7a93..d8c90a6 100644 --- a/src/core/scanner.ts +++ b/src/core/scanner.ts @@ -48,13 +48,19 @@ export function parseHtml(html: string, url: string): ParsedDocument { // Extract JSON-LD const jsonLd: JsonLdObject[] = []; const jsonLdErrors: string[] = []; - $('script[type="application/ld+json"]').each((index, el) => { + const jsonLdScripts = $('script[type="application/ld+json"]'); + jsonLdScripts.each((index, el) => { try { const parsed = JSON.parse($(el).html() || ''); const candidates = Array.isArray(parsed) ? parsed : [parsed]; for (const [candidateIndex, candidate] of candidates.entries()) { - if (candidate && typeof candidate === 'object' && !Array.isArray(candidate)) { + if (candidate !== null) { + // Keep the v0.6 scoring input compatible. The audit contract records + // non-object values separately, but the score historically counted them. jsonLd.push(candidate as JsonLdObject); + } + if (candidate && typeof candidate === 'object' && !Array.isArray(candidate)) { + continue; } else { const location = Array.isArray(parsed) ? ` item ${candidateIndex + 1}` : ''; jsonLdErrors.push(`JSON-LD block ${index + 1}${location}: expected an object`); @@ -68,10 +74,18 @@ export function parseHtml(html: string, url: string): ParsedDocument { // Extract meta tags const metaTags: Record = {}; + const metaTagValues: Record = {}; $('meta').each((_, el) => { - const name = $(el).attr('name') || $(el).attr('property') || ''; + const declaredName = $(el).attr('name') || ''; + const name = declaredName || $(el).attr('property') || ''; const content = $(el).attr('content') || ''; if (name && content) metaTags[name] = content; + if (declaredName && content) { + const normalizedName = declaredName.trim().toLowerCase(); + const values = metaTagValues[normalizedName] ?? []; + values.push(content); + metaTagValues[normalizedName] = values; + } }); // Extract links @@ -106,8 +120,10 @@ export function parseHtml(html: string, url: string): ParsedDocument { headings, paragraphs, jsonLd, + jsonLdBlockCount: jsonLdScripts.length, jsonLdErrors, metaTags, + metaTagValues, links, images, language, @@ -198,6 +214,7 @@ export function parseMarkdown(md: string, url: string): ParsedDocument { paragraphs, jsonLd: [], metaTags: {}, + metaTagValues: {}, links, images, language, diff --git a/src/core/site-audit.ts b/src/core/site-audit.ts index b5c7264..1dd84b0 100644 --- a/src/core/site-audit.ts +++ b/src/core/site-audit.ts @@ -15,6 +15,7 @@ const DEFAULT_MAX_PAGES = 20; const MAX_ALLOWED_PAGES = 200; const MAX_SITEMAPS = 5; const REQUEST_TIMEOUT_MS = 15_000; +const SITE_AUDIT_USER_AGENT = 'aeoptimize-site-audit'; export interface SiteAuditOptions { maxPages?: number; @@ -83,7 +84,7 @@ export function robotsAllows(urlValue: string, policy: RobotsPolicy): boolean { return matches[0].directive === 'allow'; } -export function parseRobotsTxt(text: string, userAgent = 'aeoptimize'): RobotsPolicy { +export function parseRobotsTxt(text: string, userAgent = SITE_AUDIT_USER_AGENT): RobotsPolicy { const groups: RobotsGroup[] = []; const sitemapUrls: string[] = []; let current: RobotsGroup | null = null; @@ -188,7 +189,12 @@ function isHtmlResource(resource: UrlResource): boolean { } function blocksIndexing(document: ParsedDocument, xRobotsTag: string | null): boolean { - const directives = [document.metaTags.robots, document.metaTags.googlebot, xRobotsTag] + const metaValues = document.metaTagValues; + const directives = [ + ...(metaValues?.robots ?? (document.metaTags.robots ? [document.metaTags.robots] : [])), + ...(metaValues?.googlebot ?? (document.metaTags.googlebot ? [document.metaTags.googlebot] : [])), + xRobotsTag, + ] .filter(Boolean) .join(', '); return /(?:^|[,\s])(?:noindex|none)(?:$|[,\s])/i.test(directives); @@ -207,7 +213,7 @@ async function fetchForSite(url: string, allowedOrigin?: string): Promise= 500) { return { @@ -456,14 +462,15 @@ export async function auditSite(startUrl: string, options: SiteAuditOptions = {} pageLookup.set(normalizeUrl(page.output.finalUrl), page); } - const failedPages = pages.filter((page) => page.output.status === 0 || page.output.status >= 400); + const failedPages = pages.filter((page) => page.output.status >= 400); + const unavailablePages = pages.filter((page) => page.output.status === 0); const longRedirectChains = pages.filter((page) => page.output.redirects.length > 1); const brokenInternalTargets = [...allInternalTargets].filter((url) => { const page = pageLookup.get(url); - return page ? page.output.status === 0 || page.output.status >= 400 : false; + return page ? page.output.status >= 400 : false; }); const uncheckedInternalTargets = [...allInternalTargets].filter((url) => - !pageLookup.has(url) && !robotsSkipped.has(url), + (!pageLookup.has(url) || pageLookup.get(url)?.output.status === 0) && !robotsSkipped.has(url), ); const htmlPages = pages.filter((page) => page.document !== null); @@ -510,10 +517,17 @@ export async function auditSite(startUrl: string, options: SiteAuditOptions = {} const brokenSitemapPages = [...sitemapUrls].filter((url) => { const page = pageLookup.get(url); - return page ? page.output.status === 0 || page.output.status >= 400 : false; + return page ? page.output.status >= 400 : false; }); + const unavailableSitemapPages = [...sitemapUrls].filter((url) => + pageLookup.get(url)?.output.status === 0, + ); const failedSitemaps = sitemapResult.reports.filter((sitemap) => - sitemap.status !== 200 && sitemap.status !== 404, + sitemap.status !== 0 && sitemap.status !== 200 && sitemap.status !== 404, + ); + const unavailableSitemaps = sitemapResult.reports.filter((sitemap) => sitemap.status === 0); + const invalidSitemaps = sitemapResult.reports.filter((sitemap) => + sitemap.status === 200 && sitemap.kind === 'unknown', ); const indexableCrawledUrls = pages .filter((page) => page.document && page.output.status >= 200 && page.output.status < 300 && !page.blocksIndexing) @@ -539,13 +553,13 @@ export async function auditSite(startUrl: string, options: SiteAuditOptions = {} : missingCanonicals.length > 0 || nonSelfCanonicals.length > 0 || duplicateCanonicals.length > 0 ? 'WARNING' : 'PASS'; - const sitemapStatus: AuditStatus = sitemapUrls.size === 0 && failedSitemaps.length === 0 - ? 'N/A' - : failedSitemaps.length > 0 || brokenSitemapPages.length > 0 + const sitemapStatus: AuditStatus = failedSitemaps.length > 0 || invalidSitemaps.length > 0 || brokenSitemapPages.length > 0 ? 'FAIL' - : missingFromSitemap.length > 0 + : unavailableSitemaps.length > 0 || unavailableSitemapPages.length > 0 || missingFromSitemap.length > 0 ? 'WARNING' - : 'PASS'; + : sitemapUrls.size === 0 + ? 'N/A' + : 'PASS'; const checks: AuditCheck[] = [ check( @@ -581,15 +595,23 @@ export async function auditSite(startUrl: string, options: SiteAuditOptions = {} check( 'site-http-status', 'Page HTTP status', - failedPages.length > 0 ? 'FAIL' : pages.length > 0 ? 'PASS' : 'N/A', + failedPages.length > 0 ? 'FAIL' : unavailablePages.length > 0 ? 'WARNING' : pages.length > 0 ? 'PASS' : 'N/A', { failedCount: failedPages.length, failedPages: failedPages.slice(0, 20).map((page) => `${page.output.status} ${page.output.requestedUrl}`), + unavailableCount: unavailablePages.length, + unavailablePages: unavailablePages.slice(0, 20).map((page) => page.output.requestedUrl), }, failedPages.length > 0 ? 'One or more crawled URLs failed to return a successful final response.' + : unavailablePages.length > 0 + ? 'One or more page requests did not yield an HTTP response, so their status is unavailable.' : 'Every crawled page returned a successful final response.', - failedPages.length > 0 ? 'Repair, remove, or intentionally retire failed URLs and update links or sitemap entries that reference them.' : null, + failedPages.length > 0 + ? 'Repair, remove, or intentionally retire failed URLs and update links or sitemap entries that reference them.' + : unavailablePages.length > 0 + ? 'Retry unavailable URLs and diagnose request or redirect-policy failures before classifying them.' + : null, 'Request each failed URL with redirects disabled and confirm the intended final status.', 'http', ), @@ -667,7 +689,10 @@ export async function auditSite(startUrl: string, options: SiteAuditOptions = {} sitemapCount: sitemapResult.reports.length, sitemapUrlCount: sitemapUrls.size, failedSitemaps: failedSitemaps.map((sitemap) => `${sitemap.status} ${sitemap.url}`).slice(0, 20), + invalidSitemaps: invalidSitemaps.map((sitemap) => sitemap.url).slice(0, 20), + unavailableSitemaps: unavailableSitemaps.map((sitemap) => sitemap.url).slice(0, 20), brokenSitemapPages: brokenSitemapPages.slice(0, 20), + unavailableSitemapPages: unavailableSitemapPages.slice(0, 20), crawledButMissing: missingFromSitemap.slice(0, 20), }, sitemapStatus === 'N/A' @@ -678,7 +703,7 @@ export async function auditSite(startUrl: string, options: SiteAuditOptions = {} sitemapStatus === 'FAIL' ? 'Repair unreadable sitemap files and remove or restore failed listed URLs.' : sitemapStatus === 'WARNING' - ? 'Review whether the omitted crawled URLs belong in the sitemap and keep canonical URL forms consistent.' + ? 'Retry unavailable URLs, review omissions, and keep canonical URL forms consistent.' : null, 'Fetch every reported sitemap, validate its XML, and request affected page URLs independently.', 'http', diff --git a/src/core/types.ts b/src/core/types.ts index a611de5..06c0400 100644 --- a/src/core/types.ts +++ b/src/core/types.ts @@ -72,8 +72,10 @@ export interface ParsedDocument { headings: Heading[]; paragraphs: string[]; jsonLd: JsonLdObject[]; + jsonLdBlockCount?: number; jsonLdErrors?: string[]; metaTags: Record; + metaTagValues?: Record; links: Link[]; images?: ImageReference[]; language?: string; From b91f9162841a1546e75844fc17a5566908c524ce Mon Sep 17 00:00:00 2001 From: Te-Shu Wang Date: Mon, 7 Sep 2026 07:38:15 +0800 Subject: [PATCH 5/5] chore: prepare v0.7.0 audit release --- .claude-plugin/marketplace.json | 2 +- .claude-plugin/plugin.json | 2 +- .github/workflows/ci.yml | 12 +++--- CHANGELOG.md | 2 +- README.md | 8 ++-- action.yml | 2 +- action/action.yml | 2 +- docs/release-v0.7.md | 42 +++++++++++++++++++ .../.github/workflows/aeoptimize.yml | 2 +- examples/github-action-sample/README.md | 2 +- package-lock.json | 4 +- package.json | 3 +- scripts/verify-release-candidate.sh | 17 ++++++++ src/cli/index.ts | 2 +- .../__tests__/evidence-boundaries.test.ts | 2 +- src/core/__tests__/release-contract.test.ts | 8 ++-- src/core/__tests__/release-verifier.test.ts | 22 +++++----- 17 files changed, 97 insertions(+), 37 deletions(-) create mode 100644 docs/release-v0.7.md diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index e0fbfe1..6e675d7 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -5,7 +5,7 @@ }, "metadata": { "description": "Content-readiness lint with evidence-bounded AI discovery experiments", - "version": "0.6.2" + "version": "0.7.0" }, "plugins": [ { diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 2a2d65d..c52aa6f 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "aeoptimize", "description": "Content-readiness lint and evidence-bounded discovery experiments", - "version": "0.6.2", + "version": "0.7.0", "author": { "name": "Te-Shu Wang" }, diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 68d633c..62bcae8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -84,7 +84,7 @@ jobs: with: path: .github/fixtures/action-low min-score: '100' - package-spec: ./aeoptimize-0.6.2.tgz + package-spec: ./aeoptimize-0.7.0.tgz - name: Validate Action outputs env: @@ -101,7 +101,7 @@ jobs: uses: ./ with: path: examples/github-action-sample/site - package-spec: ./aeoptimize-0.6.2.tgz + package-spec: ./aeoptimize-0.7.0.tgz - name: Validate sample outputs env: @@ -120,7 +120,7 @@ jobs: path: .github/fixtures/action-low min-score: '0' fail-on-low-score: 'true' - package-spec: ./aeoptimize-0.6.2.tgz + package-spec: ./aeoptimize-0.7.0.tgz - name: Validate blocking outputs env: @@ -140,7 +140,7 @@ jobs: path: .github/fixtures/action-low min-score: '100' fail-on-low-score: 'true' - package-spec: ./aeoptimize-0.6.2.tgz + package-spec: ./aeoptimize-0.7.0.tgz - name: Invalid choice is rejected id: invalid-choice @@ -149,7 +149,7 @@ jobs: with: path: .github/fixtures/action-low fail-on-low-score: sometimes - package-spec: ./aeoptimize-0.6.2.tgz + package-spec: ./aeoptimize-0.7.0.tgz - name: Out-of-range threshold is rejected id: invalid-threshold @@ -158,7 +158,7 @@ jobs: with: path: .github/fixtures/action-low min-score: '101' - package-spec: ./aeoptimize-0.6.2.tgz + package-spec: ./aeoptimize-0.7.0.tgz - name: Assert expected failures env: diff --git a/CHANGELOG.md b/CHANGELOG.md index abdb1ec..a676f0a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ All notable user-visible changes will be documented here. The project follows Semantic Versioning after the v0.6 evidence baseline is released. -## Unreleased +## 0.7.0 ### Added diff --git a/README.md b/README.md index f080d81..951b47c 100644 --- a/README.md +++ b/README.md @@ -113,10 +113,10 @@ npx aeoptimize scan ./dist --dir --json > aeoptimize-report.json node -e "const r=require('./aeoptimize-report.json'); process.exit(r.overall.total < 60 ? 1 : 0)" ``` -The v0.6 GitHub Action is advisory by default. Consume it from the repository pin until it appears on GitHub Marketplace (Marketplace listing is a checkbox on a GitHub Release, not an extra package). It reports findings without blocking the workflow: +The GitHub Action is advisory by default. Consume it from the repository pin until it appears on GitHub Marketplace (Marketplace listing is a checkbox on a GitHub Release, not an extra package). It reports findings without blocking the workflow: ```yaml -- uses: cucuwang/aeoptimize@v0.6.2 +- uses: cucuwang/aeoptimize@v0.7.0 with: path: dist ``` @@ -124,7 +124,7 @@ The v0.6 GitHub Action is advisory by default. Consume it from the repository pi Projects can explicitly choose blocking mode after accepting a baseline: ```yaml -- uses: cucuwang/aeoptimize@v0.6.2 +- uses: cucuwang/aeoptimize@v0.7.0 with: path: dist fail-on-low-score: 'true' @@ -246,7 +246,7 @@ npx skills add cucuwang/aeoptimize ## Project status -The v0.6 evidence baseline focuses on methodology, reproducible fixtures, CI compatibility, packaging, and external adoption—not more scoring rules. Release acceptance and rollback are documented in [docs/release-v0.6.md](docs/release-v0.6.md); longer-term adoption work remains in [ROADMAP.md](ROADMAP.md). +Version 0.7 adds page, build, and bounded site audits while retaining the v0.6 scoring contract. Release acceptance and rollback are documented in [docs/release-v0.7.md](docs/release-v0.7.md); longer-term adoption work remains in [ROADMAP.md](ROADMAP.md). Contributions are welcome. Rule changes require an evidence note and positive/negative fixtures; see [CONTRIBUTING.md](CONTRIBUTING.md). Report vulnerabilities through the process in [SECURITY.md](SECURITY.md). diff --git a/action.yml b/action.yml index b74cc2a..3212b7c 100644 --- a/action.yml +++ b/action.yml @@ -21,7 +21,7 @@ inputs: package-spec: description: npm package spec to install; keep the default outside prerelease testing required: false - default: 'aeoptimize@0.6.2' + default: 'aeoptimize@0.7.0' outputs: score: diff --git a/action/action.yml b/action/action.yml index 2841bd9..01d9260 100644 --- a/action/action.yml +++ b/action/action.yml @@ -20,7 +20,7 @@ inputs: package-spec: description: npm package spec to install; keep the default outside prerelease testing required: false - default: 'aeoptimize@0.6.2' + default: 'aeoptimize@0.7.0' outputs: score: diff --git a/docs/release-v0.7.md b/docs/release-v0.7.md new file mode 100644 index 0000000..99cf04a --- /dev/null +++ b/docs/release-v0.7.md @@ -0,0 +1,42 @@ +# v0.7 release and rollback guide + +Version 0.7.0 adds three evidence-backed audit workflows while retaining the v0.6.0 scoring methodology and existing `scan --json` contract. + +- `audit` inspects one URL or a local HTML/Markdown file. +- `audit-build` checks built HTML with cross-page review and optional CI failure gates. +- `audit-site` performs a bounded, same-origin crawl and compares discovered links, canonical declarations and sitemap entries. + +Audit statuses describe the evidence collected. Unavailable evidence remains unassessed. Actual search indexing, rankings, traffic and AI citation outcomes are outside these contracts. + +## Release acceptance + +1. Build from a clean release commit after `npm ci` and run `npm run release:check`. +2. Require passing Node.js 22 and 24 CI, package reproducibility, and Action contract checks on the exact merged `main` commit. +3. Preserve the candidate manifest and SHA-256. Confirm all three CLI aliases and audit commands work from that exact packed artifact in a clean consumer. +4. Verify the npm account immediately before publication, fetch `origin/main`, and require the publish source gate to confirm the exact commit. +5. Publish npm 0.7.0, then create the immutable `v0.7.0` tag and GitHub Release at that same commit. These external steps require maintainer authorization. + +`prepublishOnly` runs the candidate and source gates. The source gate requires `HEAD` to equal the freshly fetched `origin/main` commit. Do not bypass it or publish a pre-merge feature commit. + +## Publication readback + +Verify npm metadata and the exact version, download its tarball, compare its SHA-256 with the candidate, and install all CLI aliases from those verified bytes. Confirm the immutable tag and published GitHub Release independently. + +```bash +npm view aeoptimize version dist-tags --json +npm view aeoptimize@0.7.0 version gitHead dist --json +bash scripts/verify-release-v0.6.sh +``` + +The public verifier keeps its historical filename and reads the expected version from package.json. When npm supplies `gitHead`, it must match the release commit. The tarball hash is required even when that optional metadata field is absent. + +## Rollback + +With explicit rollback authorization, restore `latest` to the last fully published release and deprecate the problematic version. + +```bash +npm dist-tag add aeoptimize@0.6.2 latest +npm deprecate aeoptimize@0.7.0 "Use 0.6.2 while an audit regression is corrected." +``` + +Update the GitHub Release with the same warning. Preserve existing tags and exact-version artifacts, then fix forward with a new version and repeat the release gates. diff --git a/examples/github-action-sample/.github/workflows/aeoptimize.yml b/examples/github-action-sample/.github/workflows/aeoptimize.yml index 3a4005c..464f4a7 100644 --- a/examples/github-action-sample/.github/workflows/aeoptimize.yml +++ b/examples/github-action-sample/.github/workflows/aeoptimize.yml @@ -12,7 +12,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - uses: cucuwang/aeoptimize@v0.6.2 + - uses: cucuwang/aeoptimize@v0.7.0 with: path: site fail-on-low-score: 'false' diff --git a/examples/github-action-sample/README.md b/examples/github-action-sample/README.md index 3d1c1e7..c7b86f2 100644 --- a/examples/github-action-sample/README.md +++ b/examples/github-action-sample/README.md @@ -6,4 +6,4 @@ This directory is a copyable end-to-end sample for the v0.6 Action contract. - `site/index.html` is a deterministic public input. - The Action is advisory by default. The sample does not block a pull request on an unreviewed score threshold. -The workflow becomes reproducible only after both `aeoptimize@0.6.2` exists on npm and the immutable `v0.6.2` Git tag points to the matching release commit. Until both artifacts exist, use the local CLI or the release-candidate package during controlled verification. +The workflow becomes reproducible only after both `aeoptimize@0.7.0` exists on npm and the immutable `v0.7.0` Git tag points to the matching release commit. Until both artifacts exist, use the local CLI or the release-candidate package during controlled verification. diff --git a/package-lock.json b/package-lock.json index 3580b00..ca1999e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "aeoptimize", - "version": "0.6.2", + "version": "0.7.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "aeoptimize", - "version": "0.6.2", + "version": "0.7.0", "license": "MIT", "dependencies": { "chalk": "^5.3.0", diff --git a/package.json b/package.json index 6200c46..e140fb8 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "aeoptimize", - "version": "0.6.2", + "version": "0.7.0", "description": "Deterministic content-readiness lint for static websites and documentation", "type": "module", "main": "./dist/core/index.js", @@ -26,6 +26,7 @@ ".claude-plugin/", "docs/methodology.md", "docs/release-v0.6.md", + "docs/release-v0.7.md", "CHANGELOG.md", "CONTRIBUTING.md", "ROADMAP.md", diff --git a/scripts/verify-release-candidate.sh b/scripts/verify-release-candidate.sh index c673c8a..37564f8 100755 --- a/scripts/verify-release-candidate.sh +++ b/scripts/verify-release-candidate.sh @@ -52,6 +52,10 @@ PACKAGE_SHA256=$(node -e "const crypto=require('node:crypto');const fs=require(' jq -e ' (.[0].files | map(.path) | index("dist/cli/index.js")) != null and + (.[0].files | map(.path) | index("dist/core/audit.js")) != null and + (.[0].files | map(.path) | index("dist/core/static-audit.js")) != null and + (.[0].files | map(.path) | index("dist/core/site-audit.js")) != null and + (.[0].files | map(.path) | index("docs/release-v0.7.md")) != null and (.[0].files | map(.path) | index("fixtures/v0.6/rule-corpus.ts")) != null and (.[0].files | map(.path) | index("examples/github-action-sample/.github/workflows/aeoptimize.yml")) != null and (.[0].files | map(.path) | index("scripts/verify-release-candidate.sh")) != null and @@ -70,6 +74,19 @@ for binary in aeoptimize aeo aeo-cli; do fi done +for audit_command in audit audit-build audit-site; do + "$CONSUMER_ROOT/node_modules/.bin/aeoptimize" "$audit_command" --help >/dev/null +done + +"$CONSUMER_ROOT/node_modules/.bin/aeoptimize" audit \ + "$CONSUMER_ROOT/node_modules/aeoptimize/examples/github-action-sample/site/index.html" \ + --json > "$VERIFY_ROOT/page-audit.json" +"$CONSUMER_ROOT/node_modules/.bin/aeoptimize" audit-build \ + "$CONSUMER_ROOT/node_modules/aeoptimize/examples/github-action-sample/site" \ + --json > "$VERIFY_ROOT/build-audit.json" +jq -e '.contractVersion == "1.0" and (.checks | length > 0)' "$VERIFY_ROOT/page-audit.json" >/dev/null +jq -e '.contractVersion == "1.0" and .source == "local-html" and (.pages | length == 1)' "$VERIFY_ROOT/build-audit.json" >/dev/null + MANIFEST=$(jq -n \ --arg version "$PACKAGE_VERSION" \ --arg filename "$PACKAGE_FILENAME" \ diff --git a/src/cli/index.ts b/src/cli/index.ts index a1be550..8ac5b54 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -21,7 +21,7 @@ const program = new Command(); program .name('aeoptimize') .description('Deterministic content-readiness lint for websites and documentation') - .version('0.6.2'); + .version('0.7.0'); // ── scan command ─────────────────────────────────────────────────── diff --git a/src/core/__tests__/evidence-boundaries.test.ts b/src/core/__tests__/evidence-boundaries.test.ts index 08184a9..ce5783e 100644 --- a/src/core/__tests__/evidence-boundaries.test.ts +++ b/src/core/__tests__/evidence-boundaries.test.ts @@ -83,7 +83,7 @@ describe('public metadata', () => { const action = await readFile(join(root, 'action.yml'), 'utf8'); const compatibilityAction = await readFile(join(root, 'action/action.yml'), 'utf8'); - expect(packageJson.version).toBe('0.6.2'); + expect(packageJson.version).toBe('0.7.0'); expect(pluginJson.version).toBe(packageJson.version); expect(marketplaceJson.metadata.version).toBe(packageJson.version); expect(cli).toContain(`.version('${packageJson.version}')`); diff --git a/src/core/__tests__/release-contract.test.ts b/src/core/__tests__/release-contract.test.ts index 3a0b903..96c8071 100644 --- a/src/core/__tests__/release-contract.test.ts +++ b/src/core/__tests__/release-contract.test.ts @@ -130,7 +130,7 @@ describe('v0.6 public rule fixture corpus', () => { 'utf8', ); - expect(packageJson.version.split('.').slice(0, 2)).toEqual(ruleFixtureCorpusVersion.split('.').slice(0, 2)); + expect(ruleFixtureCorpusVersion).toBe('0.6.0'); expect(methodology).toContain(`v${ruleFixtureCorpusVersion} scoring contract`); expect(sampleWorkflow).toContain(`uses: cucuwang/aeoptimize@v${packageJson.version}`); expect(sampleWorkflow).toContain('permissions:\n contents: read'); @@ -178,10 +178,10 @@ describe('v0.6 JSON automation contract', () => { it('ships release and rollback instructions with the package', async () => { const packageJson = JSON.parse(await readFile(join(repositoryRoot, 'package.json'), 'utf8')); - const releaseGuide = await readFile(join(repositoryRoot, 'docs/release-v0.6.md'), 'utf8'); + const releaseGuide = await readFile(join(repositoryRoot, 'docs/release-v0.7.md'), 'utf8'); const publicVerifier = await readFile(join(repositoryRoot, 'scripts/verify-release-v0.6.sh'), 'utf8'); - expect(packageJson.files).toContain('docs/release-v0.6.md'); + expect(packageJson.files).toContain('docs/release-v0.7.md'); expect(packageJson.files).toContain('fixtures/'); expect(packageJson.files).toContain('examples/github-action-sample/'); expect(packageJson.files).toContain('scripts/verify-release-candidate.sh'); @@ -192,7 +192,7 @@ describe('v0.6 JSON automation contract', () => { 'npm run release:check && bash scripts/verify-publish-source.sh', ); expect(releaseGuide).toContain('## Rollback'); - expect(releaseGuide).toContain('npm dist-tag add aeoptimize@0.6.0 latest'); + expect(releaseGuide).toContain('npm dist-tag add aeoptimize@0.6.2 latest'); expect(releaseGuide).toContain(''); expect(publicVerifier).toContain('.gitHead'); expect(publicVerifier).toContain('EXPECTED_REPOSITORY_URL'); diff --git a/src/core/__tests__/release-verifier.test.ts b/src/core/__tests__/release-verifier.test.ts index 3d67102..6b2e30f 100644 --- a/src/core/__tests__/release-verifier.test.ts +++ b/src/core/__tests__/release-verifier.test.ts @@ -10,7 +10,7 @@ const testDirectory = dirname(fileURLToPath(import.meta.url)); const repositoryRoot = join(testDirectory, '../../..'); const verifier = join(repositoryRoot, 'scripts/verify-release-v0.6.sh'); const expectedCommit = '0123456789abcdef0123456789abcdef01234567'; -const tarballContent = 'verified aeoptimize v0.6.2 candidate'; +const tarballContent = 'verified aeoptimize v0.7.0 candidate'; const expectedTarballHash = createHash('sha256').update(tarballContent).digest('hex'); interface CommandResult { @@ -29,7 +29,7 @@ function runVerifier( env: { ...process.env, PATH: `${mockBin}:${process.env.PATH}`, - MOCK_LATEST: '0.6.2', + MOCK_LATEST: '0.7.0', MOCK_NPM_GIT_HEAD: expectedCommit, MOCK_REPOSITORY_URL: 'git+https://github.com/cucuwang/aeoptimize.git', MOCK_TAG_COMMIT: expectedCommit, @@ -80,13 +80,13 @@ done case "$url" in https://registry.npmjs.org/aeoptimize) - printf '{"dist-tags":{"latest":"%s"},"versions":{"0.6.2":{"gitHead":"%s","repository":{"url":"%s"},"homepage":"https://github.com/cucuwang/aeoptimize","bugs":{"url":"https://github.com/cucuwang/aeoptimize/issues"},"dist":{"tarball":"https://registry.npmjs.org/aeoptimize/-/aeoptimize-0.6.2.tgz"}}}}' "$MOCK_LATEST" "$MOCK_NPM_GIT_HEAD" "$MOCK_REPOSITORY_URL" + printf '{"dist-tags":{"latest":"%s"},"versions":{"0.7.0":{"gitHead":"%s","repository":{"url":"%s"},"homepage":"https://github.com/cucuwang/aeoptimize","bugs":{"url":"https://github.com/cucuwang/aeoptimize/issues"},"dist":{"tarball":"https://registry.npmjs.org/aeoptimize/-/aeoptimize-0.7.0.tgz"}}}}' "$MOCK_LATEST" "$MOCK_NPM_GIT_HEAD" "$MOCK_REPOSITORY_URL" ;; - https://registry.npmjs.org/aeoptimize/-/aeoptimize-0.6.2.tgz) + https://registry.npmjs.org/aeoptimize/-/aeoptimize-0.7.0.tgz) printf '%s' "$MOCK_TARBALL_CONTENT" > "$output_file" ;; - https://api.github.com/repos/cucuwang/aeoptimize/releases/tags/v0.6.2) - printf '{"tag_name":"v0.6.2","draft":%s,"prerelease":%s}' "$MOCK_RELEASE_DRAFT" "$MOCK_RELEASE_PRERELEASE" > "$output_file" + https://api.github.com/repos/cucuwang/aeoptimize/releases/tags/v0.7.0) + printf '{"tag_name":"v0.7.0","draft":%s,"prerelease":%s}' "$MOCK_RELEASE_DRAFT" "$MOCK_RELEASE_PRERELEASE" > "$output_file" printf '200' ;; *) @@ -98,7 +98,7 @@ esac await writeExecutable(join(mockBin, 'git'), `#!/usr/bin/env bash set -euo pipefail -printf '%s\trefs/tags/v0.6.2\n' "$MOCK_TAG_COMMIT" +printf '%s\trefs/tags/v0.7.0\n' "$MOCK_TAG_COMMIT" `); await writeExecutable(join(mockBin, 'npm'), `#!/usr/bin/env bash @@ -116,7 +116,7 @@ for binary in aeoptimize aeo aeo-cli; do if [ "$binary" = "$MOCK_MISSING_BINARY" ]; then continue fi - printf '#!/usr/bin/env bash\nprintf "0.6.2\\n"\n' > "$prefix/node_modules/.bin/$binary" + printf '#!/usr/bin/env bash\nprintf "0.7.0\\n"\n' > "$prefix/node_modules/.bin/$binary" chmod +x "$prefix/node_modules/.bin/$binary" done `); @@ -135,8 +135,8 @@ done expect(result.stdout).toContain('PASS: npm gitHead matches'); expect(result.stdout).toContain('PASS: npm tarball SHA-256 matches the verified candidate'); expect(result.stdout).toContain('All public release checks passed.'); - expect(npmArgs).toMatch(/aeoptimize-0\.6\.2\.tgz/); - expect(npmArgs).not.toContain('aeoptimize@0.6.2'); + expect(npmArgs).toMatch(/aeoptimize-0\.7\.0\.tgz/); + expect(npmArgs).not.toContain('aeoptimize@0.7.0'); }); it('fails closed when npm serves a different tarball', async () => { @@ -177,7 +177,7 @@ done }); expect(result.code).toBe(1); - expect(result.stderr).toContain('FAIL: v0.6.2 points to'); + expect(result.stderr).toContain('FAIL: v0.7.0 points to'); }); it('fails closed when the GitHub Release is a draft', async () => {