Ammoura Documentation

Single source of truth for setup, development, and deployment. This page is intentionally detailed so you can move from first run to production without guesswork.

Start Here

Ammoura is a SvelteKit starter template for Cloudflare. Create your own repository with Use this template, then run bun run customize to rename the app, the slug, the dev port, and the Cloudflare resource names in one pass — CUSTOMIZE.md covers the steps a script cannot do.

Start locally with an isolated D1 database, then connect the production Cloudflare resources only when you are ready to deploy.

  1. Create your repository from the template and run the customization pass.
  2. Install the frozen Bun dependency graph.
  3. Apply database migrations locally.
  4. Run the app and verify the setup, login, CMS, and chat surfaces.
  5. Configure OAuth and owner access through the setup flow.
  6. Keep every coverage metric at or above the enforced 95% floor.
  7. Create project-owned Cloudflare bindings before building or deploying remotely.

Quick Start

Bun is the recommended default for this repository. Run the commands below, then open http://localhost:4236.

Package manager: Bun

terminal bun


								
									# Install dependencies
								
							
								
									$
									bun install
								
							
								
									
								
							
								
									# Start development server
								
							
								
									$
									bun run dev
								
							
								
									
								
							
								
									# Apply local D1 migrations
								
							
								
									$
									bun run db:migrate:local
								
							
								
									
								
							
								
									# Build for production
								
							
								
									$
									bun run build
								
							
								
									
								
							
								
									# Type-check and tests
								
							
								
									$
									bun run check
								
							
								
									$
									bun run test
								
							
								
									
								
							
								
									# Coverage report
								
							
								
									$
									bun run test:coverage
								
							
								
									
								
							
								
									# Deploy to Cloudflare Pages
								
							
								
									$
									bun run deploy
								
							

What You Get Out of the Box

Ammoura integrates its main product surfaces as one Cloudflare-native application: identity, content management, AI workflows, administration, analytics, and agent-ready publishing.

Core App Shell

  • Keyboard-first navigation with command palette for fast route switching.
  • Theme system with persistent light and dark preferences.
  • Responsive layout, navigation, footer, and shared metadata components.
  • A columned widget board with pointer, touch, and keyboard dragging — see Drag and Drop.

Account and Admin Flow

  • Setup-first authentication flow for owner configuration.
  • Login, signup, profile, reset, and admin routes are already scaffolded.
  • /admin opens on the stats dashboard. /admin/settings holds the configuration summary, the /reset route switch, and the OAuth authentication keys.
  • Cloudflare D1 and KV are used for setup state and application data.

Content and AI Surfaces

  • Private CMS content types (isPublic: false) return 404 from public list/item routes and stay out of the sitemap; manage them under /admin/cms.
  • Chat exposes only enabled entries from its known model allowlist. Unknown or disabled models are rejected rather than forwarded to a provider.
  • Voice transcripts and replies persist in the same conversation history as text chat.

Contact Abuse Protection

Turnstile is optional only when both keys are absent. Set TURNSTILE_SITE_KEY and TURNSTILE_SECRET_KEY together to enable it; partial configuration fails closed so the browser and server cannot disagree.

Analytics and Operations

  • First-party, cookie-free analytics at /admin — traffic, audience, and growth, with no third-party script.
  • A Cloudflare plan-limit meter that projects whether today's traffic will exhaust your request allowance.
  • Per-admin permission so operators can see stats without owner access.

How To Use the App

Use the app in this order if you want the least confusing first run. That sequence matches how the repo is structured and avoids most setup-related false alarms.

  1. Open /setup first on a fresh environment and configure owner credentials.
  2. Complete /setup before expecting sign-in or AI features to work.
  3. Sign in through /auth/login or create an account through /auth/signup.
  4. Open the command palette with Ctrl/Cmd + K to move between major routes quickly. On a phone, tap the search icon in the navbar or choose "Search & commands" in the menu.
  5. Use /chat for AI interactions, /profile for account settings, and /admin for operator tasks.
  6. Use the theme toggle to verify light, dark, and system-preference presentation.

