agentleFS
DonaldMurilloDonaldMurillo/gofastr/.claude/skills/gofastr-host/SKILL.md

gofastr-host

Skill24 starsChanged 2 days agoMITView on GitHub

Auto-loads when working on a *host application* that imports the GoFastr framework (not the framework itself), meaning Go files in repos that import `github.com/DonaldMurillo/gofastr/...`, or a `main.go` calling `framework.NewApp`. Use it before writing app code for anything a framework battery or primitive may already ship: sign-in, sessions and roles; admin pages and audit trails; email, notifications, background jobs and schedules; uploads, images, search, webhooks and caching; CSRF, rate limits and request logs; live debugging and test fixtures; icons, SEO, accessibility and translation; analytics vendors; live updates, multi-replica deploys and WebRTC; desktop apps, OS services and terminal or native UIs; navigation guards; framework upgrades; and running the dev server. Encodes the "don't reinvent: reach for the battery first" rule and the import paths an agent needs.

  • Reads credentials

The file

We split this skill into the rules it gives an agent

7 rules. About 0 are common, 2 are distinctive, and 5 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈2

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 5

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    After a failed build the body carries the build output.

    line 21
  2. Very specific:

    If the project has no AGENTS.md, run gofastr agents init once to generate both the TOC and the .agents/ detail files.

    line 61
  3. Very specific:

    When the task is wiring a hosted analytics or experimentation vendor (PostHog, Statsig, Plausible), do not link their CDN and do not punch …

    line 156
  4. Distinctive:

    Search the project's AGENTS.md for the keyword first.

    line 210
  5. Very specific:

    Search the framework with grep -rn <symbol> $(go env GOMODCACHE)/github.com/DonaldMurillo/gofastr@*.

    line 211
  6. Very specific:

    Run gofastr docs --grep <term> to search the embedded docs, or gofastr docs <topic> to read one.

    line 212
  7. Very specific:

    Use the live /mcp introspection tools (app_routes, app_batteries, etc.) if the app is running locally with …

    line 213

≈ “Common” is an estimate: at least 1 in 5 of the 372,429 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

GoFastr host-app: load this before writing app code

You're in a Go app that uses the GoFastr framework. The framework already ships ~70% of the surface a real app needs. Before writing anything new, read this skill, the project's AGENTS.md, and the matching detail file under .agents/; they exist to keep you from reinventing what's already there.

To run the app while you work, start gofastr dev once in the background and leave it running: it rebuilds on every save and reloads the browser. go run . and a hand-launched binary never reload, because only gofastr dev sets GOFASTR_DEV=1. While the app is building, after a failed build, or after it exits, gofastr dev answers 503 with an X-Gofastr-Dev header naming which. After a failed build the body carries the build output; after an exit, the exit status. It is still running: fix the error and save, and do not start another one.

For UI work, also read and complete the project's DESIGN.md before selecting components, then open .agents/ui.md and run gofastr docs ui-composition-recipes. The app owns product intent and information hierarchy; the framework supplies the structural and visual primitives. Render desktop/mobile in both schemes and revise the three weakest visible decisions before calling the UI complete.

For record, incident, and operational pages, reach first for ui.RecordSummary + ui.MetricBand: one dominant summary, one compact signal band, and actions in the summary's natural-width Actions slot. Do not repeat the same state in a Banner. Keep its description to one or two sentences and its highlight to one decision plus one short condition. Use the compact Aside for owner/presence context, use MetricBandItem.Hint for trends, and move the full narrative or roster later. The component keeps Actions in its lead region so the primary path stays in the first useful phone viewport. The site header is the app's own package (copy it with gofastr generate package siteheader); when the desktop identity is too long for the phone header, give it a shorter phone mark. On wide detail routes, pair related bounded modules such as DetailLists in ui.Grid; do not leave a narrow stacked column beside an accidental empty rail. Reflow the pair to one column on phones. ui.Cluster wraps whole controls by default; use ClusterConfig.NoWrap only for compact chrome that is guaranteed to fit.

A fresh scaffold already mounts the adaptive framework/ui/theme.Default() palette, so ui.ThemeToggle and OS dark preference have complete light/dark tokens. Keep that WithTheme call. If you replace it with an app-owned theme, define every semantic DarkColors value before rendering a toggle. Use ui.Link for visible text links; do not rely on browser-default <a> colors. Links in the app's own header and footer take their look from those packages' owned sheets.

