Skip to content

docs: rewrite README as AI Agent-First specification#101

Merged
cnlangzi merged 4 commits into
mainfrom
docs/ai
Mar 31, 2026
Merged

docs: rewrite README as AI Agent-First specification#101
cnlangzi merged 4 commits into
mainfrom
docs/ai

Conversation

@cnlangzi

@cnlangzi cnlangzi commented Mar 31, 2026

Copy link
Copy Markdown
Member

Changed

  • Replace human-oriented README with precise, AI-executable specification
  • Remove AGENTS.md (merged into README.md as single source of truth)
  • Use IF/THEN/NEVER format for rules, tables for field definitions
  • Number all critical rules (0.1-0.7) for cross-referencing
  • Add complete minimal examples (JSON API, HTML+JSON, embed.FS, middleware group)
  • Consolidate gin/echo/chi differences and "what xun does NOT have"
  • Add section and rule indexes for quick lookup

Fixed

Added

Tests

Tasks to complete before merging PR:

  • Ensure unit tests are passing. If not run make unit-tests to check for any regressions 📋
  • Ensure lint tests are passing. if not run make lint to check for any issues
  • Ensure codecov/patch is passing for changes.

Summary by Sourcery

Rewrite the README into an AI-agent-focused, executable specification for building xun applications, consolidating prior agent-specific guidance into a single authoritative document.

Documentation:

  • Replace the human-oriented README with a structured, rule-based AI Agent Specification that fully documents xun’s architecture, routing, middleware, viewers, view engines, context, and extension ecosystem.
  • Fold the contents of AGENTS.md into the new README and remove AGENTS.md, making the README the single source of truth for agent and implementation behavior.
  • Add numbered critical rules, section and rule indexes, and multiple end-to-end examples (JSON API, HTML+JSON, embed.FS deployment, middleware group usage) to guide automated and human implementers.

- Replace human-oriented README with precise, AI-executable specification
- Remove AGENTS.md (merged into README.md as single source of truth)
- Use IF/THEN/NEVER format for rules, tables for field definitions
- Number all critical rules (0.1-0.7) for cross-referencing
- Add complete minimal examples (JSON API, HTML+JSON, embed.FS, middleware group)
- Consolidate gin/echo/chi differences and "what xun does NOT have"
- Add section and rule indexes for quick lookup

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@codecov

codecov Bot commented Mar 31, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 92.10%. Comparing base (fd82e95) to head (b579c2c).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main     #101   +/-   ##
=======================================
  Coverage   92.10%   92.10%           
=======================================
  Files          66       66           
  Lines        2102     2102           
=======================================
  Hits         1936     1936           
  Misses        136      136           
  Partials       30       30           
Flag Coverage Δ
Unit-Tests 92.10% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@sourcery-ai

sourcery-ai Bot commented Mar 31, 2026

Copy link
Copy Markdown

Reviewer's Guide

Replaces the long, human-oriented README with a compact, rule-driven AI Agent specification that is now the single authoritative source of truth, merging AGENTS.md into it and restructuring all documentation around numbered critical rules, formal type/behavior descriptions, and minimal code examples.

Sequence diagram for request handling and middleware chain in xun

sequenceDiagram
    actor Client
    participant Server as httpServer
    participant Mux as httpServeMux
    participant App
    participant Routing
    participant Group as groupchain
    participant MWA as MiddlewareA
    participant MWB as MiddlewareB
    participant Handler as HandleFunc
    participant Ctx as Context

    Client->>Server: HTTP request
    Server->>Mux: ServeHTTP(request, response)
    Mux->>App: wrappedHandler(response, request)

    App->>Ctx: construct Context
    App->>Routing: lookup Pattern and Routing
    Routing->>Group: Next(HandleFunc)
    Group->>MWA: apply middleware chain
    MWA->>MWB: wrap(next HandleFunc)
    MWB->>Handler: wrap(next HandleFunc)
    Group-->>Routing: composed HandleFunc

    Routing->>Ctx: Next(Ctx)
    activate MWA
    MWA->>MWB: next(Ctx)
    activate MWB
    MWB->>Handler: next(Ctx)
    activate Handler
    Handler-->>MWB: error or nil
    deactivate Handler
    MWB-->>MWA: error or ErrCancelled
    deactivate MWB
    MWA-->>Routing: error or ErrCancelled
    deactivate MWA

    Routing-->>App: error or nil
    App-->>Mux: return
    Mux-->>Server: return
    Server-->>Client: HTTP response
