Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

feat: render audit and comparison reports as markdown and html

Luigi Agosti8ac8850dd8dd
diff --git a/cmd/pinchtab/cmd_cli_register.go b/cmd/pinchtab/cmd_cli_register.go
index b69ab48b..c25d1f47 100644
--- a/cmd/pinchtab/cmd_cli_register.go
+++ b/cmd/pinchtab/cmd_cli_register.go
@@ -364,6 +364,7 @@ func configureBrowserFlags() {
auditCmd.Flags().Bool("json", false, "Print the full report JSON to stdout")
auditCmd.Flags().String("seaportal-report", "", "Audit pages from a SeaPortal results JSON file (array of Result objects)")
auditCmd.Flags().Bool("enrich-all", false, "Browser-enrich every seaportal page, ignoring browserRecommended routing")
+ auditCmd.Flags().String("format", "json", "Report format: json, md, or html (md/html written next to report.json, or printed without --output-dir)")
compareCmd.Flags().String("pages", "", "Comma-separated relative paths to compare (default: the base URLs)")
compareCmd.Flags().Bool("visual-diff", true, "Capture screenshots and compute visual diffs")
@@ -371,6 +372,7 @@ func configureBrowserFlags() {
compareCmd.Flags().Int("concurrency", 0, "Pages audited in parallel per side (default 2, max 8)")
compareCmd.Flags().Bool("json", false, "Print the comparison report JSON to stdout")
compareCmd.Flags().Bool("fail-on-diff", false, "Exit non-zero when any visual or data diff exists")
+ compareCmd.Flags().String("format", "json", "Report format: json, md, or html")
addTabFlag(consoleCmd, errorsCmd)
}
diff --git a/internal/audit/report/html.go b/internal/audit/report/html.go
new file mode 100644
index 00000000..4b1bb623
--- /dev/null
+++ b/internal/audit/report/html.go
@@ -0,0 +1,178 @@
+package report
+
+import (
+ "bytes"
+ "fmt"
+ "html/template"
+
+ "github.com/pinchtab/pinchtab/internal/audit"
+)
+
+// reportCSS keeps the HTML output self-contained: no external stylesheets,
+// fonts, or scripts.
+const reportCSS = `
+body { font-family: -apple-system, "Segoe UI", Roboto, sans-serif; margin: 2rem auto; max-width: 60rem; padding: 0 1rem; color: #1a1a2e; }
+h1 { border-bottom: 2px solid #0a6cff; padding-bottom: .3rem; }
+h2 { margin-top: 2rem; border-bottom: 1px solid #d0d4dd; padding-bottom: .2rem; }
+table { border-collapse: collapse; width: 100%; margin: .5rem 0 1rem; }
+th, td { border: 1px solid #d0d4dd; padding: .35rem .6rem; text-align: left; font-size: .92rem; }
+th { background: #f2f4f8; }
+.score { font-size: 1.3rem; font-weight: 700; }
+.error { color: #c0182b; }
+img.screenshot { max-width: 100%; border: 1px solid #d0d4dd; margin: .3rem 0 1rem; }
+code { background: #f2f4f8; padding: .1rem .3rem; border-radius: 3px; }
+`
+
+var htmlTemplate = template.Must(template.New("report").Funcs(template.FuncMap{
+ "pageLabel": pageLabel,
+ "consoleProblems": consoleProblems,
+ "formatMs": formatMs,
+ "formatCLS": formatCLS,
+ "sortedKeys": sortedKeys,
+ "pageErrors": pageConsoleErrors,
+}).Parse(`<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<title>Site Audit Report</title>
+<style>{{.CSS}}</style>
+</head>
+<body>
+<h1>Site Audit Report</h1>
+<p>Schema version {{.R.SchemaVersion}} · generated {{.R.GeneratedAt.Format "2006-01-02 15:04:05 UTC"}} · {{len .R.Pages}} page(s)</p>
+
+<h2>Summary</h2>
+<p class="score">Summary score: {{.R.SummaryScore}}/100</p>
+<table>
+<tr><th>Page</th><th>Score</th><th>Load</th><th>Broken assets</th><th>Console errors</th><th>Status</th></tr>
+{{range .R.Pages}}<tr><td>{{pageLabel .}}</td><td>{{.Browser.AccessibilityScore}}</td><td>{{formatMs .Browser.TimingMetrics.Load}}</td><td>{{len .Browser.BrokenAssets}}</td><td>{{pageErrors .}}</td><td>{{if .Error}}<span class="error">{{.Error}}</span>{{else}}ok{{end}}</td></tr>
+{{end}}</table>
+
+{{if .HasSeaportal}}<h2>SEO &amp; Metadata</h2>
+{{range .R.Pages}}{{if .Seaportal}}<h3>{{pageLabel .}}</h3><table>
+{{$p := .}}{{range sortedKeys .Seaportal}}<tr><th>{{.}}</th><td>{{index $p.Seaportal .}}</td></tr>
+{{end}}</table>{{end}}{{end}}{{end}}
+
+{{if .HasElements}}<h2>Content &amp; Functionality</h2>
+<table><tr><th>Page</th><th>Title</th><th>Interactive elements</th></tr>
+{{range .R.Pages}}<tr><td>{{.URL}}</td><td>{{.Title}}</td><td>{{len .Browser.InteractiveElements}}</td></tr>
+{{end}}</table>{{end}}
+
+{{if .HasVisualDiff}}<h2>Visual Differences</h2>
+<table><tr><th>Page</th><th>Changed</th><th>Diff pixels</th><th>Diff ratio</th><th>Diff image</th></tr>
+{{range .R.Pages}}{{if .Browser.VisualDiff}}<tr><td>{{pageLabel .}}</td><td>{{.Browser.VisualDiff.Changed}}</td><td>{{.Browser.VisualDiff.DiffPixels}}</td><td>{{printf "%.4f" .Browser.VisualDiff.DiffRatio}}</td><td>{{.Browser.VisualDiff.DiffPath}}</td></tr>{{end}}
+{{end}}</table>{{end}}
+
+{{if .HasTiming}}<h2>Performance</h2>
+<table><tr><th>Page</th><th>TTFB</th><th>FCP</th><th>LCP</th><th>CLS</th><th>Load</th></tr>
+{{range .R.Pages}}<tr><td>{{pageLabel .}}</td><td>{{formatMs .Browser.TimingMetrics.TimeToFirstByte}}</td><td>{{formatMs .Browser.TimingMetrics.FirstContentfulPaint}}</td><td>{{formatMs .Browser.TimingMetrics.LargestContentfulPaint}}</td><td>{{formatCLS .Browser.TimingMetrics.CumulativeLayoutShift}}</td><td>{{formatMs .Browser.TimingMetrics.Load}}</td></tr>
+{{end}}</table>{{end}}
+
+{{if .HasConsole}}<h2>Console &amp; JS Errors</h2>
+{{range .R.Pages}}{{$problems := consoleProblems .}}{{if $problems}}<h3>{{pageLabel .}}</h3><ul>
+{{range $problems}}<li><code>{{.Level}}</code> {{.Message}}</li>
+{{end}}</ul>{{end}}{{end}}{{end}}
+
+{{if .HasBroken}}<h2>Broken Assets</h2>
+<table><tr><th>Page</th><th>Asset</th><th>Type</th><th>Status</th></tr>
+{{range .R.Pages}}{{$p := .}}{{range .Browser.BrokenAssets}}<tr><td>{{pageLabel $p}}</td><td>{{.URL}}</td><td>{{.ResourceType}}</td><td>{{if .Status}}{{.Status}}{{else}}{{.Error}}{{end}}</td></tr>
+{{end}}{{end}}</table>{{end}}
+
+{{if .Usability}}<h2>Usability Issues</h2><ul>
+{{range .Usability}}<li>{{pageLabel .}}: accessibility score {{.Browser.AccessibilityScore}}/100</li>
+{{end}}</ul>{{end}}
+
+{{if .R.SecurityFindings}}<h2>Security Findings</h2><ul>
+{{range .R.SecurityFindings}}<li><strong>{{.RuleID}}</strong> [{{.Severity}}]: {{.Detail}}{{if .URL}} ({{.URL}}){{end}}</li>
+{{end}}</ul>{{end}}
+
+{{if .Recommendations}}<h2>Recommendations</h2><ol>
+{{range .Recommendations}}<li>{{.}}</li>
+{{end}}</ol>{{end}}
+
+{{if .Screenshots}}<h2>Screenshots</h2>
+{{range .R.Pages}}{{if .Browser.ScreenshotPath}}<h3>{{pageLabel .}}</h3><img class="screenshot" src="{{.Browser.ScreenshotPath}}" alt="Screenshot of {{pageLabel .}}">{{end}}{{end}}{{end}}
+</body>
+</html>
+`))
+
+type htmlContext struct {
+ R audit.AuditReport
+ CSS template.CSS
+ HasSeaportal bool
+ HasElements bool
+ HasVisualDiff bool
+ HasTiming bool
+ HasConsole bool
+ HasBroken bool
+ Usability []audit.PageResult
+ Recommendations []string
+ Screenshots bool
+}
+
+func renderHTML(r audit.AuditReport) ([]byte, error) {
+ screenshots := false
+ for _, p := range r.Pages {
+ if p.Browser.ScreenshotPath != "" {
+ screenshots = true
+ break
+ }
+ }
+ var buf bytes.Buffer
+ err := htmlTemplate.Execute(&buf, htmlContext{
+ R: r,
+ CSS: template.CSS(reportCSS),
+ HasSeaportal: hasSeaportal(r),
+ HasElements: hasElements(r),
+ HasVisualDiff: hasVisualDiff(r),
+ HasTiming: hasTiming(r),
+ HasConsole: hasConsoleProblems(r),
+ HasBroken: hasBrokenAssets(r),
+ Usability: usabilityPages(r),
+ Recommendations: recommendations(r),
+ Screenshots: screenshots,
+ })
+ if err != nil {
+ return nil, err
+ }
+ return buf.Bytes(), nil
+}
+
+var comparisonHTMLTemplate = template.Must(template.New("comparison").Funcs(template.FuncMap{
+ "pct": func(p *float64) string {
+ if p == nil {
+ return "-"
+ }
+ return fmt.Sprintf("%.2f%%", *p)
+ },
+}).Parse(`<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<title>Site Comparison Report</title>
+<style>{{.CSS}}</style>
+</head>
+<body>
+<h1>Site Comparison Report</h1>
+<p>Schema version {{.R.SchemaVersion}} · generated {{.R.GeneratedAt.Format "2006-01-02 15:04:05 UTC"}}</p>
+<p>Live: {{.R.LiveBase}}<br>Staging: {{.R.StagingBase}}<br>Differences found: {{.R.HasDiffs}}</p>
+
+<h2>Summary</h2>
+<table><tr><th>Page</th><th>Status</th><th>Visual diff</th><th>Data drift</th><th>Diff image</th></tr>
+{{range .R.Pages}}<tr><td>{{if .Path}}{{.Path}}{{else}}(base){{end}}</td><td>{{.Status}}</td><td>{{pct .DiffPercentage}}</td><td>{{len .Drift}}</td><td>{{if .DiffImagePath}}<img class="screenshot" src="{{.DiffImagePath}}" alt="Diff for {{.Path}}">{{end}}</td></tr>
+{{end}}</table>
+</body>
+</html>
+`))
+
+func renderComparisonHTML(r audit.ComparisonReport) ([]byte, error) {
+ var buf bytes.Buffer
+ err := comparisonHTMLTemplate.Execute(&buf, struct {
+ R audit.ComparisonReport
+ CSS template.CSS
+ }{r, template.CSS(reportCSS)})
+ if err != nil {
+ return nil, err
+ }
+ return buf.Bytes(), nil
+}
diff --git a/internal/audit/report/markdown.go b/internal/audit/report/markdown.go
new file mode 100644
index 00000000..7a0edf30
--- /dev/null
+++ b/internal/audit/report/markdown.go
@@ -0,0 +1,226 @@
+package report
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/pinchtab/pinchtab/internal/audit"
+)
+
+func renderMarkdown(r audit.AuditReport) []byte {
+ var b strings.Builder
+ w := func(format string, args ...any) { fmt.Fprintf(&b, format+"\n", args...) }
+
+ w("# Site Audit Report")
+ w("")
+ w("- Schema version: %s", r.SchemaVersion)
+ w("- Generated: %s", r.GeneratedAt.Format("2006-01-02 15:04:05 UTC"))
+ w("- Pages audited: %d", len(r.Pages))
+ w("")
+
+ w("## Summary")
+ w("")
+ w("**Summary score: %d/100**", r.SummaryScore)
+ w("")
+ w("| Page | Score | Load | Broken assets | Console errors | Status |")
+ w("|---|---|---|---|---|---|")
+ for _, p := range r.Pages {
+ status := "ok"
+ if p.Error != "" {
+ status = "error: " + p.Error
+ }
+ w("| %s | %d | %s | %d | %d | %s |",
+ pageLabel(p), p.Browser.AccessibilityScore, formatMs(p.Browser.TimingMetrics.Load),
+ len(p.Browser.BrokenAssets), pageConsoleErrors(p), status)
+ }
+ w("")
+
+ if hasSeaportal(r) {
+ w("## SEO & Metadata")
+ w("")
+ for _, p := range r.Pages {
+ if len(p.Seaportal) == 0 {
+ continue
+ }
+ w("### %s", pageLabel(p))
+ w("")
+ for _, k := range sortedKeys(p.Seaportal) {
+ w("- %s: %v", k, p.Seaportal[k])
+ }
+ w("")
+ }
+ }
+
+ if hasElements(r) {
+ w("## Content & Functionality")
+ w("")
+ w("| Page | Title | Interactive elements |")
+ w("|---|---|---|")
+ for _, p := range r.Pages {
+ w("| %s | %s | %d |", p.URL, p.Title, len(p.Browser.InteractiveElements))
+ }
+ w("")
+ }
+
+ if hasVisualDiff(r) {
+ w("## Visual Differences")
+ w("")
+ w("| Page | Changed | Diff pixels | Diff ratio | Diff image |")
+ w("|---|---|---|---|---|")
+ for _, p := range r.Pages {
+ vd := p.Browser.VisualDiff
+ if vd == nil {
+ continue
+ }
+ w("| %s | %v | %d | %.4f | %s |", pageLabel(p), vd.Changed, vd.DiffPixels, vd.DiffRatio, vd.DiffPath)
+ }
+ w("")
+ }
+
+ if hasTiming(r) {
+ w("## Performance")
+ w("")
+ w("| Page | TTFB | FCP | LCP | CLS | DOMContentLoaded | Load |")
+ w("|---|---|---|---|---|---|---|")
+ for _, p := range r.Pages {
+ t := p.Browser.TimingMetrics
+ if t == (audit.BrowserTimingMetrics{}) {
+ continue
+ }
+ w("| %s | %s | %s | %s | %s | %s | %s |", pageLabel(p),
+ formatMs(t.TimeToFirstByte), formatMs(t.FirstContentfulPaint), formatMs(t.LargestContentfulPaint),
+ formatCLS(t.CumulativeLayoutShift), formatMs(t.DOMContentLoaded), formatMs(t.Load))
+ }
+ w("")
+ }
+
+ if hasConsoleProblems(r) {
+ w("## Console & JS Errors")
+ w("")
+ for _, p := range r.Pages {
+ problems := consoleProblems(p)
+ if len(problems) == 0 {
+ continue
+ }
+ w("### %s", pageLabel(p))
+ w("")
+ for _, l := range problems {
+ w("- `%s` %s", l.Level, l.Message)
+ }
+ w("")
+ }
+ }
+
+ if hasBrokenAssets(r) {
+ w("## Broken Assets")
+ w("")
+ w("| Page | Asset | Type | Status |")
+ w("|---|---|---|---|")
+ for _, p := range r.Pages {
+ for _, a := range p.Browser.BrokenAssets {
+ status := fmt.Sprintf("%d", a.Status)
+ if a.Status == 0 {
+ status = a.Error
+ }
+ w("| %s | %s | %s | %s |", pageLabel(p), a.URL, a.ResourceType, status)
+ }
+ }
+ w("")
+ }
+
+ if pages := usabilityPages(r); len(pages) > 0 {
+ w("## Usability Issues")
+ w("")
+ for _, p := range pages {
+ w("- %s: accessibility score %d/100", pageLabel(p), p.Browser.AccessibilityScore)
+ }
+ w("")
+ }
+
+ if len(r.SecurityFindings) > 0 {
+ w("## Security Findings")
+ w("")
+ for _, f := range r.SecurityFindings {
+ suffix := ""
+ if f.URL != "" {
+ suffix = " (" + f.URL + ")"
+ }
+ w("- **%s** [%s]: %s%s", f.RuleID, f.Severity, f.Detail, suffix)
+ }
+ w("")
+ }
+
+ if recs := recommendations(r); len(recs) > 0 {
+ w("## Recommendations")
+ w("")
+ for i, rec := range recs {
+ w("%d. %s", i+1, rec)
+ }
+ w("")
+ }
+
+ return []byte(b.String())
+}
+
+func pageConsoleErrors(p audit.PageResult) int {
+ n := 0
+ for _, l := range p.Browser.ConsoleLogs {
+ if l.Level == "error" {
+ n++
+ }
+ }
+ return n
+}
+
+func renderComparisonMarkdown(r audit.ComparisonReport) []byte {
+ var b strings.Builder
+ w := func(format string, args ...any) { fmt.Fprintf(&b, format+"\n", args...) }
+
+ w("# Site Comparison Report")
+ w("")
+ w("- Schema version: %s", r.SchemaVersion)
+ w("- Generated: %s", r.GeneratedAt.Format("2006-01-02 15:04:05 UTC"))
+ w("- Live: %s", r.LiveBase)
+ w("- Staging: %s", r.StagingBase)
+ w("- Differences found: %v", r.HasDiffs)
+ w("")
+
+ w("## Summary")
+ w("")
+ w("| Page | Status | Visual diff | Data drift | Diff image |")
+ w("|---|---|---|---|---|")
+ for _, p := range r.Pages {
+ label := p.Path
+ if label == "" {
+ label = "(base)"
+ }
+ visual := "-"
+ if p.DiffPercentage != nil {
+ visual = fmt.Sprintf("%.2f%%", *p.DiffPercentage)
+ }
+ w("| %s | %s | %s | %d | %s |", label, p.Status, visual, len(p.Drift), p.DiffImagePath)
+ }
+ w("")
+
+ drifted := false
+ for _, p := range r.Pages {
+ if len(p.Drift) > 0 {
+ drifted = true
+ break
+ }
+ }
+ if drifted {
+ w("## Data Drift")
+ w("")
+ w("| Page | Field | Live | Staging |")
+ w("|---|---|---|---|")
+ for _, p := range r.Pages {
+ for _, d := range p.Drift {
+ w("| %s | %s | %s | %s |", p.Path, d.Field, d.Live, d.Staging)
+ }
+ }
+ w("")
+ }
+
+ return []byte(b.String())
+}
diff --git a/internal/audit/report/report.go b/internal/audit/report/report.go
new file mode 100644
index 00000000..a80bd5e3
--- /dev/null
+++ b/internal/audit/report/report.go
@@ -0,0 +1,202 @@
+// Package report renders audit results into human-readable Markdown and
+// self-contained HTML. Sections without data are omitted entirely (the
+// documented empty-section policy); the JSON report remains the complete
+// machine interface. Rendering is deterministic: stable section and item
+// ordering, sorted map keys, and no wall-clock reads — the only timestamp
+// is the report's own GeneratedAt.
+package report
+
+import (
+ "fmt"
+ "sort"
+ "strings"
+
+ "github.com/pinchtab/pinchtab/internal/audit"
+)
+
+// Formats accepted by Render.
+const (
+ FormatJSON = "json"
+ FormatMarkdown = "md"
+ FormatHTML = "html"
+)
+
+// Render renders an AuditReport as Markdown or HTML. FormatJSON is the
+// caller's business (the report already is JSON) and is rejected here.
+func Render(r audit.AuditReport, format string) ([]byte, error) {
+ switch format {
+ case FormatMarkdown:
+ return renderMarkdown(r), nil
+ case FormatHTML:
+ return renderHTML(r)
+ default:
+ return nil, fmt.Errorf("unsupported render format %q (md|html)", format)
+ }
+}
+
+// RenderComparison renders a ComparisonReport as Markdown or HTML.
+func RenderComparison(r audit.ComparisonReport, format string) ([]byte, error) {
+ switch format {
+ case FormatMarkdown:
+ return renderComparisonMarkdown(r), nil
+ case FormatHTML:
+ return renderComparisonHTML(r)
+ default:
+ return nil, fmt.Errorf("unsupported render format %q (md|html)", format)
+ }
+}
+
+func pageLabel(p audit.PageResult) string {
+ if p.Title != "" {
+ return p.Title
+ }
+ return p.URL
+}
+
+func hasSeaportal(r audit.AuditReport) bool {
+ for _, p := range r.Pages {
+ if len(p.Seaportal) > 0 {
+ return true
+ }
+ }
+ return false
+}
+
+func hasVisualDiff(r audit.AuditReport) bool {
+ for _, p := range r.Pages {
+ if p.Browser.VisualDiff != nil {
+ return true
+ }
+ }
+ return false
+}
+
+func hasTiming(r audit.AuditReport) bool {
+ for _, p := range r.Pages {
+ if p.Browser.TimingMetrics != (audit.BrowserTimingMetrics{}) {
+ return true
+ }
+ }
+ return false
+}
+
+func hasElements(r audit.AuditReport) bool {
+ for _, p := range r.Pages {
+ if len(p.Browser.InteractiveElements) > 0 {
+ return true
+ }
+ }
+ return false
+}
+
+// consoleProblems returns the error and warning console entries of a page.
+func consoleProblems(p audit.PageResult) []audit.ConsoleLogEntry {
+ var out []audit.ConsoleLogEntry
+ for _, l := range p.Browser.ConsoleLogs {
+ if l.Level == "error" || l.Level == "warning" || l.Level == "warn" {
+ out = append(out, l)
+ }
+ }
+ return out
+}
+
+func hasConsoleProblems(r audit.AuditReport) bool {
+ for _, p := range r.Pages {
+ if len(consoleProblems(p)) > 0 {
+ return true
+ }
+ }
+ return false
+}
+
+func hasBrokenAssets(r audit.AuditReport) bool {
+ for _, p := range r.Pages {
+ if len(p.Browser.BrokenAssets) > 0 {
+ return true
+ }
+ }
+ return false
+}
+
+// usabilityPages are the pages with a below-perfect accessibility score.
+func usabilityPages(r audit.AuditReport) []audit.PageResult {
+ var out []audit.PageResult
+ for _, p := range r.Pages {
+ if p.Error == "" && p.Browser.AccessibilityScore < 100 {
+ out = append(out, p)
+ }
+ }
+ return out
+}
+
+func totalBrokenAssets(r audit.AuditReport) int {
+ n := 0
+ for _, p := range r.Pages {
+ n += len(p.Browser.BrokenAssets)
+ }
+ return n
+}
+
+func totalConsoleErrors(r audit.AuditReport) int {
+ n := 0
+ for _, p := range r.Pages {
+ for _, l := range p.Browser.ConsoleLogs {
+ if l.Level == "error" {
+ n++
+ }
+ }
+ }
+ return n
+}
+
+// recommendations merges the report's explicit recommendations with
+// rule-derived ones, in a stable order.
+func recommendations(r audit.AuditReport) []string {
+ recs := append([]string(nil), r.Recommendations...)
+ if n := totalBrokenAssets(r); n > 0 {
+ recs = append(recs, fmt.Sprintf("Fix %d broken asset reference(s) — see Broken Assets.", n))
+ }
+ if n := totalConsoleErrors(r); n > 0 {
+ recs = append(recs, fmt.Sprintf("Investigate %d console error(s) — see Console & JS Errors.", n))
+ }
+ if pages := usabilityPages(r); len(pages) > 0 {
+ recs = append(recs, fmt.Sprintf("Improve accessibility on %d page(s) scoring below 100 — see Usability Issues.", len(pages)))
+ }
+ if n := len(r.SecurityFindings); n > 0 {
+ recs = append(recs, fmt.Sprintf("Address %d security finding(s) — see Security Findings.", n))
+ }
+ failed := 0
+ for _, p := range r.Pages {
+ if p.Error != "" {
+ failed++
+ }
+ }
+ if failed > 0 {
+ recs = append(recs, fmt.Sprintf("Re-check %d page(s) that failed to audit.", failed))
+ }
+ return recs
+}
+
+// sortedKeys returns a map's keys in stable sorted order.
+func sortedKeys(m map[string]any) []string {
+ keys := make([]string, 0, len(m))
+ for k := range m {
+ keys = append(keys, k)
+ }
+ sort.Strings(keys)
+ return keys
+}
+
+func formatMs(v float64) string {
+ if v == 0 {
+ return "-"
+ }
+ return fmt.Sprintf("%.0f ms", v)
+}
+
+func formatCLS(v float64) string {
+ if v == 0 {
+ return "0"
+ }
+ return strings.TrimRight(strings.TrimRight(fmt.Sprintf("%.3f", v), "0"), ".")
+}
diff --git a/internal/audit/report/report_test.go b/internal/audit/report/report_test.go
new file mode 100644
index 00000000..3de64403
--- /dev/null
+++ b/internal/audit/report/report_test.go
@@ -0,0 +1,216 @@
+package report
+
+import (
+ "bytes"
+ "flag"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/audit"
+)
+
+var update = flag.Bool("update", false, "regenerate golden files")
+
+// sampleReport exercises every section: seaportal metadata, elements,
+// visual diff, timing, console errors, broken assets, usability, security
+// findings, and recommendations. GeneratedAt is fixed for determinism.
+func sampleReport() audit.AuditReport {
+ r := audit.NewAuditReport()
+ r.GeneratedAt = time.Date(2026, 7, 4, 12, 0, 0, 0, time.UTC)
+ r.Input = audit.AuditInput{URLs: []string{"http://fixtures/audit-site/index.html"}}
+ r.Options = audit.AuditOptions{Screenshot: true, NetworkMonitor: true, Concurrency: 2}
+ r.SummaryScore = 85
+ r.SecurityFindings = []audit.SecurityFinding{
+ {RuleID: "insecure-form-action", Severity: "medium", Detail: "password posts over http", URL: "http://fixtures/audit-site/forms.html"},
+ }
+ r.Recommendations = []string{"Serve the site over https."}
+ r.Pages = []audit.PageResult{
+ {
+ URL: "http://fixtures/audit-site/index.html",
+ Title: "Audit Fixture Site",
+ Seaportal: map[string]any{
+ "title": "Audit Fixture Site",
+ "description": "Deterministic audit fixture site.",
+ "confidence": 90,
+ },
+ Browser: audit.BrowserPageData{
+ ScreenshotPath: "screenshots/page-001.png",
+ ConsoleLogs: []audit.ConsoleLogEntry{
+ {Level: "error", Message: "boom"},
+ {Level: "warning", Message: "careful"},
+ {Level: "log", Message: "ignored in report"},
+ },
+ BrokenAssets: []audit.BrokenAsset{
+ {URL: "http://fixtures/audit-site/assets/missing.png", ResourceType: "image", Status: 404},
+ {URL: "http://fixtures/api", ResourceType: "xhr", Error: "net::ERR_FAILED"},
+ },
+ InteractiveElements: []audit.InteractiveElement{{Ref: "e1", Role: "link", Name: "Home"}},
+ AccessibilityScore: 70,
+ VisualDiff: &audit.VisualDiffResult{BaselinePath: "base.png", CurrentPath: "cur.png", DiffPath: "diffs/index.diff.png", DiffPixels: 120, DiffRatio: 0.02, Changed: true},
+ TimingMetrics: audit.BrowserTimingMetrics{TimeToFirstByte: 5, FirstContentfulPaint: 120, LargestContentfulPaint: 300, CumulativeLayoutShift: 0.05, DOMContentLoaded: 90, Load: 200},
+ },
+ },
+ {
+ URL: "http://fixtures/audit-site/down.html",
+ Error: "navigation failed: net::ERR_CONNECTION_REFUSED",
+ },
+ }
+ return r
+}
+
+func goldenCompare(t *testing.T, name string, got []byte) {
+ t.Helper()
+ path := filepath.Join("testdata", name)
+ if *update {
+ if err := os.MkdirAll("testdata", 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(path, got, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ want, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("read golden %s: %v (run `go test -update`)", path, err)
+ }
+ if !bytes.Equal(got, want) {
+ t.Errorf("%s differs from golden (got %d bytes, want %d)", name, len(got), len(want))
+ }
+}
+
+func TestRenderMarkdownGolden(t *testing.T) {
+ got, err := Render(sampleReport(), FormatMarkdown)
+ if err != nil {
+ t.Fatalf("Render: %v", err)
+ }
+ goldenCompare(t, "report.golden.md", got)
+}
+
+func TestRenderHTMLGolden(t *testing.T) {
+ got, err := Render(sampleReport(), FormatHTML)
+ if err != nil {
+ t.Fatalf("Render: %v", err)
+ }
+ goldenCompare(t, "report.golden.html", got)
+}
+
+func TestAllSectionsPresent(t *testing.T) {
+ md, err := Render(sampleReport(), FormatMarkdown)
+ if err != nil {
+ t.Fatalf("Render: %v", err)
+ }
+ for _, heading := range []string{
+ "## Summary",
+ "## SEO & Metadata",
+ "## Content & Functionality",
+ "## Visual Differences",
+ "## Performance",
+ "## Console & JS Errors",
+ "## Broken Assets",
+ "## Usability Issues",
+ "## Security Findings",
+ "## Recommendations",
+ } {
+ if !strings.Contains(string(md), heading) {
+ t.Errorf("markdown missing heading %q", heading)
+ }
+ }
+}
+
+func TestEmptySectionsOmitted(t *testing.T) {
+ r := audit.NewAuditReport()
+ r.GeneratedAt = time.Date(2026, 7, 4, 12, 0, 0, 0, time.UTC)
+ r.SummaryScore = 100
+ r.Pages = []audit.PageResult{{URL: "http://x/clean.html", Title: "Clean", Browser: audit.BrowserPageData{AccessibilityScore: 100}}}
+
+ md, err := Render(r, FormatMarkdown)
+ if err != nil {
+ t.Fatalf("Render: %v", err)
+ }
+ if !strings.Contains(string(md), "## Summary") {
+ t.Error("Summary must always render")
+ }
+ for _, absent := range []string{"## Broken Assets", "## Security Findings", "## Console", "## Visual Differences", "## SEO", "## Usability"} {
+ if strings.Contains(string(md), absent) {
+ t.Errorf("empty section %q should be omitted", absent)
+ }
+ }
+}
+
+func TestRenderDeterministic(t *testing.T) {
+ for _, format := range []string{FormatMarkdown, FormatHTML} {
+ first, err := Render(sampleReport(), format)
+ if err != nil {
+ t.Fatalf("Render(%s): %v", format, err)
+ }
+ for range 5 {
+ again, err := Render(sampleReport(), format)
+ if err != nil {
+ t.Fatalf("Render(%s): %v", format, err)
+ }
+ if !bytes.Equal(first, again) {
+ t.Fatalf("%s rendering is not byte-identical across runs", format)
+ }
+ }
+ }
+}
+
+func TestHTMLSelfContained(t *testing.T) {
+ html, err := Render(sampleReport(), FormatHTML)
+ if err != nil {
+ t.Fatalf("Render: %v", err)
+ }
+ s := string(html)
+ if !strings.Contains(s, "<style>") {
+ t.Error("HTML must inline its CSS")
+ }
+ for _, external := range []string{"<link ", "<script src", "https://cdn.", "@import"} {
+ if strings.Contains(s, external) {
+ t.Errorf("HTML must be self-contained, found %q", external)
+ }
+ }
+ if !strings.Contains(s, `src="screenshots/page-001.png"`) {
+ t.Error("screenshot links must stay relative")
+ }
+}
+
+func TestRenderRejectsUnknownFormat(t *testing.T) {
+ if _, err := Render(sampleReport(), "pdf"); err == nil {
+ t.Error("Render should reject unsupported formats")
+ }
+ if _, err := RenderComparison(audit.ComparisonReport{}, "json"); err == nil {
+ t.Error("RenderComparison should reject unsupported formats")
+ }
+}
+
+func TestRenderComparisonMarkdown(t *testing.T) {
+ pct := 2.5
+ cr := audit.ComparisonReport{
+ SchemaVersion: audit.SchemaVersion,
+ GeneratedAt: time.Date(2026, 7, 4, 12, 0, 0, 0, time.UTC),
+ LiveBase: "http://x/live/",
+ StagingBase: "http://x/stage/",
+ HasDiffs: true,
+ Pages: []audit.PageComparison{
+ {Path: "index.html", Status: audit.CompareStatusCompared, DiffPercentage: &pct, DiffImagePath: "diffs/index.html.diff.png",
+ Drift: []audit.DataDrift{{Field: "accessibilityScore", Live: "100", Staging: "90"}}},
+ {Path: "gone.html", Status: audit.CompareStatusRemoved, Drift: []audit.DataDrift{}},
+ },
+ }
+ md, err := RenderComparison(cr, FormatMarkdown)
+ if err != nil {
+ t.Fatalf("RenderComparison: %v", err)
+ }
+ for _, want := range []string{"# Site Comparison Report", "## Summary", "## Data Drift", "2.50%", "removed"} {
+ if !strings.Contains(string(md), want) {
+ t.Errorf("comparison markdown missing %q", want)
+ }
+ }
+
+ if _, err := RenderComparison(cr, FormatHTML); err != nil {
+ t.Errorf("RenderComparison html: %v", err)
+ }
+}
diff --git a/internal/audit/report/testdata/report.golden.html b/internal/audit/report/testdata/report.golden.html
new file mode 100644
index 00000000..e72167e4
--- /dev/null
+++ b/internal/audit/report/testdata/report.golden.html
@@ -0,0 +1,88 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<title>Site Audit Report</title>
+<style>
+body { font-family: -apple-system, "Segoe UI", Roboto, sans-serif; margin: 2rem auto; max-width: 60rem; padding: 0 1rem; color: #1a1a2e; }
+h1 { border-bottom: 2px solid #0a6cff; padding-bottom: .3rem; }
+h2 { margin-top: 2rem; border-bottom: 1px solid #d0d4dd; padding-bottom: .2rem; }
+table { border-collapse: collapse; width: 100%; margin: .5rem 0 1rem; }
+th, td { border: 1px solid #d0d4dd; padding: .35rem .6rem; text-align: left; font-size: .92rem; }
+th { background: #f2f4f8; }
+.score { font-size: 1.3rem; font-weight: 700; }
+.error { color: #c0182b; }
+img.screenshot { max-width: 100%; border: 1px solid #d0d4dd; margin: .3rem 0 1rem; }
+code { background: #f2f4f8; padding: .1rem .3rem; border-radius: 3px; }
+</style>
+</head>
+<body>
+<h1>Site Audit Report</h1>
+<p>Schema version 1.0 · generated 2026-07-04 12:00:00 UTC · 2 page(s)</p>
+
+<h2>Summary</h2>
+<p class="score">Summary score: 85/100</p>
+<table>
+<tr><th>Page</th><th>Score</th><th>Load</th><th>Broken assets</th><th>Console errors</th><th>Status</th></tr>
+<tr><td>Audit Fixture Site</td><td>70</td><td>200 ms</td><td>2</td><td>1</td><td>ok</td></tr>
+<tr><td>http://fixtures/audit-site/down.html</td><td>0</td><td>-</td><td>0</td><td>0</td><td><span class="error">navigation failed: net::ERR_CONNECTION_REFUSED</span></td></tr>
+</table>
+
+<h2>SEO &amp; Metadata</h2>
+<h3>Audit Fixture Site</h3><table>
+<tr><th>confidence</th><td>90</td></tr>
+<tr><th>description</th><td>Deterministic audit fixture site.</td></tr>
+<tr><th>title</th><td>Audit Fixture Site</td></tr>
+</table>
+
+<h2>Content &amp; Functionality</h2>
+<table><tr><th>Page</th><th>Title</th><th>Interactive elements</th></tr>
+<tr><td>http://fixtures/audit-site/index.html</td><td>Audit Fixture Site</td><td>1</td></tr>
+<tr><td>http://fixtures/audit-site/down.html</td><td></td><td>0</td></tr>
+</table>
+
+<h2>Visual Differences</h2>
+<table><tr><th>Page</th><th>Changed</th><th>Diff pixels</th><th>Diff ratio</th><th>Diff image</th></tr>
+<tr><td>Audit Fixture Site</td><td>true</td><td>120</td><td>0.0200</td><td>diffs/index.diff.png</td></tr>
+
+</table>
+
+<h2>Performance</h2>
+<table><tr><th>Page</th><th>TTFB</th><th>FCP</th><th>LCP</th><th>CLS</th><th>Load</th></tr>
+<tr><td>Audit Fixture Site</td><td>5 ms</td><td>120 ms</td><td>300 ms</td><td>0.05</td><td>200 ms</td></tr>
+<tr><td>http://fixtures/audit-site/down.html</td><td>-</td><td>-</td><td>-</td><td>0</td><td>-</td></tr>
+</table>
+
+<h2>Console &amp; JS Errors</h2>
+<h3>Audit Fixture Site</h3><ul>
+<li><code>error</code> boom</li>
+<li><code>warning</code> careful</li>
+</ul>
+
+<h2>Broken Assets</h2>
+<table><tr><th>Page</th><th>Asset</th><th>Type</th><th>Status</th></tr>
+<tr><td>Audit Fixture Site</td><td>http://fixtures/audit-site/assets/missing.png</td><td>image</td><td>404</td></tr>
+<tr><td>Audit Fixture Site</td><td>http://fixtures/api</td><td>xhr</td><td>net::ERR_FAILED</td></tr>
+</table>
+
+<h2>Usability Issues</h2><ul>
+<li>Audit Fixture Site: accessibility score 70/100</li>
+</ul>
+
+<h2>Security Findings</h2><ul>
+<li><strong>insecure-form-action</strong> [medium]: password posts over http (http://fixtures/audit-site/forms.html)</li>
+</ul>
+
+<h2>Recommendations</h2><ol>
+<li>Serve the site over https.</li>
+<li>Fix 2 broken asset reference(s) — see Broken Assets.</li>
+<li>Investigate 1 console error(s) — see Console &amp; JS Errors.</li>
+<li>Improve accessibility on 1 page(s) scoring below 100 — see Usability Issues.</li>
+<li>Address 1 security finding(s) — see Security Findings.</li>
+<li>Re-check 1 page(s) that failed to audit.</li>
+</ol>
+
+<h2>Screenshots</h2>
+<h3>Audit Fixture Site</h3><img class="screenshot" src="screenshots/page-001.png" alt="Screenshot of Audit Fixture Site">
+</body>
+</html>
diff --git a/internal/audit/report/testdata/report.golden.md b/internal/audit/report/testdata/report.golden.md
new file mode 100644
index 00000000..13488aab
--- /dev/null
+++ b/internal/audit/report/testdata/report.golden.md
@@ -0,0 +1,73 @@
+# Site Audit Report
+
+- Schema version: 1.0
+- Generated: 2026-07-04 12:00:00 UTC
+- Pages audited: 2
+
+## Summary
+
+**Summary score: 85/100**
+
+| Page | Score | Load | Broken assets | Console errors | Status |
+|---|---|---|---|---|---|
+| Audit Fixture Site | 70 | 200 ms | 2 | 1 | ok |
+| http://fixtures/audit-site/down.html | 0 | - | 0 | 0 | error: navigation failed: net::ERR_CONNECTION_REFUSED |
+
+## SEO & Metadata
+
+### Audit Fixture Site
+
+- confidence: 90
+- description: Deterministic audit fixture site.
+- title: Audit Fixture Site
+
+## Content & Functionality
+
+| Page | Title | Interactive elements |
+|---|---|---|
+| http://fixtures/audit-site/index.html | Audit Fixture Site | 1 |
+| http://fixtures/audit-site/down.html | | 0 |
+
+## Visual Differences
+
+| Page | Changed | Diff pixels | Diff ratio | Diff image |
+|---|---|---|---|---|
+| Audit Fixture Site | true | 120 | 0.0200 | diffs/index.diff.png |
+
+## Performance
+
+| Page | TTFB | FCP | LCP | CLS | DOMContentLoaded | Load |
+|---|---|---|---|---|---|---|
+| Audit Fixture Site | 5 ms | 120 ms | 300 ms | 0.05 | 90 ms | 200 ms |
+
+## Console & JS Errors
+
+### Audit Fixture Site
+
+- `error` boom
+- `warning` careful
+
+## Broken Assets
+
+| Page | Asset | Type | Status |
+|---|---|---|---|
+| Audit Fixture Site | http://fixtures/audit-site/assets/missing.png | image | 404 |
+| Audit Fixture Site | http://fixtures/api | xhr | net::ERR_FAILED |
+
+## Usability Issues
+
+- Audit Fixture Site: accessibility score 70/100
+
+## Security Findings
+
+- **insecure-form-action** [medium]: password posts over http (http://fixtures/audit-site/forms.html)
+
+## Recommendations
+
+1. Serve the site over https.
+2. Fix 2 broken asset reference(s) — see Broken Assets.
+3. Investigate 1 console error(s) — see Console & JS Errors.
+4. Improve accessibility on 1 page(s) scoring below 100 — see Usability Issues.
+5. Address 1 security finding(s) — see Security Findings.
+6. Re-check 1 page(s) that failed to audit.
+
diff --git a/internal/cli/actions/actions_audit.go b/internal/cli/actions/actions_audit.go
index 30003bb2..9f35a4c7 100644
--- a/internal/cli/actions/actions_audit.go
+++ b/internal/cli/actions/actions_audit.go
@@ -9,6 +9,8 @@ import (
"path/filepath"
"time"
+ "github.com/pinchtab/pinchtab/internal/audit"
+ auditreport "github.com/pinchtab/pinchtab/internal/audit/report"
"github.com/pinchtab/pinchtab/internal/cli/apiclient"
"github.com/spf13/cobra"
)
@@ -68,12 +70,28 @@ func Audit(client *http.Client, base, token string, cmd *cobra.Command, target s
os.Exit(1)
}
+ format := renderFormat(cmd)
+
if dir, _ := cmd.Flags().GetString("output-dir"); dir != "" {
if err := writeAuditArtifacts(dir, report); err != nil {
fmt.Fprintf(os.Stderr, "write artifacts: %v\n", err)
os.Exit(1)
}
+ if format != auditreport.FormatJSON {
+ if err := renderAuditReportFile(dir, report, format); err != nil {
+ fmt.Fprintf(os.Stderr, "render report: %v\n", err)
+ os.Exit(1)
+ }
+ }
fmt.Fprintf(os.Stderr, "report written to %s\n", filepath.Join(dir, "report.json"))
+ } else if format != auditreport.FormatJSON {
+ rendered, err := auditreport.Render(typedAuditReport(report), format)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "render report: %v\n", err)
+ os.Exit(1)
+ }
+ fmt.Println(string(rendered))
+ return
}
if v, _ := cmd.Flags().GetBool("json"); v {
@@ -84,6 +102,33 @@ func Audit(client *http.Client, base, token string, cmd *cobra.Command, target s
printAuditSummary(report)
}
+// renderFormat reads the --format flag, defaulting to json.
+func renderFormat(cmd *cobra.Command) string {
+ f := mustString(cmd, "format")
+ if f == "" {
+ return auditreport.FormatJSON
+ }
+ return f
+}
+
+// typedAuditReport converts the generic report map (possibly mutated by
+// artifact writing) back into the typed schema for rendering.
+func typedAuditReport(report map[string]any) audit.AuditReport {
+ data, _ := json.Marshal(report)
+ var typed audit.AuditReport
+ _ = json.Unmarshal(data, &typed)
+ return typed
+}
+
+// renderAuditReportFile writes report.md / report.html next to report.json.
+func renderAuditReportFile(dir string, report map[string]any, format string) error {
+ rendered, err := auditreport.Render(typedAuditReport(report), format)
+ if err != nil {
+ return err
+ }
+ return os.WriteFile(filepath.Join(dir, "report."+format), rendered, 0o644)
+}
+
// writeAuditArtifacts writes report.json and screenshots/ under dir. Inline
// base64 screenshots are moved to files and each page's browser entry gets
// the relative screenshotPath instead.
diff --git a/internal/cli/actions/actions_compare.go b/internal/cli/actions/actions_compare.go
index 7be24a55..0237bd9c 100644
--- a/internal/cli/actions/actions_compare.go
+++ b/internal/cli/actions/actions_compare.go
@@ -9,6 +9,7 @@ import (
"strings"
"github.com/pinchtab/pinchtab/internal/audit"
+ auditreport "github.com/pinchtab/pinchtab/internal/audit/report"
"github.com/pinchtab/pinchtab/internal/cli/apiclient"
"github.com/spf13/cobra"
)
@@ -55,10 +56,27 @@ func Compare(client *http.Client, base, token string, cmd *cobra.Command, liveBa
fmt.Fprintf(os.Stderr, "report written to %s\n", filepath.Join(dir, "report.json"))
}
+ format := renderFormat(cmd)
+ if format != auditreport.FormatJSON {
+ rendered, err := auditreport.RenderComparison(outcome.Report, format)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "render report: %v\n", err)
+ os.Exit(1)
+ }
+ if dir, _ := cmd.Flags().GetString("output-dir"); dir != "" {
+ if err := os.WriteFile(filepath.Join(dir, "report."+format), rendered, 0o644); err != nil {
+ fmt.Fprintf(os.Stderr, "write rendered report: %v\n", err)
+ os.Exit(1)
+ }
+ } else {
+ fmt.Println(string(rendered))
+ }
+ }
+
if mustBool(cmd, "json") {
out, _ := json.MarshalIndent(outcome.Report, "", " ")
fmt.Println(string(out))
- } else {
+ } else if format == auditreport.FormatJSON {
printCompareSummary(outcome.Report)
}
diff --git a/tests/e2e/scenarios/cli/audit-report-basic.sh b/tests/e2e/scenarios/cli/audit-report-basic.sh
new file mode 100755
index 00000000..6f223cf4
--- /dev/null
+++ b/tests/e2e/scenarios/cli/audit-report-basic.sh
@@ -0,0 +1,58 @@
+#!/bin/bash
+# audit-report-basic.sh — pinchtab audit --format md/html rendered reports.
+
+GROUP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+source "${GROUP_DIR}/../../helpers/cli.sh"
+
+OUT_DIR=$(mktemp -d /tmp/audit-report.XXXXXX)
+
+# ─────────────────────────────────────────────────────────────────
+start_test "audit --format md writes report.md next to report.json"
+
+pt_ok audit "${FIXTURES_URL}/audit-site/broken-assets.html" --output-dir "$OUT_DIR" --format md
+
+if [ -f "$OUT_DIR/report.json" ]; then
+ pass_assert "report.json exists"
+else
+ fail_assert "report.json exists"
+fi
+if [ -f "$OUT_DIR/report.md" ]; then
+ pass_assert "report.md exists"
+else
+ fail_assert "report.md exists"
+fi
+
+for heading in "## Summary" "## Broken Assets"; do
+ if grep -q "$heading" "$OUT_DIR/report.md" 2>/dev/null; then
+ pass_assert "report.md contains '$heading'"
+ else
+ fail_assert "report.md contains '$heading'"
+ fi
+done
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "audit --format html writes a self-contained report.html"
+
+pt_ok audit "${FIXTURES_URL}/audit-site/broken-assets.html" --output-dir "$OUT_DIR" --format html
+
+if [ -f "$OUT_DIR/report.html" ]; then
+ pass_assert "report.html exists"
+else
+ fail_assert "report.html exists"
+fi
+if grep -q "<style>" "$OUT_DIR/report.html" 2>/dev/null; then
+ pass_assert "report.html inlines its CSS"
+else
+ fail_assert "report.html inlines its CSS"
+fi
+if grep -q 'src="screenshots/' "$OUT_DIR/report.html" 2>/dev/null; then
+ pass_assert "report.html links screenshots relatively"
+else
+ fail_assert "report.html links screenshots relatively"
+fi
+
+end_test
+
+rm -rf "$OUT_DIR"