Common First-Run Checks

  • If auth looks broken, re-check setup lock state and provider credentials first.
  • If chat is missing from navigation, verify AI provider configuration and route access.
  • If admin tools are unavailable, confirm you are signed in as the configured owner.

Where To Extend

  • Modify routes under src/routes when changing page behavior.
  • Use src/lib/components for reusable UI and shell elements.
  • Keep business logic in src/lib/services and shared helpers in src/lib/utils.

UI Kit

Standard elements live in src/lib/ui and import from one place. Every one uses the theme's CSS variables only, works in light and dark, and is usable by keyboard. See them all running, with the code for each, at /components.

import { Button, TextInput, Select, Dialog, Tabs, Table, toast } from '$lib/ui';
  • Actions — Button (four variants, three sizes, link form, loading state), ButtonGroup, Menu, DropdownMenu (checkbox and radio items), Command (a filterable command palette, inline or as a Ctrl+K dialog), Toggle and ToggleGroup.
  • Forms — TextInput, Textarea, Select, Checkbox, RadioGroup, Switch, Slider, Combobox, Calendar, DatePicker, InputOTP, InputGroup, NumberInput, TagInput and FileDrop, all wired the way Field wires them: a real label, the hint and error in aria-describedby.
  • Feedback — Alert, toasts, Badge, Progress, Spinner and Skeleton.
  • Overlays — Dialog and AlertDialog (native <dialog>), Sheet (from any side, so also a drawer), Popover, HoverCard, Tooltip and ContextMenu.
  • Navigation — Tabs, Accordion, Breadcrumbs, Pagination, Menubar, NavigationMenu, Sidebar and Stepper.
  • Layout — Container, Stack, Separator, AspectRatio, ScrollArea, Resizable and Collapsible.
  • Data display — Card, Item, Table, DataTable (search, sort, paging, selection), BarChart, LineChart and DonutChart (plain SVG, each with a hidden data table for screen readers), Stat, Carousel, Timeline, Avatar, AvatarGroup, Kbd, CodeBlock, Prose and EmptyState.

That is every element shadcn/ui ships, and more. None of it needs a dependency beyond Svelte, and none of it is a paid add-on: the kit is MIT-licensed with the rest of the project.

Toasts need one <Toaster />, which the root layout already renders. Raise one from anywhere with toast.success('Saved'); pass 0 as the duration to keep it until it is dismissed.

The catalog is checked: a test fails when a component is added to src/lib/ui, or a widget is registered, without an entry in src/lib/ui/catalog.ts. Full reference: docs/UI_KIT.md.

Modules

Where the UI kit gives you elements, modules give you the blocks every app ends up building. They live in src/lib/modules, are built from $lib/ui, and are shown running, with the accessibility behaviour each one keeps, at /modules.

import { SignInForm, PricingTable, DataGrid, KanbanBoard } from '$lib/modules';
  • Account — sign-in, sign-up, password reset, profile, sessions, two-factor.
  • Settings — appearance, notifications, API keys, webhooks, cookie consent, privacy.
  • Marketing — hero, pricing, comparison, FAQ, testimonials, footer, contact.
  • App shell — app shell, notification center, global search, wizard, error states.
  • Data & teams — data grid, kanban, comments, files, calendar, tree, audit log.
  • Commerce — billing, invoices, checkout, cart, reviews, status page, changelog.

Each module takes its data and copy as props, emits events, and never fetches. All are mobile first from 320px, use CSS variables only, and work by keyboard and screen reader.

Control Room