Loading

Sequence diagram for Context.View viewer selection logic

sequenceDiagram
    participant Ctx as Context
    participant Routing
    participant Accept as AcceptHeaders
    participant NamedV as NamedViewer
    participant RouteVs as RouteViewers
    participant FallbackV as FallbackViewer
    participant Viewer as SelectedViewer

    Ctx->>Routing: read Viewers for route
    Ctx->>Accept: parse Accept() from request

    alt named viewer provided
        Ctx->>NamedV: lookup by name in appviewers
        alt MimeType matches any Accept
            Ctx->>Viewer: use NamedViewer
            Viewer->>Ctx: Render(data)
        else no Accept match for named viewer
            Ctx->>RouteVs: iterate routingViewers with Accept
            alt some viewer matches Accept
                Ctx->>Viewer: use first matching viewer
                Viewer->>Ctx: Render(data)
            else no viewer matches Accept
                Ctx->>FallbackV: use first viewer in routingViewers
                alt FallbackV exists
                    FallbackV->>Ctx: Render(data)
                else routingViewers empty
                    Ctx-->>Ctx: return ErrViewNotFound
                end
            end
        end
    else no named viewer
        Ctx->>RouteVs: iterate routingViewers with Accept
        alt some viewer matches Accept
            Ctx->>Viewer: use first matching viewer
            Viewer->>Ctx: Render(data)
        else no viewer matches Accept
            Ctx->>FallbackV: use first viewer in routingViewers
            alt FallbackV exists
                FallbackV->>Ctx: Render(data)
            else routingViewers empty
                Ctx-->>Ctx: return ErrViewNotFound
            end
        end
    end
Loading

Class diagram for core xun types in the AI Agent specification