AGENTS.md is a thin TOC of every framework primitive with its trigger phrases. When your task matches a row, open the linked file under .agents/ (e.g. .agents/battery-admin.md) for the full shape / import / don't-reinvent breakdown.

If the project has no AGENTS.md, run gofastr agents init once to generate both the TOC and the .agents/ detail files.

Upgrading the framework: install the target CLI first (an old binary can't know newer migration notes), run gofastr upgrade [--to vX.Y.Z] to see every migration-relevant change between your version and the target (with file:line hits in this app), --apply to run go get / tidy / build / test, then gofastr agents sync to refresh the generated guidance.

Don't reinvent: reach for these first

Task phrasingUse this
audit trail, who-did-what, compliance logapp.WithAuditLog(cfg) (chained *App method)
admin pages, ops dashboard, queue browserbattery/admin
login, signup, session, CSRF, bcrypt, "require admin"battery/auth
passkeys, WebAuthn, "sign in with Face ID / Touch ID", passwordless sign-inauth.NewPasskeyPlugin(auth.PasskeyConfig{RPID: …, Origins: …, OnSuccessURL: …, TwoFactorURL: …}) + auth.NewSQLPasskeyStore; mark ui.Buttons with auth.PasskeyLoginAttrs / PasskeyRegisterAttrs / PasskeyDeleteAttrs and render the csrf-token meta behind auth.CSRF; never hand-roll navigator.credentials calls; gofastr docs auth
send notification, password reset link, fan-out across channelsbattery/notify
background job, scheduled task, retry-on-failurebattery/queue (use DBQueue for real workloads)
send email, SMTP, transactional mailbattery/email
file upload, S3, MinIO, attachmentsbattery/storage + framework.WithFileStorage
image upload wanting thumbnails, srcset, blur placeholderframework.WithImagePipeline(imagefield.MustNew(...)): every schema.Image upload gets renditions + a BlurHash, written to <field>_blurhash / <field>_variants / <field>_placeholder sibling columns you declare. Render with image.BlurHashDataURL + ui.PipelineImage. Per-field variation via WithImagePipelineFor. Never hand-roll resize/encode in an upload handler
full-text searchbattery/search
search the whole site, docs search, search box over every rendered page, search that works in a static exportbattery/sitesearch: search := sitesearch.New(sitesearch.Config{Groups: …}), app.Batteries.Register(search), a results page at site.Register("/search", sitesearch.Screen(search), nil), and ui.CommandPaletteConfig.Search for the palette; gofastr docs site-search
per-visitor data in the browser, IndexedDB, offline list, "save without an account", state that survives reload and syncs across tabscore-ui/localdb (localdb.New(name).Store(…)) for the database and framework/localentity (Define, Form, List, Count) for forms and lists over it; never localStorage by hand; gofastr docs localdb, gofastr docs local-entities, reference examples/team-builder
static site, export to HTML, host on a CDN or GitHub Pagesgofastr export [--base /sub] <dir>; batteries add files through static.Contributor; gofastr docs static-export
gzip, compression without a reverse proxyframework.WithConfig(framework.AppConfig{Compression: true}); off by default because a proxy or CDN usually compresses; read the BREACH note in gofastr docs security first
outbound signed webhooks with retrybattery/webhook
PostHog, Statsig, Plausible, product analytics, A/B test, experiment behind a vendor, ad blocker eating the vendor script, first-party proxybattery/relay + a host-authored bootstrap: gofastr docs analytics-recipes (relay routes, uihost.ScriptHandler + RegisterExternalScript(uihost.ScriptURL(...)), one pageview per gofastr:navigate, {"id":...} endpoint over handler.GetUser)
cache key/value, memoize, "remember for N seconds"battery/cache
UI components, page layout, forms, tables, theming, dark modeframework/ui (~100 components): gofastr docs ui-composition-recipes for page grammar, gofastr docs ui-new-components for the catalog, live demos at /components/<slug> on the docs site (examples/site)
site header, footer, or help/docs page, "marketing chrome", "colophon", top bar with phone menuthe app's own package, copied from the canonical one: gofastr generate package siteheader, sitefooter or docpage (owned .style.css + tests, self-import rewritten; examples/acme-site keeps customised copies). Extend the theme with the package's own Tokens; gofastr gen styles after sheet edits
live/auto-refreshing dashboard, counter, status ("websockets"?)the reactivity ladder (gofastr docs reactivity): passive freshness = data-cui-poll / widget Builder.Poll (no connection, no infra); SSE bus ONLY for presence/collab/sub-second; never WebSockets, never a bespoke EventSource
stale page after mutation, "back button shows old data", bust cached screenui.InvalidateScreens(w, "/orders") on the mutation handler: evicts that pathname (and its query variants) from the requesting tab's screen cache; pair with data-cui-rpc-navigate when the user should land on the fresh screen; gofastr docs runtime-contract for selector rules
behind a reverse proxy or load balancer (client address for limits and stream caps)list the proxy tiers (IPs or CIDRs): uihost.WithTrustedProxies for the island stream cap, ratelimit.Config{TrustForwardedFor: true, TrustedProxies: …} for the limiter; without them every anonymous visitor counts as the proxy; gofastr docs reactivity, gofastr docs rate-limit
multi-replica deploy (sessions, live updates across replicas)framework.WithSecret (or GOFASTR_SECRET env) + framework.WithFanout: fanout without a secret fails at boot by design; gofastr docs scaling
in-browser agent tools, WebMCP, "page tools" for Gemini-in-Chrome, modelContextframework/experimental/webmcp (experimental): Register Tools (name, description, JSON Schema, same-origin endpoint) then Mount(app.Router(), uiHost); execute() runs as the signed-in user (session + CSRF re-enter server-side). Separate from WithMCP* (session auth vs token auth); gofastr docs webmcp
MCP prompt templates, paginated tool/resource lists, push notifications when tools or resources changecore/mcp: RegisterPrompt (+WithPromptGate), RegisterResourceTemplate, cursor pagination on every list method, and notifications/* over the SSE GET stream with resources/subscribe. Gated items stay hidden from lists AND from notifications, filtered per subscriber at delivery; gofastr docs mcp
agent client protocol, editor/harness attaching over stdio, ACPcore/acp: initialize, authenticate, session/new, session/prompt, session/cancel, session/update streaming and session/request_permission. Unimplemented client features (fs, terminal) are declared absent at initialize rather than dropped; gofastr docs acp
plugin needs a host-page permission (camera, microphone, geolocation) and silently breakspluginhost.Manifest.HostRequirements (permissions-policy:<feature>) plus CheckHostRequirements at boot: the default headers deny those features, so the HOST page's getUserMedia fails with a console error nobody sees. The check warns at startup instead; gofastr docs plugin-platform
MCP App widget, the JS running inside a chat host's iframe, ui/initialize, calling a tool from inside a widgetcore/mcp: mcp.WidgetDocument inlines the widget client; hand-written HTML inlines WidgetClientJS() (never link it: the host resolves a <script src> on its own origin). Handshake plus the six widget-to-host requests (tools/call, resources/read, ui/open-link, ui/request-display-mode, ui/message, ui/update-model-context). GoFastr serves the widget side; it is not a chat host; gofastr docs mcp
serve agents from their own process or listener, split MCP traffic off the web appGOFASTR_ROLE=agent (or WithRole(RoleAgent)): serves /mcp, /a2a (with WithA2A) and health, forwarding MCP to the app router so auth and owner scoping are identical to the serve role. No entity CRUD, OpenAPI, docs, admin or well-known discovery, and no workers; gofastr docs scaling
sidebar collapse stored per user in the database, SSR a collapsed sidebar, icon railui.SidebarConfig.Collapse is tri-state like CurrentPath: the zero value keeps localStorage behaviour, SidebarCollapseCollapsed/SidebarCollapseExpanded hand the state to the server and the runtime stops touching localStorage. SidebarAutoHide is a 64px rail that opens on hover and :focus-within, no JavaScript; gofastr docs ui-new-components
plugin declares a CSP tier (wasm) in its manifest and the frame ignores itpluginhost.ClientModule.AssetServer(prefix, specs) builds the asset server from the module, so Manifest.CSP reaches the mount instead of only the response header. NewAssetServer stays for assets belonging to no module; gofastr docs plugin-platform
sign the agent card, A2A signed cards, publish verification keys, JWKSAgentCardConfig.SigningKeys: one JWS per key over the RFC 8785 canonical form of the card, EdDSA for Ed25519 and ES256/ES384/ES512 for EC, plus a public-keys-only JWK Set at /.well-known/jwks.json. Multiple keys mean multiple signatures, which is how rotation works. Requires a pinned BaseURL and refuses to mount without one; gofastr docs agent-ready
author an MCP App widget, the HTML that runs in a chat host's iframemcp.WidgetDocument: assembles the document with the widget client inlined ahead of Script. Body and Script are author content; a Script carrying </script or <!-- is rejected at build time rather than shipping a document the parser truncates; gofastr docs agent-host
verify signed agent traffic, Web Bot Auth, RFC 9421 signatures on inbound requestsWithWebBotAuth(WebBotAuthConfig{Verify: &WebBotAuthVerifyConfig{Require: false}}) (experimental, tracks draft-meunier-webbotauth-httpsig-protocol-02): observe mode annotates and logs without blocking, Require refuses unverified traffic. framework.VerifiedAgent(ctx) gives the identity, nil for the unverified majority - treat nil as "learned nothing", never as hostility; gofastr docs web-bot-auth
expose skills to other agents, A2A task exchange, agent-to-agent tasks, SendMessage / GetTask endpointframework.WithA2A(framework.A2AConfig{Skills: …}) mounts the A2A v1.0 JSON-RPC exchange at /a2a through the app router, so the API's session/bearer auth and owner scoping apply; every entity with MCP tools is a skill for free, and AgentCardConfig{A2AEndpoint: "/a2a", Skills: app.A2ASkills()} advertises it. Skills are invoked by name (message.metadata.skill or a "skill" data part), never inferred from prose; gofastr docs a2a
per-agent rate limit, throttle verified agents by identity instead of IPlimiter.MiddlewareByKey(framework.AgentRateLimitKey(false)) after WithWebBotAuth: a verified agent is its own bucket (keyed by its directory URL, so key rotation does not reset it), everything else is the client IP; gofastr docs web-bot-auth
nav submenu, menu with radio rows (theme or density switch), one menu row addressable from page JSui.MenuItem: Children nests a submenu through the same disclosure machinery (ArrowRight/Left move in and out, Escape closes one level at a time); Radio + Checked render menuitemradio rows that check/uncheck same-group siblings client-side while the server re-render stays authoritative; ID sets the row's id (MenuItem.ExtraAttrs still drops id, the field owns it). A submenu parent is disclosure-only — Children alongside Href, RPC, or Radio panics at render time
porting a Radix-style tab strip, tests pinning data-state, locators that must not match text inside hidden panelsui.TabsConfig: StateAttrs mirrors data-state="active"/"inactive" onto tab buttons after client-side switches, ID wires tab↔panel id/aria-controls, VacateHidden ships hidden panels empty with their content parked in an adjacent data-cui-tabs-stash script and restored by the demand-loaded tabs module (armed with data-cui-prefetch="tabs"). Two caveats worth knowing before you reach for VacateHidden: a hidden panel is genuinely empty until that module loads on the first hover/focus, so a switch driven before load shows an empty panel; and nothing queues — an update targeting a vacated panel is lost permanently, not replayed on re-show, because the live nodes are detached and invisible to any document-scoped write. All three knobs are opt-in; zero values keep the default output
one dialog per row, widget chrome that depends on the entity, per-item confirm dialogdata-cui-ctx on the open trigger (data-cui-open="layout-remove" data-cui-ctx="inv-42") forwards its context on the chrome fetch, the slot reads it via widget.ChromeContext(ctx) in RenderCtx, and the runtime keys its chrome cache by (name, ctx). The context string is opaque to the framework — authorise the entity it names in the slot, against the request context
own transaction plus CRUD writes, events after MY commit, db.WithTx for a hand-opened txdb.WithTxQueue(ctx, tx) instead of bare db.WithTx, then queue.RunAfterCommit() after your Commit succeeds (drop it on rollback — held events die with it). Bare WithTx still works but the framework then polls your live tx to learn its fate (it warns once per process), and inside App.InTx none of this applies — the framework drains for you; gofastr docs hooks-and-transactions
per-user background jobs the erase plane can delete, GDPR erasure reaching the queueset queue.Job.UserID on enqueue; App.EraseUserData deletes matching queue_jobs rows. Rows enqueued before the field existed carry '' and are treated as unowned
structured request log, JSON logs to stdout for containers (log.JSONSink), panic recovery, log MCP debug toolsbattery/log
browser refresh on gofastr dev rebuildauto-wired by framework.NewApp and by uihost on whatever router it mounts on, no host code; a router with no uihost on it calls dev.RegisterLiveReload(router)
see layout boxes, what overflows, why a page scrolls sideways on a phoneunder gofastr dev press Alt+Shift+L: outlines every layout layer, slot, outlet, area, owned-style scope, island and widget with its name, marks scroll boxes and elements past the viewport, and a legend says whether the page scrolls sideways; auto-wired by framework.NewApp and uihost (a router with no uihost: dev.RegisterLayoutLayer(router)); opt out with GOFASTR_DEV_LAYOUT=0; gofastr docs dev-livereload
agent debugging under gofastr devauto-wired by framework.NewApp: /mcp mount + introspection (app_routes, app_config, contracts_list/contracts_explain, …; the framework_docs_* tools need framework.WithMCPTools(mcptools.Register) from framework/docs/mcptools) + under dev the working pair contracts_verify/contracts_fix + control (app_module_enable/disable) + battery/log debug tools; opt out with GOFASTR_DEV_MCP=0; production needs explicit WithMCP/WithMCPIntrospection/WithMCPControl (and framework.WithMCPTools(mcptools.Register))
load .env filesauto-wired by framework.NewApp; do nothing
per-test isolated Postgres DBframework/testkit.NewIsolatedDB(t, adminDSN, migrate)
"does it work without JavaScript", progressive enhancement check, dead # links, forms that need scriptframework/testkit/nojstest: tab, cancel := nojstest.NewTab(t, browserCtx) then problems, err := nojstest.Check(tab, url) per page; reports empty <main>, dead links, forms with no native submit, error statuses; gofastr docs testkit
"how much CSS does this page ship", CSS size budget, stylesheet weight per pageframework/testkit/cssweight: w, err := cssweight.Measure(client, url) then compare w.Gzip() against a cap per page; counts <style> text and linked sheets, errors on non-200 or a redirect; gofastr docs testkit
favicon, app icon, PWA iconsuihost.WithAppIcon(pngBytes): one source image becomes 32/180/192/512 PNGs, /favicon.ico, head links, and the PWA manifest icons; generate placeholder art in code with framework/image.NewGradient (no committed binaries)
SEO: page title/description, Open Graph, Twitter cards, canonical, JSON-LD, sitemap, robotsuihost WithDescription/WithOpenGraph/WithSitemap/WithRobots/WithRobotsMeta + per-screen ScreenSEO/ScreenSchema interfaces; gofastr docs seo. Static export writes sitemap.xml/robots.txt from the same config
accessibility, ADA/WCAG compliance, "aria-label", a11y auditgofastr audit a11y (static guided lint) and gofastr audit a11y --url <base> (axe-core in headless Chrome, both color schemes, pages from /sitemap.xml). Note gofastr build enforces the static lint: fix findings, don't reach for --no-a11y; gofastr docs accessibility
enforce SEO + a11y completeness, "error if a page has no SEO", strict defaults, launch checklist as codeuihost.WithStrict(): boot fails listing every page screen missing title/description, missing site description/icon/sitemap/robots, every chrome link to a path nothing serves (validated after the last route registration, so battery and plugin routes count; a catch-all GET route satisfies it unverified), and (dev only) every screen without a recorded axe scan (framework/testkit/axetest writes .gofastr/axe-coverage.json); every check tunes individually via StrictConfig (enforce/warn/off + ExemptScreens route patterns, zero value = strictest); gofastr docs strict-mode
"is this still idiomatic?", pre-merge check, lint, "did I wire this right", CI quality gategofastr verify: one pipeline over routing, permissions, security, rendering, a11y, architecture, performance, data, entities, testing and AI-slop rules; every finding carries an ID (GOFASTR1002), why it matters, and the fix. gofastr verify <capability> scopes it, --rule <id> --fix applies one rule's mechanical fixes, --changed narrows to this change (fixes included), --json/--sarif for machines. Strict by default; relax in gofastr.settings.yml (contracts:) or per-line with //gofastr:allow(RULE) reason. Adopt on an existing app with --baseline-write. Its vet stage also runs the type-aware analyzers (unbounded bodies, == on secrets, clients without timeouts, …) over the app; --no-vet skips them; gofastr docs contracts
verify flags my strings.HasPrefix on a path, my X-Forwarded-Proto read, or json.NewDecoder(r.Body)GOFASTR1006 / GOFASTR1406 / GOFASTR1407: compare rel == root || strings.HasPrefix(rel, root+"/"), honour only "http"/"https", decode through handler.Bind or handler.DecodeStrict (envelopes, frames and buffered bodies included); gofastr verify --explain <rule>
vet flags a 0644/0755/os.Create write, a fixed /tmp name, == on a token or code, an id minted from time.Now(), or _ = json.Unmarshalworldreadable / fixedtmp / secretcompare / timestampid / discardeddecode: write 0600/0700, use os.MkdirTemp, subtle.ConstantTimeCompare, crypto/rand, check the error; a site that is the shape on purpose carries //gofastr:allow(<analyzer>) why on its line
auth.NewEntityTwoFAStore no longer compiles after upgradingit takes EntityTwoFAStoreConfig{EncryptionKey: <32 random bytes>} and returns an error; plaintext rows from older builds still verify and re-seal on their next write
bilingual or multilingual site, <html lang> per page, "screen reader reads Spanish pages in English", per-language search index, translate the prev/next pagerapp.WithLangFunc(func(path string) string) resolves the document language per route and a screen overrides its own page with ScreenLang() string (app.ScreenLanger, read after Load); uihost.WithLangFunc covers the shells the host builds (404, 405, embed frame); a docs pager is the app's own package (gofastr generate package docpage; examples/acme-site/helpdocs is a customised copy), so its prev/next words are the app's strings; gofastr docs i18n
upgrading the framework version, migration notes between releasesinstall the target CLI first, then gofastr upgrade [--to vX.Y.Z] [--apply]. It shows every migration-relevant change in range with file:line hits in your app; gofastr docs upgrading; finish with gofastr agents sync
customer-facing CLI, "ship a terminal client", stripe/gh-style CLI for my APIgofastr generate cli: standalone stdlib binary, scoped gfsk_ token auth, custom.go extension seam; gofastr docs app-cli
client SDKs, "publish an SDK", downloadable Go/JS/TS client, API docs site for customersgofastr generate sdk (Go module zip + client.js/client.d.ts under gen/sdk/) + sdkdocs.Mount(site, app.Router(), sdkdocs.Config{Registry: app.Registry, Artifacts: os.DirFS("gen/sdk/dist")}) for the hosted docs site + downloads; gofastr docs sdk
route parameters in middleware, guard a dynamic screen, "session gone" page with a real 410 / 404 statushost.RouteMatchMiddleware() puts app.Match on the request (uiapp.MatchFromContext(ctx) → match.Param("id")); answer a guard with host.RenderScreen(w, r, screen, uihost.ScreenResponse{Status: 410}) (full chrome on a load, bare body on a client-side navigation, no-store on both); gofastr docs ui-wiring
in-browser agent tools, WebMCP, navigator.modelContext, tools only on signed-in pageswebmcp.New(webmcp.WithInstructions(text), webmcp.WithObserver(fn)), host.Handle(rt, tool, handler, webmcp.WithHTTPMiddleware(auth)) binds declaration and route in one call, Mount(rt, host, webmcp.WithDocumentScope(pred), webmcp.WithAssetAuthorization(mw), webmcp.WithPrivateAssets()) gates the bridge and manifest like the endpoints; the marker header attributes, the cookie decides; gofastr docs webmcp
script only on some pages, a capability that must not survive a client-side navigationhost.RegisterDocumentScript(src, scope): the tag ships only on in-scope routes and the runtime hard-navigates across the scope edge; gofastr docs ui-wiring
worker that needs wasm or eval (OpenCV, ONNX) without widening the host page's CSPassets.AddBytes(route, contentType, framed, bytes, pluginhost.WithWorkerCSP(pluginhost.WorkerCSP{WASM: true}), pluginhost.WithCache(pluginhost.CachePublicImmutable)): the worker's own response carries the narrow policy, the document's CSP is untouched; gofastr docs plugin-platform
realtime WebSocket state, snapshot plus events, reconnect that cannot resurrect stale statestream.NewStateChannel(source) (per-role snapshots and sequenced events above Hub) with __gofastr.loadModule('ws') → connectWebSocket (reconnect generations) and createSequencedReducer (applies only newer sequences); gofastr docs reactivity
dropdown menu with my own styled trigger buttonui.Menu(ui.MenuConfig{TriggerElement: ui.Button(...), Items: ...}): the caller's element becomes the disclosure controller, no <summary> nesting
reference for authenticated WebMCP plus WebRTC (support console, one-time operator link, peer-to-peer camera)examples/webmcp-remote-assist; go run ./examples/webmcp-remote-assist
video call, screen share, camera, WebRTC, peer to peer, data channel, TURN, STUN, signalingbattery/rtc: app.RegisterPlugin(rtc.New(rtc.Config{Authorize: …})) for signaling rooms with per-peer TURN credentials; browser side __gofastr.loadModule('rtc') → connectRoom (perfect negotiation, reconnect generations); media flows peer to peer or through your TURN relay, never through the Go process; gofastr docs rtc
rtc socket flood, "one user opens dozens of signaling sockets", cap WebRTC connections per userrtc.Config.MaxSocketsPerUser: default 16 concurrent signaling sockets per Join.User across every room; a principal's next socket past the cap displaces their oldest (the replace-on-rejoin posture); callers with no Join.User share one bucket
a2a stream flood, cap concurrent task SSE streams per owner, 429 past the capframework.A2AConfig{MaxStreamSeatsPerOwner, StreamSeatOverflow}: 0 = 16 seats per owner, negative = unlimited; stream.SeatOverflowRefuse (default) answers 429 at connect, SeatOverflowEvictOldest closes that owner's oldest stream; gofastr docs a2a
image decode from untrusted uploads, huge or dribbling source streams pinning memoryimage.Config.MaxSourceBytes (default 64 MiB): DecodeWithConfig stops buffering at the cap and returns image.ErrSourceTooLarge before the MaxPixels guard allocates anything
attach my row to another user's parent (order_items onto someone else's order), belongs_to FK on writebuilt into crud: a create/update whose BelongsTo FK targets an owner/tenant/read-scoped row the caller cannot read answers 404; exempt contexts are owner.AllowCrossOwner, the target's CrossOwnerRead permission, tenant.AllowCrossTenant, and crud.WithServerWrites for host-driven writes
cross-site form guard, Sec-Fetch-Site, refuse a cross-site POST, Fetch Metadatahandler.IsCrossSiteRequest(r) / handler.IsCrossSiteRequestStrict(r) (core/handler): the one shared predicate, Fetch Metadata first with an Origin-host compare fallback; Strict also refuses an opaque Origin: null with no Fetch Metadata (fetch()-only surfaces)
desktop app, native window, menu bar, file dialog, clipboard, run the app in the OS WebViewbattery/desktop (experimental, macOS today): desktop.AppOptions(id) into NewApp, mount the uihost, app.RegisterBattery(desktop.New(desktop.Config{ID, Title, Menu})), d.Run(app) instead of Start; page side __gofastr.desktop.<cap>.<method>(); gofastr desktop run, build, types; test with desktoptest.Run(t, app, d) (fake shell, real Run flow: h.Call, h.ClickMenu, h.Answer); gofastr docs desktop; reference examples/desktop-notes
run as a service, background service, launchd, systemd, Task Scheduler, start at login, keep running after the terminal closes, daemon with a web UIbattery/service (experimental): svc := service.New(service.Config{ID, Name, Port}), then svc.Run(ctx, os.Args[1:], build) from main, where build(rt service.Runtime) calls rt.AppOptions() (app.db + secret in the state dir) and returns the App; the builder runs only in the daemon and the dev run. Users run <app> service install, open, status, logs, uninstall; the UI is on 127.0.0.1:<Port> behind a Host pin, a cross-site refusal and a session cookie open mints. Never build the App in main, never probe the port (ask status); agents use <app> service mcp as a stdio MCP server (never open /mcp past the gate); gofastr docs service; reference examples/gofastr-runs
native UI, terminal UI, TUI, run the app's services with no HTTP server, in-process presentation from another libraryapp.Run(ctx, framework.ServicesHost()) on a goroutine, wait on app.ServicesReady(), then call the App in-process (app.MustCrudHandler(name) or a service built on it) with the user in the context (handler.SetUser); a one-person app calls localapp.Install() first, or owner-scoped calls fail with "owner context required". No http.Server or listener exists, and Run refuses OnReady hooks and interactive setup. The presentation library owns its native or terminal rendering, controls and styling (never GoFastr's private CSS or runtime internals); GoFastr renders none of it, and the app's web screens still compose framework/ui with zero bespoke CSS. A custom framework.Host implements Run(ctx, *Session) and Stop(ctx), and Stop returns once its ctx is done. A WebView that needs GoFastr's HTTP surface uses app.Serve(ln), never app.Router() behind your own server. An App runs once: a second run returns framework.ErrAlreadyStarted, one after Shutdown returns nil and starts nothing, so build a new App to run again. Abort boot by returning an error, never a synchronous Shutdown from an OnStart hook (it waits out its ctx, and with context.Background() never returns); gofastr docs application-hosts
unsaved changes, warn before leaving, checkpoint a draft before Back, block navigation until saved, renderer library, navigation guardApp code stays Go: a web form sets ui.FormConfig{LeaveGuard: "<words>"} and the kit asks before a link, Back, Escape or reload discards its edits. Only a separate presentation library that ships its own runtime script (a WebView renderer checkpointing through its Go behavior) touches the JS seams: await __gofastr.loadModule('navguard'), then __gofastr.guardNavigation(async (nav) => ...) (allow, deny or a promise of either; keep the disposer), and __gofastr.replaceURL(url) to rewrite the current entry's URL without departing. Never wrap _pushURL or _interceptPopstate, and never write app-authored JavaScript for this. WebKit has not accepted the guard yet; test on the engine you ship. gofastr docs runtime-contract

First-party analytics and experiments

When the task is wiring a hosted analytics or experimentation vendor (PostHog, Statsig, Plausible), do not link their CDN and do not punch script-src/connect-src holes into the CSP. The shipped pattern: battery/relay mounts the vendor's SDK and endpoints under one same-origin path with fixed upstreams; your own bootstrap JS is served via uihost.ScriptHandler and registered with RegisterExternalScript(uihost.ScriptURL(...)), so it ships on every full-page render and survives client-side navigation; pageviews ride the runtime's gofastr:navigate event (fire the initial one yourself; never count on gofastr:beforenavigate, it is cancelable and pre-commit); identity comes from a same-origin endpoint over handler.GetUser. gofastr docs analytics-recipes has both vendors wired end to end, plus a featureflag.Store adapter for server-side boolean gates.

Hard rules

  1. Every <form method="POST"> includes auth.CSRFInputFromCtx(ctx). The CSRF middleware rejects unsigned mutations. No exceptions.
  2. _, _ = db.Exec(...) is almost always wrong. The two acceptable cases (best-effort telemetry, search-history logging) require a comment on the call line explaining why failure is tolerable.
  3. Never hand-roll bcrypt / session cookies / the users-table schema. auth.HashPassword, auth.CheckPassword, auth.SessionMiddleware, auth.UserEntityFields() are the contract.
  4. Audit log writes are not best-effort. Failing audit fails the user write; that's the point.
  5. Strict CSP and one styling surface. Host apps ship zero bespoke CSS outside owned style sheets, and zero hand-rolled structural markup. Themes mutate tokens; missing visual or layout treatments are framework component gaps to add upstream. Chrome the kit does not ship (the site header, footer, docs page) is the app's own package with an owned sheet (<name>.style.css + gofastr gen styles): scoped, tokens only. The framework runtime is the only script tag; extra scripts use WithExtraScripts(externalURL).
  6. gofastr dev sets GOFASTR_DEV=1 on the child process; the framework auto-wires browser reload via SSE. Don't write your own livereload. Opt out with GOFASTR_DEV_LIVERELOAD=0.

Project shape

  • main.go builds the App: framework.NewApp(WithDB, WithConfig, …); chained methods like app.WithAuditLog(cfg) come after.
  • entities/ declares EntityConfigs; use Seed + SeedFS instead of hand-rolled seedIfEmpty helpers.
  • screens/ is one screen per page; in-page state changes are island RPCs, not new routes.
  • Migrations: prefer auto-migrate for greenfield schemas; otherwise versioned migrations under migrations/.
  • Tests against Postgres: framework/testkit.NewIsolatedDB(t, adminDSN, migrate) carves a fresh DB per test. Don't t.Skip when the DB is missing; hard-fail.

When in doubt

  1. Search the project's AGENTS.md for the keyword first.
  2. Search the framework with grep -rn <symbol> $(go env GOMODCACHE)/github.com/DonaldMurillo/gofastr@*.
  3. Run gofastr docs --grep <term> to search the embedded docs, or gofastr docs <topic> to read one.
  4. Use the live /mcp introspection tools (app_routes, app_batteries, etc.) if the app is running locally with framework.WithMCPIntrospection(), and framework_docs_search when it also has framework.WithMCPTools(mcptools.Register); generated apps wire both (plus framework.WithMCP()) by default.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.