Ammoura runs a fleet of client sites. Each client site is its own NebulaKit fork. The control room, at /admin/control-room, is for the owner only. It registers those sites, reads their health and package versions over their /api/v1, records releases, and shows which update each site needs.

  • Security releases — applied to every site that has the package.
  • Feature releases — offered. A site owner opts in on their own site.
  • Health — POST /api/cron/site-health checks every site and records the answer. The screen shows seven-day uptime. Call it on a schedule with the CRON_SECRET bearer.
  • Rollout — runs from the CLI, because a Worker has no git. It merges the release, runs the site's tests, and rolls back if they fail.
bun scripts/orchestrator.ts status
bun scripts/orchestrator.ts sync
bun scripts/orchestrator.ts plan --releases releases.json
bun scripts/orchestrator.ts rollout --releases releases.json --test "bun run test"

Site keys are stored encrypted with the ENCRYPTION_KEY secret. Set it in .dev.vars for local work. See docs/CONTROL_ROOM.md for the full reference.

Drag and Drop

<WidgetBoard> takes a layout and a list of columns, and reports a new layout through on:change. It stores nothing itself, so where a layout is saved stays your decision.

<WidgetBoard bind:widgets {columns} on:change={(e) => save(e.detail.widgets)} />

Registering a widget takes three edits and none of them is the board: an entry in src/lib/widgets/manifest.ts, a line in src/lib/widgets/index.ts, and the component itself. The kit ships six standard widgets — stat, clock, checklist, meter, notes and links — all running at /components; delete the ones your app does not use. The two actions underneath the board — use:draggable and use:dropzone — work on any markup, so a sortable list or a nav reorder needs no board at all.

Keyboard control

Every pointer gesture has a keyboard equivalent, announced through a live region. Focus a drag handle, then:

  • Space or Enter — pick the widget up, and put it down again.
  • Arrow up and down — move it within its column.
  • Arrow left and right — move it to the column either side.
  • Escape — cancel, returning it to where it started.

On a touchscreen, hold a handle briefly before dragging — a swipe stays a swipe, so the page still scrolls. Dragging near the top or bottom edge scrolls the page with you.

The rule that will bite you

A widget's stored state must be inert. A value that changes on a timer — a price, a clock, a connection count — goes out through the widget's live event and comes back in through the board's live prop; it must never be written into widget.title, which is persisted. Ignoring this is how a dashboard rewrites its whole layout every thirty seconds and burns a day's storage quota from one open tab.

Full reference, including the reorder contract and the component checklist: docs/WIDGET_BOARD.md.

Working With AI in This Repo

Treat AI as a fast pair programmer, not as a source of truth. It is useful here because the repo already includes app structure, tests, and strong conventions, which gives the assistant real context to work against.

Good Prompts

  • Point the assistant at a concrete file, route, failing test, or command.
  • Ask it to write or update tests first when changing behavior.
  • Ask for narrow fixes instead of broad rewrites unless you want architectural change.

Good Validation Habits

  • Have the assistant explain which route, store, or service controls the behavior.
  • Require executable validation after changes, not only a diff summary.
  • Always finish by running check, tests, and coverage.

What AI Is Best At Here

  • Tracing a route from UI to service layer and identifying the smallest edit surface.
  • Adding tests around setup, auth, chat, or command palette behavior.
  • Summarizing repo conventions such as Cloudflare bindings, migrations, and theme rules.

If you are using an AI coding agent, keep requests concrete: mention the page or failing test, state the desired behavior, and ask for the smallest validating change that solves it.

Core Commands

These scripts are defined in package.json and are the canonical local workflow.

Development

  • bun run dev runs on host 0.0.0.0, port 4236.
  • bun run preview previews the production build on port 4236.
  • bun run check runs Svelte sync plus svelte-check.

Testing

  • bun run test runs Vitest in CI mode.
  • bun run test:watch runs Vitest in watch mode.
  • bun run test:e2e runs Playwright tests.
  • bun run test:all runs unit tests, then E2E tests.