classDiagram

    class App {
        -mux *http.ServeMux
        -handlerViewers []Viewer
        -fsys fs.FS
        -watch bool
        -interceptor Interceptor
        -compressors []Compressor
        -viewers mapstringViewer
        -routes mapstringRouting
        -funcMap templateFuncMap
        +New(opts ...Option) App
        +Get(pattern string, hf HandleFunc, opts ...RoutingOption)
        +Post(pattern string, hf HandleFunc, opts ...RoutingOption)
        +Put(pattern string, hf HandleFunc, opts ...RoutingOption)
        +Delete(pattern string, hf HandleFunc, opts ...RoutingOption)
        +Group(prefix string) group
        +Start() void
        +Close() void
    }

    class Context {
        +Request *httpRequest
        +Response ResponseWriter
        +Routing Routing
        +App *App
        +TempData mapstringany
        +View(data any, options ...string) error
        +Redirect(url string, statusCode ...int) void
        +AcceptLanguage() []string
        +Accept() []MimeType
        +RequestReferer() string
        +WriteStatus(code int) void
        +WriteHeader(key string, value string) void
        +Get(key string) any
        +Set(key string, value any) void
    }

    class Routing {
        +Pattern string
        +Handle HandleFunc
        -chain chain
        +Options *RoutingOptions
        +Viewers []Viewer
        +Next(ctx *Context) error
    }

    class RoutingOptions {
        -metadata mapstringany
        -viewers []Viewer
        +WithViewer(v ...Viewer) RoutingOption
        +WithMetadata(key string, value any) RoutingOption
        +WithNavigation(name string, icon string, access string) RoutingOption
    }

    class group {
        -prefix string
        -middlewares []Middleware
        -app *App
        +Use(middleware ...Middleware) void
        +Get(pattern string, hf HandleFunc, opts ...RoutingOption)
        +HandleFunc(pattern string, hf HandleFunc, opts ...RoutingOption)
        +Next(hf HandleFunc) HandleFunc
    }

    class Viewer {
        <<interface>>
        +MimeType() MimeType
        +Render(ctx *Context, data any) error
    }

    class HtmlViewer {
        +MimeType() MimeType
        +Render(ctx *Context, data any) error
    }

    class JsonViewer {
        +MimeType() MimeType
        +Render(ctx *Context, data any) error
    }

    class TextViewer {
        +MimeType() MimeType
        +Render(ctx *Context, data any) error
    }

    class FileViewer {
        +MimeType() MimeType
        +Render(ctx *Context, data any) error
    }

    class ViewEngine {
        <<interface>>
        +Load(fsys fsFS, app *App) void
        +FileChanged(fsys fsFS, app *App, event fsnotifyEvent) error
    }

    class StaticViewEngine {
        +Load(fsys fsFS, app *App) void
        +FileChanged(fsys fsFS, app *App, event fsnotifyEvent) error
    }

    class HtmlViewEngine {
        +Load(fsys fsFS, app *App) void
        +FileChanged(fsys fsFS, app *App, event fsnotifyEvent) error
    }

    class TextViewEngine {
        +Load(fsys fsFS, app *App) void
        +FileChanged(fsys fsFS, app *App, event fsnotifyEvent) error
    }

    class MimeType {
        +Type string
        +SubType string
    }

    class ResponseWriter {
        <<interface>>
        +Header() httpHeader
        +Write(b []byte) int
        +WriteHeader(statusCode int) void
        +BodyBytesSent() int
        +StatusCode() int
        +Close() void
    }

    class Interceptor {
        <<interface>>
        +RequestReferer(c *Context) string
        +Redirect(c *Context, url string, statusCode ...int) bool
    }

    class HandleFunc {
        <<function>>
        +invoke(c *Context) error
    }

    class Middleware {
        <<function>>
        +wrap(next HandleFunc) HandleFunc
    }

    class chain {
        <<interface>>
        +Next(hf HandleFunc) HandleFunc
    }

    class TEntityT {
        +Data T
        +Errors mapstringstring
        +Validate(languages ...string) bool
    }

    App --> Context : creates
    App --> Routing : owns
    App --> ViewEngine : uses
    App --> Viewer : registers handlerViewers
    App --> Interceptor : uses
    App --> Compressor : uses

    Context --> App : backref
    Context --> Routing : backref
    Context --> ResponseWriter : uses
    Context --> Viewer : selects in View
    Context --> MimeType : via Accept

    Routing --> HandleFunc : wraps
    Routing --> chain : uses for middleware
    group ..|> chain : implements

    ViewEngine <|.. StaticViewEngine
    ViewEngine <|.. HtmlViewEngine
    ViewEngine <|.. TextViewEngine

    Viewer <|.. HtmlViewer
    Viewer <|.. JsonViewer
    Viewer <|.. TextViewer
    Viewer <|.. FileViewer

    ResponseWriter <.. Context

    HandleFunc <-- Middleware : wraps

    TEntityT --> Context : used via form binding
Loading

File-Level Changes

