Offline tooling
Read a set of keys
Section titled “Read a set of keys”After generating a schema containing the schema-3 built-ins:
import { call, connect, has } from './valence/bridge.g';
await connect();if (has('data.getMany')) { const rows = await call('data.getMany', { bucket: 'plants', keys: ['fern', 'oak', 'fern'], });}The host reads the active bundle’s schema and returns live Row objects in first-requested order, with duplicates removed. Missing keys and tombstones are omitted. Empty keys return an empty list. More than 500 input keys returns E_PARAMS; split larger reads into batches. A batch crosses the bridge once. The test-app emulator measured roughly 15 ms per individual round trip; that is an observation, not a performance guarantee.
Show pending sync operations
Section titled “Show pending sync operations”if (has('sync.status')) { const status = await call('sync.status'); // status.pending includes deletes and repeated edits to the same key. // status.lastSyncedAt is epoch milliseconds, or null before a full success.}This reads local data without starting sync. pending counts operations rather than distinct dirty keys, so counting negative-usn rows is no longer needed. offline describes transport failure on the last attempted sync, and is false before an attempt. It does not claim current connectivity. A busy run leaves the observations alone. Only a successful unscoped run advances the persisted lastSyncedAt; a scoped run can update offline but cannot declare all buckets fresh.
lastSyncedAt: null means “not known”, not “never”. It is null before this host’s first successful sync — including on a device that just migrated from 0.3 with a full database, because no 0.3 host wrote the timestamp. Rendering it as “Never synced” is therefore wrong on exactly the launch where it matters most, under data that is complete and current. Say nothing rather than something false, and let the first sync (usually seconds after launch) fill it in. pending and offline are correct from the first call.
Schema 15 adds nullable reason for the last completed sync attempt. It persists across redraws and cold starts; scoped attempts replace it too, and account switches clear it. See capability and status fields.
For older hosts, or a warning that must survive unrelated successful scopes, persist the rejection yourself, and clear it only on a success you asked for:
// Register before the first route, so a 401 during startup is not missed.on('auth.expired', () => call('prefs.set', { key: 'authRejected', value: '1' }));on('sync.done', ({ result }) => { if (result.reason === 'unauthorized') call('prefs.set', { key: 'authRejected', value: '1' });});
// And clear it only from an explicit, successful retry — not from a background run that happened to// work against a public bucket.async function retry() { const r = await call('sync.now', {}); if (!r.offline && r.reason !== 'unauthorized') await call('prefs.set', { key: 'authRejected', value: null });}sync.done’s SyncResult.reason is the push half of the same information, and it is the one that
carries the outcome — pair it with sync.status() on mount rather than choosing between them. Schema 15 exposes the last completed reason directly; the prefs pattern still serves older hosts and explicit bucket receipts.
sync.now also returns optional nullable pending. Treat absence as unknown when an older host replies. These new fields and methods require updating the schema and regenerating; upgrading the package alone does not add them to an existing app’s IDL. Guard schema-3 methods on older hosts with has().
Seed more than one schema
Section titled “Seed more than one schema”{ "data": { "plants": 2 }, "seedSchemas": { "plants": [1] }}Put { "schema": 1, "rows": [...] } in plants.v1.json and the schema-2 payload in plants.v2.json. Run node valence/valence.mjs seed --from seed. Both pairs land in one database. Legacy plants.json still works. Current data pairs are implicitly declared; seedSchemas adds versions for read-only buckets already in data. Filename and payload versions must match. Duplicate pairs and undeclared versions fail while preserving the old seed. An old pair alone warns that the current pair is missing.
The seed does not mark a pair synced for the OTA data gate. The host still needs the server pull required by the update protocol. Garbage collection follows bundle requirements and never deletes a writable pair.
For launch-time database locks, see Seed import and recovery. Imported rows survive a failed completion marker; retries write only the marker.
Choose a channel and bridge floor
Section titled “Choose a channel and bridge floor”Set "ota": { "base": "https://ota.example.com", "channel": "beta" } before codegen and the host build. Channel names use letters, digits, _ and -; the default is production. Codegen emits valenceOtaChannel and wires it into valenceConfig.channel. The updater reads channels/beta.json. Publish the pointer with pointer --channel beta; bundles themselves remain channel-neutral.
OTA bundles default requires.bridge to the last recorded store schema version. Before any store baseline, they use the current schema. Built-in/store builds use the current schema, and --requires-bridge N overrides either. Newer calls need has() guards; the build warning names them. If users still have a store build older than the newest recorded one, explicitly pin that older bridge version.
Partial handler test doubles
Section titled “Partial handler test doubles”class FakeHandlers with BridgeHandlersDefaults { @override Future<void> appReady() async {}}Every other generated handler throws E_UNSUPPORTED through normal dispatch. Nullable generated constructor fields are optional named parameters. Use these defaults deliberately for tests or partial hosts. Production handlers extend ValenceBuiltins and implement app-specific methods; applying the defaults mixin over that base would replace working runtime delegations.
Mechanical doctor
Section titled “Mechanical doctor”Both CLI entry points run the checks in contracts section 7. Every FAIL includes Fix: and exits nonzero:
| Check | Failure and fix |
|---|---|
| Bridge version | Schema and generated hostBridgeVersion disagree. Run codegen and rebuild the host. |
| Store baseline | Invalid recorded schema or incompatible changes. Restore the committed baseline; do not rebaseline to silence a failure. |
| Local OTA | Signature/files fail, or requires.bridge exceeds the recorded store bridge. Rebuild with --requires-bridge <store-version> and has() guards, or ship the new host first. Historical local manifests are checked too: archive obsolete releases outside dist-ota. |
| Database directory | host.database contains a path or invalid filename. Set the existing file name and regenerate. The row reports <appSupport>/<name> as WARN: installed location and legacy adoption require a device check. Doctor never moves or opens the user’s database. |
| Signing keys in Git | A PEM private-key header appears in tracked or non-ignored files, or the configured key directory resolves inside Git, including through a link. Move keys outside Git, remove exposed files from the index, rotate keys and audit history. Contents are withheld. Ignored files and history are outside the scan; unavailable Git is WARN. |
| Connection origins | web.connect contains invalid HTTP(S) URLs, credentials, whitespace or CSP source syntax. URL paths remain supported. http.origins uses the stricter exact-origin rule and needs codegen plus a store build when changed; browser permission never grants native token access. |
One row passes with a number instead of warning: oldest servable bundle reports the lowest
requires.bridge among the bundles a device can still be served — every local release plus the built-in
bundle. That number is what says whether a
retirement is safe, and it was arithmetic by
hand across baseline.json and dist-ota/manifests/ before. For each retired method the row also
searches every servable bundle’s files — discounting the METHOD_SINCE table codegen writes into all of
them — and either reports that nothing references the name, saying what a text search cannot prove, or
WARNs naming the newest bundle that still does, because a device on that bundle gets E_UNSUPPORTED. The published floor is not subtracted from the
requires.bridge number: a floor binds only a device that has already committed a bundle carrying it, so
subtracting it would report a safer number than the field. It does split the reference count, which is
what makes the warning clearable at all — warning with no floor published, warning with a count while any
referencing bundle is at or above it, and passing with the never-committed-the-floor residue stated once
every referencing bundle is below it. The row WARNs when there is no readable local bundle, and when baseline.json
records a release whose manifest is not in this checkout (dist-ota/ is gitignored, so that is what a
fresh clone or a CI release pipeline looks like). Like every row here it FAILs on an unreadable config or
schema.
Missing baseline or OTA evidence is WARN, so a new project can be diagnosed before its first release. A passing static check cannot prove hand-written host wiring reports the generated bridge version; retain the fresh-install device test.
node valence/valence.mjs doctornode valence/valence.mjs doctor --testsThe vendored CLI checks generated freshness, store baseline, stack-report presence, declared native value, Android desugaring (FAIL until both Gradle lines exist; codegen writes them), the store listing comparison of appId with the Android applicationId (FAIL on a mismatch), built-in signature/files and compatibility, seed coverage and resolved Flutter dependencies. The wizard’s doctor includes these checks plus installation, signing-key presence and attributes checks. Missing resolution evidence is WARN; failed dependency inspection after resolution is FAIL. It reports the temporary device-tested path_provider_android pre-JNI range >=2.2.17 <2.3.0 (resolving 2.2.23) (checked 2026-10-21), rather than claiming that every newer version is broken.
Declare at least two distinct capabilities under nativeValue: offline, notifications, widget, share, haptics, biometric, links (deep links). This is a declaration, so the row still warns that native setup and device evidence need review.
Map app tests in .valence/test-matrix.json:
{ "bridge": ["test/wiring_test.dart"], "integration": ["integration_test/offline_test.dart"]}Stable IDs are bridge, loopback, updater, store-sync, integration; every ID gets a row. Paths are relative to the Flutter host and must name existing test/ or integration_test/ Dart test files. Nothing prunes this file for you, so a mapped test you delete is a FAIL that names the mapping and asks you to remove it — the usual reason it happens is a retirement that made the test deletable in the first place. An empty array says there is no app-owned wiring at that layer and the package suite covers it; that row is WARN, not FAIL. Commit the file. Package invariants belong to the package suite; app mappings point to app wiring and device evidence. A mapping is an evidence pointer, not proof that its assertions cover every contract clause.
--tests executes mapped unit tests. Integration files stay WARN until a separate emulator/device run supplies evidence. Missing or unexecuted checks are WARN, executed failures are FAIL, and any FAIL exits nonzero. A passing doctor cannot establish store compliance or device behavior. Android is tested; iOS remains experimental and untested.
Reading a doctor run that did not finish
Section titled “Reading a doctor run that did not finish”On Windows, the where.exe flutter.bat discovery command uses the same child
budget. A timeout or failed discovery stays FAIL and never starts Flutter; only a
completed lookup with no match reports Flutter unavailable. This prevents a
timed-out lookup from turning an unexecuted check into a harmless missing-SDK warning.
The row names the probe rather than the command it was probing for: it says
where.exe flutter.bat could not establish whether Flutter is installed and sends
you to check PATH for a dead mapped drive or a stale UNC entry, which is what
blocks name resolution. Before that, it borrowed the Flutter row’s own message and
tail, so a PATH fault read as “flutter pub deps –json failed; run flutter pub get”
with where.exe’s output attached as Flutter’s.
Doctor prints running <name> before each check and <status> <name> (<ms> ms) <detail> after it, to
stderr; stdout stays exactly one JSON document, and each row in it ends with its own elapsed
milliseconds. Capture both streams in CI. If your own wrapper kills doctor on a timeout, the completed
checks and the name of the one that was still running are in the stderr capture — a trailing
running <name> with no result after it is the answer to “where did the time go”, and stdout in that
case is empty, because the JSON document is written once at the end.
--tests takes as long as your mapped suites take. Every child command doctor spawns is bounded at
180 seconds by default — one flutter test per mapped layer, flutter pub deps --json, and the Git
private-key scan, which walks every tracked and non-ignored file and so grows with your repository rather
than with your app. Budget the sum of those bounds, not one of them.
node valence/valence.mjs doctor --tests --timeout 600--timeout <seconds> raises or lowers that per-command bound, which is the answer when the default
is wrong for your checkout rather than wrong about your app: the private-key scan is the row that grows
with the repository, and a large, long-lived one can reach 180 seconds while everything is fine. The
value is an integer from 1 to 3600, it applies to each child command rather than to the whole run, and a
timeout row then names the bound you chose. Anything outside that range is refused before the first check
runs, by either entry point — 0 means “no timeout” to Node, which is the silent hang this whole section is about, and the
one-hour ceiling catches a budget typed in milliseconds.
A command killed by its bound is not a failing test, and doctor says which of the two happened:
FAIL §8 bridge flutter test failed for bridge | Fix: correct the mapped test path or failing test, …FAIL §8 bridge flutter test for bridge was killed by its own 180s timeout; no assertion ran, so this says nothing about whether the app is correct | Fix: run "flutter test …" in host.dir yourself; doctor runs one Flutter command at a time and a second concurrent run is the usual cause, or raise the budget with doctor --timeout <seconds>Both are FAIL and both exit nonzero — doctor could not establish what the row claims — but only the first
is a statement about your app. The same distinction applies to flutter pub deps --json and to the
private-key scan, where it matters most: a scan that could not finish must never be read as “no key
found”. If you reach a bound, check that nothing else is running a Flutter command in the same checkout;
doctor itself never runs two at once.
The packaged example combines the schema-3 batch/status demo with the login and secure-storage demo. Both use the generated host capabilities and the same signed built-in bundle.