Deploy and Validation

  • bun run deploy builds then deploys .svelte-kit/cloudflare.
  • bun run validate:contrast checks theme contrast.
  • bun run validate:all runs check + test + contrast validation.

Cloudflare Bindings

Ammoura is configured for Cloudflare Pages with these bindings in wrangler.toml:

  • DB as D1 database binding (database name: ammourakit-db).
  • KV as KV namespace for runtime config and flags.
  • BUCKET as R2 bucket binding.
  • Queue producer binding is documented but commented out by default.

Set app secrets in Cloudflare dashboard or Wrangler secrets for production. Avoid committing raw secrets to source control.

Database Migrations

Migrations are ordered SQL files under migrations/ and tracked by D1. Never edit or delete existing migration files once committed to main.

# Apply pending migrations to local D1
bun run db:migrate:local

# Apply pending migrations to remote D1
bun run db:migrate

# List migration status
bun run db:migrate:list

When schema changes are needed, create a new file with the next sequence number (for example, 0012_add_feature_flag.sql) and use ALTER TABLE or new CREATE statements.

Authentication and Setup Flow

Authentication is built into this app on a setup-first workflow — no third-party auth library sits in the request path. The browser receives an unsigned opaque session token (random, worthless without its server-side record — its SHA-256 digest is the lookup key), while the revocable session record, identity, and roles are loaded from D1 on every request. Authentication fails closed if D1 or SESSION_SECRET is unavailable.

You can sign in with email and password, or with GitHub and Discord once those providers are configured. The main routes are /setup, /auth/login, /auth/signup, and /reset.

1. Configure

Set SESSION_SECRET and SETUP_SECRET, then open /setup and submit the bootstrap secret, GitHub OAuth credentials, and admin GitHub username.

2. Lock Setup

After owner/config state exists, only the authenticated owner can change setup or manage authentication keys. GitHub and Discord validate unexpired one-time state in D1, exchange the provider code, then atomically consume that state before changing accounts or sessions. Discord does not bootstrap ownership; it inherits owner status only when linked or matched to the configured GitHub owner account.

3. Reset When Needed

/reset is owner-only. It clears setup-related KV keys, revokes every active D1 session, and clears the browser cookie. The reset route can also be disabled.

Admin Analytics

/admin is the built-in analytics surface: traffic over a 1, 7, 30, or 90-day window, views by route, the most-read CMS items, referrers, countries, an audience breakdown, and user and content growth over time. It is first-party — there is no third-party script, no account, and no API key to provision.

Everything collected is a daily aggregate counter in D1. There are no cookies, no identifiers, and no IP addresses anywhere in the feature. The User-Agent is read to classify the request and then discarded, so only coarse buckets (operating system, browser, device, language, viewport) are ever stored, and country comes from the Cloudflare edge rather than from an IP lookup. Because nothing per-visitor is retained, this needs no consent banner.

Turning It On

  1. Apply migrations 0007 through 0009, plus 0014 for the Top content table, with db:migrate:local (or db:migrate for remote).
  2. Collection starts on the next request. Traffic and audience panels fill in as visits arrive.
  3. Country stays (unknown) in local development — it is supplied by the Cloudflare edge.
  4. Top content appears once a published CMS item is read. It is the only counter whose row count grows with your catalogue rather than with a fixed list, so on a large catalogue watch it — the retention cron is what keeps it in hand.

Granting Access

The owner always sees the dashboard stats. Any other admin needs the can_view_stats flag, which defaults to off so existing admins do not gain access on upgrade. Without it, an admin still lands on /admin but sees no stats:

UPDATE users SET can_view_stats = 1 WHERE email = 'someone@example.com';

The permission is re-read from the database on every request, so revoking it takes effect without waiting for a sign-out.

Retention

The counter tables grow one row per day per dimension unless pruned. Set CRON_SECRET and have any scheduler POST to the retention endpoint; rows older than 400 days are removed.

curl -X POST https://your-app/api/cron/prune-view-stats \
  -H "Authorization: Bearer $CRON_SECRET"