Change Details Files
Rewrite README into an AI-executable specification with numbered rules and structured sections.
  • Replaced narrative feature/guide-style README with a specification organized into sections 0–20, focusing on types, behaviors, and contracts rather than marketing or tutorial content.
  • Introduced Critical Rules 0.1–0.7 that define non-obvious, non-negotiable behaviors (e.g., WithHandlerViewers semantics, c.View usage, middleware error handling, Start not starting server, Accept-matching for viewers, pages/* GET-only, {$} semantics).
  • Documented core types (HandleFunc, Middleware, Option, RoutingOption, chain) and clarified the error semantics for handlers and middleware.
README.md
Document App, routing, middleware, Context, viewers, and view engines in a precise, implementation-oriented way.
  • Described App fields, their defaults, and which options override them, including consequences of nil or empty configurations (e.g., handlerViewers, fsys).
  • Explained route registration APIs (Get/Post/etc), group-based middleware chaining, and how chains wrap handlers inside-out.
  • Clarified Context API versus standard library usage, including when to use http.Request/http.ResponseWriter directly and how c.View selects viewers based on Accept headers and names.
README.md
Define behavior of viewers, view engines, project layout, and static asset handling including fingerprinting.
  • Specified the Viewer interface, built-in viewer types, and precise selection/fallback rules when Accept headers and named viewers interact.
  • Explained StaticViewEngine/HtmlViewEngine/TextViewEngine responsibilities, hot-reload behavior under WithWatch, and template dependency handling (layouts, components, pages, views, text).
  • Documented project directory conventions and how filenames and folders map to routes, including dynamic segments, host-based routing, and index/{$} patterns.
  • Described asset fingerprinting via WithBuildAssetURL and the asset template function, including cache-control semantics for fingerprinted paths.
README.md
Codify error handling, compression, redirects, and extension behaviors for use by agents.
  • Defined canonical meanings for handler return values (nil, ErrCancelled, ErrViewNotFound, other errors) and the framework’s resulting HTTP responses, including X-Log-Id on 500s.
  • Documented ResponseWriter extensions (BodyBytesSent, StatusCode, Close), compressor selection via Accept-Encoding, and lifecycle expectations (Close via framework).
  • Specified Redirect and Interceptor behavior, including how htmx integration changes redirect handling and RequestReferer logic.
README.md
Provide explicit guidance for form binding/validation, cookies, ACL, SSE, and other extensions as machine-usable APIs.
  • Summarized key APIs and configuration patterns for extensions (acl, autotls, cache, cookie, csrf, form, hsts, htmx, proxyproto, reqlog, sse), including their middleware usage and main entrypoints.
  • Gave concrete examples for form binding and validation (BindForm/BindQuery/BindJson, TEntity, AddValidator) and cookie signing helpers.
  • Outlined usage patterns and security constraints for features like HSTS, PROXY protocol, ACL rules from config files, SSE event delivery, and logging integration.
README.md
Add migration notes for users familiar with Gin/Echo/Chi and provide minimal end-to-end examples for typical deployments.
  • Enumerated what common helpers from other frameworks do not exist and how to translate them into xun equivalents using standard library calls and c.View/form binding.
  • Contrasted middleware and error-handling patterns versus Gin-style c.Next/Abort, to prevent incorrect porting of code.
  • Added minimal examples for JSON-only APIs, mixed JSON/HTML routes, embed.FS-based deployments, and authenticated route groups with middleware.
  • Clarified Go 1.22 router syntax and how xun uses it, including edge cases with trailing slashes and dynamic segments.
README.md
Remove AGENTS documentation file in favor of a single-source specification in the README.
  • Deleted the separate agents-focused AGENTS document and merged its relevant content into the new README specification, making README the single authoritative source.
  • Updated language in the README to state that all other documentation is derived from this file and it takes precedence.
README.md
AGENTS.md

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@deepsource-io

deepsource-io Bot commented Mar 31, 2026

Copy link
Copy Markdown

DeepSource Code Review

We reviewed changes in fd82e95...b579c2c on this pull request. Below is the summary for the review, and you can see the individual issues we found as inline review comments.

See full review on DeepSource ↗

PR Report Card

Overall Grade   Security  

Reliability  

Complexity  

Hygiene  

Code Review Summary

Analyzer Status Updated (UTC) Details
Go Mar 31, 2026 1:14a.m. Review ↗

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 1 issue

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="README.md" line_range="313" />
<code_context>
+    Handle  HandleFunc
+    chain   chain           // *App or *group
+    Options *RoutingOptions
+    Viewers []Viewer       // viewer's for this route
+}
 ```
</code_context>
<issue_to_address>
**suggestion (typo):** Fix typo in comment: "viewer’s" should be "viewers".

The comment on the `Viewers` field should use the plural "viewers" (e.g., `// viewers for this route`) rather than the possessive "viewer’s" to match the slice.

Suggested implementation:

```
    Viewers []Viewer       // viewers for this route

```

If the incorrect comment (`// viewer's for this route`) appears in multiple code examples or sections of the README, apply the same search/replace to each occurrence to keep the documentation consistent.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread README.md Outdated
cnlangzi and others added 3 commits March 31, 2026 09:08
Before:
  "This is the authoritative specification..."
  → AI may skip as natural language header

After:
  "Status: AUTHORITATIVE / Before writing any xun code, read this..."
  → Clear first-person directive, harder to skip

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@cnlangzi cnlangzi merged commit b6f0fe2 into main Mar 31, 2026
9 checks passed
@cnlangzi cnlangzi deleted the docs/ai branch March 31, 2026 01:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant