The spec
Valence is an architecture, not a library you link against. The contract between the layers is written down in one file, contracts.md, and that file is normative: when it and any code disagree, the code is wrong.
The pages in these docs restate it in a friendlier order and with more explanation. They are accurate, but contracts.md is where the precise wording is, and it is what the reviewer agent cites.
Which page restates which section
Section titled “Which page restates which section”| Spec section | Page |
|---|---|
| Canonical manifest check order | Bundle format |
§1 Project layout, .gitattributes |
Configuration |
| §2.1 Static host layout, §2.2 the manifest | Bundle format |
| §2.3 Update algorithm, §2.4 activation state machine | Update protocol |
| §3 Loopback server, port, nonce, resume, platform setup | Flutter host guide |
| §4.1 Bridge IDL, §4.3 codegen | Typed bridge guide |
| §4.2 Wire protocol | Bridge protocol |
| §4.4 Secure storage, the bearer token, the account switch | Login and secrets, Signing users in and out |
| §4.11 Image sharing | Sharing an image |
| §5 Data layer: schema, seed, pull, push, co-versioning, sync triggers | Data and sync guide |
| §6 Native value | Flutter host guide |
| §7 Store-policy rules | Store policy guide |
| §8 Test matrix | Below |
Who implements this
Section titled “Who implements this”For a Flutter app, nobody does: it is a package. valence
implements §2, §3, §4.2 and §5, and runs the §8 matrix below as its own test suite. flutter pub add valence, write about twenty lines of main.dart, and read this page to understand the behaviour and to
debug it — not to build it.
ValenceServer The loopback server, the derived port, the nonce, the CSP header, the SPA fallbackValenceUpdater Pointer, manifest, the canonical check order, content-addressed downloads, the trial and rollback state machine, garbage collectionValenceStore The SQLite schema, the seed import, reads and writes per (bucket, schema)ValenceSync Incremental pull, the outbox and push, the sync leaseValenceApp The WebView, the navigation lock, the foreground-only ready timer, log captureconfig.g.dart and bridge.g.dart are generated by valence codegen and import all of it, so the
typed bridge and the keyring come free too. Your own code is main.dart, your bridge methods, the
platform files and the asset declarations — see the host guide.
Writing a host in another runtime
Section titled “Writing a host in another runtime”This spec is the contract, not the Dart code. The bundle format, the manifest, the wire protocol and
the sync protocol are what a host has to satisfy; a host in Kotlin, Swift or anything else that passes §8
is a valid Valence host, and an OTA bundle built by valence bundle works with it unchanged.
It is a real project: the Dart implementation is around 1,500 lines across the five components above,
covering a signature check order, an activation state machine, a content-addressed store, a loopback
server and an incremental sync engine. Beta testers did write complete hosts from contracts.md with no
access to the Valence source, and reported them behaving as written on the first device run — so it is
achievable from this page alone. Just do not plan it as an afternoon, and start from the §8 matrix.
Acceptance criteria
Section titled “Acceptance criteria”This is §8 of the spec: the minimum tests that have to pass before a host is done. Treat a missing row as a missing feature, not a missing test.
Updater. Each of checks 1 to 7 rejects. A pointer.seq below pending drops pending. The rollout gate is deterministic for an install id. The total-size cap stops a download. An update does not become pending until its requires.data pairs are synced — and a bundle requiring a pair the phone lacks becomes pending only after step 7 pulls that pair, and never on an offline phone. A phone holding v1 and v2 of one bucket satisfies a requirement for either. A bundle requiring exactly hostBridgeVersion is accepted, and check 5 compares against that generated constant rather than a second literal.
State machine. A trial that calls ready() commits and raises the floor. A ready() from a current page after a timeout never commits the trial. A timeout counts exactly one failure. A trial that fails once is retried at the next UI start and marked bad on the second failure. The UI start after that serves current, not the bad bundle. An update check while a seq is on trial does not re-pend it. A commit clears a pending holding the committed seq. A crash while serving == trial counts one failure. A newer built-in bundle wins and drops older pending and trial. A built-in bundle that fails its checks promotes nothing, leaves the state untouched, is not added to bad, and with no current is surfaced rather than served. Garbage collection keeps current, previous, pending, trial and the built-in bundle, and leaves writable buckets untouched. A supersede collects the pairs that fell out of previous, and collection skips the pair step while the sync lease is held. No transition runs from a background isolate. The ready timer pauses in the background.
Server. The same port across launches. A bind failure means a new port in the same range, a new nonce, a reload, and never serving from the old port. Rebinding the same port on resume keeps the nonce and the page keeps working. The nonce appears in the entry page only. The CSP header is on the entry page. GET and HEAD only, any other method 405. A path with an empty, . or .. segment is a 400, so //_host/<id> never reaches the fallback. The SPA fallback works. A /_host/ route is matched before the manifest lookup, an unknown id under it is a 404 rather than the entry page, neither a web-supplied path nor a malformed id escapes the host’s directory, and a /_host/ response carries nosniff and default-src 'none'; sandbox, refuses a scriptable Content-Type, and is refused as a main-frame navigation. A corrupt file in the content-addressed store is detected the first time the server serves it. A bundle file is served no-cache with its sha256 as a strong ETag, a matching If-None-Match (weak and * included) is a 304 with no body, and the same path in the next bundle gets a different ETag, so a cached copy can never answer for new code; the entry page stays no-store and carries no ETag. The back gesture goes back through WebView history and closes the app only when there is none left.
Store and sync. A paged pull is atomic per page. Tombstones are honoured. Outbox rows are not clobbered by a pull or by a push echo. A push acknowledgement clears only acknowledged ids. The seed import per (bucket, schema) only moves forward. Writable buckets use schema 1. The sync lease blocks a concurrent sync, is renewed per page, and treats a future timestamp as expired. A lease recorded by another pid, or by an older host with no pid, is taken over rather than waited out, while the current process’s own live lease is still respected. A blocked run reports reason: busy rather than an empty success, a fully completed run reports ok, server/protocol failures report failed, and an unreachable server reports offline with the old offline flag unchanged. sync.status names the holder’s kind and its age while a lease is held, reports both null when it is free or when the lease is one this host would take over, and reports unknown rather than free for a held lease written by a host that records no kind; a refused run logs the holder and its age, and taking and releasing the lease are each a log line, so a lease a torn-down background isolate never released is a missing line rather than an inference.
Native value (§6, on the device). Each item the app ships actually works: a biometric prompt appears rather than throwing no_fragment_activity; a reminder scheduled N seconds out really posts and reports exact or inexact rather than ok; a scheduled window survives a clock change and a reboot; a re-arm does not cancel a notification already on screen; a widget snapshot reaches a placed widget, with the provider resolving under its fully-qualified class name.
Bridge. A missing or wrong nonce gives E_DENIED. An unknown method gives E_UNKNOWN. Bad params give E_PARAMS. A write to a read-only bucket gives E_DENIED. A prefs.* call on a valence. key gives E_DENIED. open.external rejects javascript: and file:. A reply round-trips U+2028 and quotes. An inbound message over MAX_MESSAGE_BYTES of UTF-8 is rejected by @getvalence/bridge before postMessage, with E_TOO_LARGE, rather than killing the WebView — including a multi-byte string under the cap by length and over it by size. An over-cap reply is replaced by E_TOO_LARGE rather than sent, and data.list clamps limit to 500 — so data.list’s after cursor is how a bucket past the clamp is read completely, and data.count reports its size without reading rows.
On a device or emulator, not just in unit tests: the first launch opens the database and paints; a cold start in airplane mode renders the built-in bundle with seed data; a corrupt file in the content-addressed store is detected on first serve and re-downloaded by the next update check; a background sync followed by a bridge call still works; a background-then-resume after ten minutes rebinds the server and the page keeps working; and each §6 native-value item the app ships actually works — a biometric prompt appears rather than throwing no_fragment_activity, and a reminder scheduled N seconds out really posts and reports exact or inexact rather than ok.
That last group is not optional padding. sqflite_common_ffi, the factory flutter test uses, is more permissive than Android’s SQLiteDatabase — it accepts execute for pragmas, which Android rejects — so a fully green unit suite is not evidence that the store opens on a phone. See the data guide. Testing OTA and sync locally covers how to run the device cases without a CDN.
Traps worth knowing before you start
Section titled “Traps worth knowing before you start”Each of these has cost someone a day.
- A random loopback port wipes web storage on every launch, because the origin includes the port. Derive a stable port per install from
appIdandinstallId, and keep it below 30000. - Never serve from a port you failed to bind. Another process may own it. Move to a new random port in the same range — never
bind(port: 0), which hands you an OS ephemeral port. - Swapping the active bundle restarts the server, so close the old one first or it collides with its own socket mid-fallback.
file://breaks ES modules in Android WebView, and service workers in WKWebView need App-Bound Domains, which break script message handlers. Serve from loopback.- iOS reclaims listening sockets while suspended. Rebind the same port on resume, or lazily loaded chunks start 404ing.
- A
JavaScriptChannelis visible to every frame, which is why the navigation lock, the ban on off-origin subframes andframe-src 'none'are mandatory. - SvelteKit’s entry page has an inline boot script, so a plain
default-src 'self'renders a blank app.valence bundlehashes inline scripts into the manifest CSP; the host sends that. - Git on Windows rewrites line endings in the built-in bundle and breaks every signature.
.gitattributeswith-textis mandatory. - sqflite on Android rejects row-returning pragmas through
execute(). UserawQuery. The ffi test factory accepts both, so your tests will not catch it. - sqflite handles are process-wide, not per isolate. Closing the database in a background task breaks the UI isolate. Never close it.
- A pull or a push echo must not overwrite a row with a pending outbox entry, or the user’s edits vanish.
- The update check must stop on
trial, and apendinginbadmust never be promoted, or the two-strike rollback becomes an infinite retry of a broken bundle. - Garbage collection must keep the
pendingandtrialfiles, or a healthy update 404s and gets marked bad. It must also never delete a writable bucket, which no manifest ever lists inrequires.data. - Background launches must not touch the state machine. Only the host widget promotes
pendingtotrial. - Flutter asset directories are not recursive. Declare
assets/valence/builtin/andassets/valence/builtin/files/separately — and runvalence seedandvalence bundle --builtinbefore anyfluttercommand in a fresh checkout, or the asset bundle refuses to build and evenflutter testfails. - A bundle that needs a newer bridge than a shipped host has never reaches that host. Build with
--requires-bridge <old>and guard the new calls withhas()— and note the default is the schema’sversion, so without the flag every release after a schema bump is refused by those hosts too, not just the one that needed it. - The updater must compare
requires.bridgeagainst the generatedhostBridgeVersion. A second literal drifts, and then the host refuses its own built-in bundle with nothing left to serve, on every install, from first launch after a schema bump. - The SPA fallback swallows every host route placed after it. It answers any extensionless path, so an unknown photo id comes back as HTTP 200 with the entry page’s HTML — a blank
<img>and nothing in either log. Reserve/_host/and match it first. - Build so the entry page references assets from the origin root. With
base: './'it asks for./assets/app.js; served as the fallback for/a/bthe WebView resolves that to/a/b/assets/app.js, which has an extension and so is a real 404. Cold start always loads/, so it only appears on a reload or a back gesture onto a nested route. It isbase: '/'in Vite; in SvelteKit it is the setting for relative asset paths, not the deployment subpath. /_host/bytes are not yours, so they must never be a document. That branch serves whatever a camera or a download produced, on the bundle’s origin. Sendnosniffanddefault-src 'none'; sandbox, take theContent-Typefrom an allow-list of non-scriptable types, and keep/_host/out of the main-frame navigation allow-list — a JavaScript channel is per WebView, not per document, so atext/htmlresponse navigated to directly reads the nonce out of the entry page and gets the whole bridge.- Normalise the request path once before choosing a branch, and 400 an empty,
.or..segment, or//_host/<id>falls through to the SPA fallback and returns the entry page with HTTP 200. - Step 7’s pull is a sync, so it takes the sync lease, resumes from the pair’s own
max_usnrather than a hard-coded 0, and is budgeted. Failing to take the lease is stop-and-log, not a failure. - The reply direction needs a cap too. An oversized reply kills the WebView; if that happens while a trial is on screen it spends a strike, and a healthy bundle can be marked bad for ever. Clamp
data.list’slimithost-side — and give it a key cursor, or a bucket past the clamp has no complete read at all, and a truncated list is indistinguishable from a short one. - §2.3 step 7 is a pull, not a check. Ordinary sync only fetches the pairs the active bundle reads, so a bundle requiring a new
(bucket, schema)pair has no other way to get it; a host that only checks parks the update for ever with nothing logged. Track synced pairs as a set per bucket — a bucket-to-schema map lets v1 hide v2 during a bump. - Log every reason the updater stops. A declined update and a failed one look identical: pointer fetched, manifest verified, then silence.
- The Android back gesture closes the app from any sub-screen unless the host wraps its scaffold in
PopScopeand asks the WebView first.onNavigationRequestnever fires forhistory.pushState, so nothing else hints that the page has history. - Bytes do not go through the bridge. Messages are JSON and capped at 256 KB, because Android routes them through Binder and overrunning its buffer kills the WebView uncatchably. Serve files over
/_host/instead. - The §6 native-value items need native setup Valence does not generate.
local_authneedsFlutterFragmentActivity; an on-time reminder needsSCHEDULE_EXACT_ALARM;home_widgetneeds a provider and a registration. All of them fail on a device while the build, the analyzer, the tests anddoctorare green.
Compatibility
Section titled “Compatibility”- The bridge IDL and the manifest
formatnumber are additive only. A field’s meaning never changes; new behaviour gets a new field or a newformat. - A method of your own that nothing calls can be marked
"retired": true: the name and its shape stay, sohas()and every shipped bundle are unchanged, and codegen answers it withE_UNSUPPORTEDinstead of demanding a handler. See retiring a method. - The bundle format and the update protocol are meant to stay stable through beta. The CLI, the generated code and the two packages’ APIs may still change. See what beta means.
Existing APIs in 0.4
Section titled “Existing APIs in 0.4”Your own backend documents http.request (since 4; version 3 provides batch reads and sync status), its generated HttpResponse {status, headers, body}, and the reference REST sync adapter. Regenerate and ship a store build for the new method and compiled http.origins origins; guard calls on older hosts with has(). The host attaches the R1 token, returns redirects without following them, caps request bodies at 64 KiB, decompressed response bodies at compiled http.maxBodyBytes (default 65536, range 1..262144), and headers at 16 KiB, and applies a 20-second deadline (E_TIMEOUT; E_OFFLINE when the OS reports no network interface, E_INTERNAL otherwise, and every size refusal names the observed size and the limit). An authenticated 401 also emits auth.expired once per request. There is no cookie jar unless a store build opts one origin into http.cookieJar, which lets the host complete a cookie-paired CSRF token (the Django and Rails default POST shape) without the page ever seeing a cookie; without it, a session-cookie API is out of scope for this method. Native HTTP is online RPC. Revision-18 REST caching keeps selected responses offline through disposable SQLite overlays; server-managed datasets and queued writes still use the sync protocol. Android is tested; iOS is experimental and untested.
Contracts §4.7 is restated in Safe areas and accessibility: edge-to-edge system insets, Android text zoom and schema-7 appearance snapshots.
Permissions restate §4.9: Permissions.
Signing users in and out documents auth.setToken’s account and discardPending params and auth.account (since 13). Recording a different account id, or signing out with one recorded, clears every writable bucket’s rows, cursor and outbox before the new token is stored, and refuses with E_PENDING while the outbox is not empty. A refresh of the same id, a first id with none recorded, and an app that never passes one all clear nothing. Gate the params on has('auth.account'): they have no since of their own, and an older host rejects them with E_PARAMS.