Platform Usage Meter

The same page tracks billable Function invocations — a larger set than page views, since bots, /api/* calls, 404s, and non-GET requests all count against your plan. It projects whether today will exhaust the free 100,000-request daily allowance before the UTC reset.

Treat it as an early warning and a floor, not a bill: the Cloudflare dashboard remains authoritative.

Reading Stats From a Dashboard

An external dashboard can read the same numbers as JSON. The owner issues a stats token under "Dashboard access" on /admin/analytics; it is shown once, and only its hash is stored. The dashboard then sends it as a bearer token:

curl https://your-app/api/stats/summary?window=7 \
  -H "Authorization: Bearer nks_…"

The response is read-only and aggregate-only — exactly what /admin shows. Rotate replaces the token; Revoke cuts the dashboard off on its next read. A site that has never issued one answers 401 to every request.

Connecting Google Analytics

Optional, and off until you turn it on. The owner opens /admin/analytics, pastes either the GA4 Measurement ID (G-ABCD123456) or the whole gtag.js snippet — the ID is read out of it — and saves. A toggle pauses the tag without discarding the ID, and Disconnect removes it entirely.

The tag loads on public pages only. /admin, /api, and /setup are excluded, so your own admin traffic stays out of the numbers, and page views are sent on every client-side navigation rather than by gtag's automatic tracking, which would count only the first page of a visit.

This is additive: the built-in stats keep working, and reports are read in Google's own console. Google Analytics sets cookies and collects per-visitor data, which is a different privacy posture from the built-in counters — review your privacy policy and add a consent banner where your jurisdiction requires one. Only the owner can change the connection.

Testing and Quality Gates

Ammoura follows Test-Driven Development. Write failing tests first, then implementation, then refactor.

# Run all tests
bun run test

# Run tests in watch mode
bun run test:watch

# Check coverage
bun run test:coverage

# Run E2E tests
bun run test:e2e

# Run all tests (unit + E2E)
bun run test:all

Vitest enforces a 95% floor for lines, statements, functions, and branches. A change is not ready when any metric falls below that threshold.

Project Structure

Ammoura/
├── .github/              # Copilot and workflow instructions
├── src/
│   ├── lib/
│   │   ├── components/     # Reusable UI components
│   │   ├── services/       # Business logic
│   │   ├── stores/         # Svelte stores
│   │   ├── types/          # Shared type definitions
│   │   └── utils/          # Helpers
│   ├── routes/             # SvelteKit routes
│   │   ├── api/            # API endpoints
│   │   ├── auth/           # Authentication pages
│   │   ├── chat/           # Chat UI
│   │   ├── setup/          # First-time setup flow
│   │   └── documentation/  # This page
│   ├── app.css            # Global styles & theme
│   └── app.html           # HTML shell and install metadata
├── tests/                  # unit/integration/e2e tests
├── migrations/             # Immutable D1 migration files
├── docs/                   # Extended project docs
└── wrangler.toml           # Cloudflare bindings/config

Deployment to Cloudflare Pages

  1. Push your repository to GitHub.
  2. In Cloudflare dashboard, open Pages and connect the repository.
  3. Use build command bun run build.
  4. Use output directory .svelte-kit/cloudflare.
  5. Add D1, KV, and R2 bindings to the Pages project settings.
  6. Add required environment variables and secrets.
  7. Deploy and verify auth, setup flow, and database connectivity.

The local deploy script already uses wrangler pages deploy .svelte-kit/cloudflare.

Troubleshooting

  • If setup API reports KV unavailable, create KV namespaces and update wrangler.toml binding IDs.
  • If login fails after setup, confirm OAuth callback URL and ensure GitHub credentials are valid.
  • If migrations fail, run bun run db:migrate:list and check migration numbering.
  • If command palette entries are missing, verify AI provider status and authentication state.

Lighthouse Monitoring

/admin/lighthouse shows Lighthouse scores for your own public pages, worst first, with the specific audits that failed underneath each one. Press Run now to audit on demand.

How it measures without a browser

Lighthouse drives a real Chrome. A Cloudflare Worker has no browser, and this project deploys to Pages, which has no Cron Triggers either. So the scores come from Google's PageSpeed Insights API, which runs Lighthouse on Google's infrastructure and returns the report over HTTP — the audit is a fetch.

The catch is that PSI can only reach a public URL. It cannot audit localhost or anything before your first deploy, so site.url has to be real. Until it is, the admin page says so rather than showing an empty table.

Scheduling it

There is no cron in a Pages deployment, so an external scheduler calls the endpoint — a Cron Trigger Worker, a GitHub Actions schedule:, or anything that can POST. It uses the same shared secret as the other background jobs:

curl -X POST https://your-app.example/api/cron/lighthouse \
  -H "Authorization: Bearer $CRON_SECRET"

Daily is plenty — PSI's keyless rate limit will not tolerate much more, and these scores do not move hourly. PAGESPEED_API_KEY is optional and only raises that limit. Full notes in docs/LIGHTHOUSE_MONITORING.md.

Agent Readiness

This site publishes a machine-readable discovery layer so search crawlers and AI agents can find it, read it efficiently, and understand how to interact with it. Everything below is live without per-domain URL configuration. Placeholder Cloudflare bindings still make /api/health return 503 until project-owned D1/KV resources are configured.

  • /robots.txt — crawl rules, explicit entries for AI crawlers (GPTBot, ClaudeBot, PerplexityBot and others), and Content Signals declaring how the content may be used.
  • /sitemap.xml — every public page plus all published CMS content, regenerated on request so newly published items appear immediately.
  • /.well-known/api-catalog — an RFC 9727 catalog of this deployment's APIs.
  • /.well-known/agent-skills/index.json — short guides teaching an agent how to read content and contact the site, each with a SHA-256 digest.
  • /auth.md — how agents authenticate (and what is not offered).
  • /api/health — service health, used as the catalog's status link.

The catalog currently anchors these implemented endpoints: /api/contact-form-submissions, /api/health, /api/cms/types, /api/chat/models, and /api/chat/stream. Their catalog notes distinguish public, Turnstile-gated, and session-authenticated access.

Reading pages as Markdown

Any page can be fetched as Markdown instead of HTML by sending an Accept: text/markdown header. Browsers are unaffected — HTML remains the default. Responses include an x-markdown-tokens estimate so an agent can budget context before reading.

curl -H 'Accept: text/markdown' https://app.ammoura.me/

In-browser tools (WebMCP)

When opened by a WebMCP-capable agent, this site registers tools for searching content, listing pages, reading a page as Markdown, navigating, and switching theme. They are read-and-navigate only and restricted to this site's own origin. The page-reading tool enforces the public sitemap allowlist with browser credentials omitted, so an authenticated visitor cannot expose private/admin pages through WebMCP.

Content usage policy

The shipped default is fully permissive — search=yes, ai-input=yes, ai-train=yes — which matches Ammoura's public open-source content. Change CONTENT_SIGNAL in src/lib/agent-discovery.ts before publishing any proprietary content; every robots.txt group picks the change up automatically.

DNS-based discovery (DNS-AID) is the one piece that must be added by hand, since DNS records live with your provider rather than in this repo. See docs/AGENT_READINESS.md for the exact records and the DNSSEC requirement.

References

Contributing

Use TDD, keep changes small and reviewable, and run tests plus checks before opening a pull request.

  • Write tests before implementation changes.
  • Run bun run check, bun run test, and bun run test:coverage.
  • Prefer Cloudflare-native services and minimal external dependencies.
  • Do not edit past migration files; create a new one instead.

If Ammoura helps your workflow, consider giving the project a star on GitHub!