# Databases and apps

A database is a set of tables that people, bots and cards read and write together. It lives on
people's devices, syncs like messages do, and is end-to-end encrypted. Isolink's apps (Shopping,
Todo, Notes) and the store's apps are databases with screens; every database also opens in
Isolink's own views (List, Table, Board), so nothing is locked in an app.

The design and the parts still to come are in the project's design notes; this page is what's
built.

## How it's kept

Every database is a space (Connect, `spaces.dart`) of the app `isolink.db`. Everything about it is a
record in that space, so it syncs, merges and is carried like any other record:

| Record | What it holds |
| --- | --- |
| `_db` | 1 name, 2 icon, 3 accent, 4 the app that made it, 5 the default role, 6 sync, 7 deleted |
| `_t:<table>` | a table's name, title and order fields |
| `_f:<table>:<id>` | one field. Fields are records of their own, so two Admins adding fields apart keep both |
| `_r:<table>` | field ids retired from a table, never used again |
| `_v:<view>` | a saved view |
| `_roles` | role changes, each with the clock it was made at |
| anything else | a row: its type is its table, its fields the table's fields by id, plus 1000001 who made it, 1000002 when, 1000003 who changed it last |

## Schemas

```json
{
  "name": "Shopping",
  "icon": "shopping_cart",
  "tables": {
    "items": {
      "title": "name",
      "order": "pos",
      "fields": {
        "name": { "type": "text", "max": 80, "required": true },
        "aisle": { "type": "choice", "options": [{ "id": "dairy", "name": "Dairy" }, "other"] },
        "got": { "type": "bool", "default": false },
        "pos": { "type": "order" }
      }
    }
  }
}
```

Field types, and how each is kept:

| Type | Value | Kept as |
| --- | --- | --- |
| `text` | a string (`max`, `lines`) | latest wins |
| `markdown` | a string (`max` bytes) | `doc`: merges by paragraph |
| `number` | a number (`min`, `max`, `decimals`, `unit`) | latest wins, scaled to a whole number |
| `bool` | true or false | latest wins |
| `date` | `2026-11-06` | latest wins |
| `datetime` | ms since 1970, or ISO 8601 | latest wins |
| `choice` | one option's id (`options`: objects or plain strings) | latest wins |
| `tags` | a list of strings (`max`) | a set: adds and removes merge |
| `counter` | a whole number; `down` lets it go down | two counters: everyone's adds count |
| `person` | an account; `many` for a list | latest wins, or a set |
| `link` | an http or https address | latest wins |
| `ref` | a row id of `table`; `many` for a list | latest wins, or a set |
| `place`, `file`, `order`, `json` | `{lat, lng}`, a file, a position, any JSON | latest wins |

Fields get ids when they're made and keep them. A field can be renamed, never retyped, and its
`decimals` are fixed; a removed field's id is retired. A removed option stays, marked `retired`, so
rows holding it still show its name; nothing new can pick it, and listing it again brings it back.
A schema has at most 64 fields a table.

Any field can have a `name` people see (otherwise its key, as words: `dueDate` reads "Due date") and
`hidden: true` for one the app keeps for itself, such as where a note sits on a board: Isolink's own
List, Table and record editor leave it out. A choice whose options all have a `color` (`#RRGGBB`) is
picked from colour swatches.

Every device checks what a received edit changes against the schema as it knows it, as well as the
author's role. Values that don't fit, and tables or fields it hasn't heard of yet, are held like
edits that weren't allowed, and checked again when the schema changes.

## Roles

Admin (the space's group admins), Edit, Add (only the rows you added) and View. Every device checks
every edit it receives against the role its author had at the edit's own clock, and holds back
edits that weren't allowed for 30 days, checking them again when roles change.

## Sync

- **Relays** (the default): local routes first, then relays.
- **Nearby**: never a relay or a carrier, not even sealed. Edits wait in the outbox, marked
  `nearby`, until there's a local path (Bluetooth, Wi-Fi, the same network). The change of Sync
  itself goes every way, so everyone hears it. Who's in the database is sent like a group change.

## Queries

One JSON shape, for the views, bots and the REST API:

```json
{
  "from": "items",
  "where": [["got", "=", false], ["aisle", "in", ["dairy", "bakery"]]],
  "sort": [["pos", "asc"]],
  "limit": 100,
  "fields": ["name", "aisle"]
}
```

`where` is a list (all must match), an object (`{"got": false, "qty": {"gt": 2}}`), or `{"or": [...]}`.
Ops: `=` `!=` `<` `<=` `>` `>=` `in` `has` `contains` `empty` `set` `near`. Values can be
`{"now": "+1d"}`, `{"today": 0}` or `{"me": true}`. Also `search`, `after` (a cursor), `expand`
(refs), `group`, and one of `count`, `sum`, `min`, `max`, `avg`. A query runs on the asking device's
own copy.

## Bots

An Admin adds a bot like a person, with a role. While answering someone who is also in the database,
the bot has `list_databases`, `query_database` and (unless View) `edit_database`. Its copy is kept by
its engine on its relay, so its relay can read what it can. A Nearby database never reaches a bot.

The REST API has `GET /databases`, `POST /databases/{database}/query` and
`POST /databases/{database}/edits` for a bot's token (relay-api.md).

## Cards

A card block of kind `view` (`u` the database, `h` the table, `m` lets people tick) shows a table
live from each phone's own copy. Share › Send to chat sends one. People not in the database see
its title.

## Store apps

How to make one, every component and the `isolink` module are in [apps.md](apps.md); this is the
format in brief.

`apps/<official|community>/<id>/app.json` in the store, published as `.isoapp` in the store's
extras (type `app`):

```json
{
  "id": "habits",
  "name": "Habits",
  "icon": "star",
  "accent": 4294928970,
  "schema": { "tables": { "...": {} } },
  "starter": { "habits": [{ "name": "Read" }] }
}
```

The schema can be in `schema.json` beside it instead. Apps › Browse lists them; Get makes a
database (app `store:<id>`) with the starter rows.

An app can carry its own screens. `"main": "src/app.tsx"` (TSX) or `"src/app.iso"` (`<script>`,
`<template>` and `<style>` blocks, with `iso-` tags) names the entry; the store's checker compiles
it and everything it imports, with the `isolink` language (packages/isolink_js), into the pack's
`js`. Imports are `isolink` or relative files; there's no npm. On a device with the engine the
database opens in those screens; in the browser, or when the code fails to start, it opens in
Isolink's own views. Table, Share and the database picker are always there.

```json
{
  "id": "habits",
  "version": 3,
  "api": 1,
  "main": "src/app.tsx",
  "needs": { "web": ["api.example.com"] }
}
```

`needs` is all a store app reaches beyond its own databases: `web` lists the https hosts `fetch`
and `Image` may reach, `device` may name `camera` (Camera, Scanner), `location` (My location on
Map and PlacePicker) and `microphone` (Recorder), and `system` names what it uses of the phone or
computer (below). Anything else is refused by the checker.

Files in `file` fields are sealed like chat files: the bytes go to every member's devices (over
local routes only for a Nearby database), and the key travels in the row. `Camera`, `Upload`,
`Recorder`, `ImageCrop` and `Sketch` add one and hand its value to the app; `Image`, `Gallery`,
`Video` and `Audio` show one. A member who joins later gets a file from a member in reach when it's
first shown. Up to 25 MB a file.

`secrets` lists keys the person gives the app, such as an API key: `{"key": "openai", "name":
"OpenAI key", "hosts": ["api.openai.com"]}`, its hosts in `web`. The app writes `{secret:openai}`
in a `fetch` header, body or query; Isolink asks for the key the first time, keeps it in the
device's keychain, and fills it in outside the app's code, only for those hosts and with no
redirects. The app's code never sees it, and it never syncs. Keys (the key button) sets or
removes them.

Its words in other languages go in `l10n/<lang>.json` beside app.json (`es`, `fr`, `de`, `pt`,
`zh`, `ar`), English text to its translation. The code writes `t('Got · {n}', { n })`, which
gives the person's language, or the English as written.

An app's own looks: `import s from './app.css'` gives its classes (`class={s.card}`), and
`style={{ background: '#fde68a' }}` sets one element's. `Masonry` (`columns`, `gap`) lays children
in columns; with `onReorder(id, index)` a long press drags one to a new place, and `onHold(id)`
fires when it's let go without moving. `StickyNote` (`color`, `tilt`, `fold`, `pinned`) is a
paper note with a folded corner. `ProgressRing` shows its children in the middle. A plain
`Editor` (`plain`) has no box, for writing on a note. `useDialog().menu(items)` opens a menu of
`{id, label, icon, danger}` and gives the picked id.

`summary` says what's waiting, for the app's tile when it's pinned to You: `{"table": "notes",
"where": [...], "none": "No notes yet", "one": "1 note", "many": "{p0} notes"}`, its words in the
app's `l10n` like the rest. An app's ⋯ menu has Share, Table, what it's allowed and Pin to You.

Shopping, Todo and Notes are in the store too (`apps/official/shopping`, `todo`, `notes`), with the
same schemas as the ones Isolink comes with. Once the store's version comes (the check every six hours), their
databases open in it, so they change with the store and not an app update. Until it comes they open
in the copy Isolink came with, and where the code can't run, in Isolink's own database views. Only Isolink's own store can update them, and Browse doesn't list
them.

### Using the phone or computer

An app declares everything it uses in `needs.system` (designs/app-system-access.md). Each entry is
a name, or `{ "name": …, "optional": true }` for one a feature uses rather than the app as a whole:

```json
"needs": { "system": ["notify", { "name": "calendar.add", "optional": true }] }
```

- **Essential** ones (no `optional`) are asked for once, in one sheet, when the app first opens,
  then the system's own permission. Declined, the app shows what it needs and an Allow button.
- **Optional** ones are asked for the first time the app uses them, from a tap: Isolink's sheet
  ("Plans wants to see your calendar", Allow or Not now), then the system's. Not now makes the
  call fail and `has()` stays true, so the app can offer it again from another tap.
- The system's own sheets (`calendar.add`, `contacts.pick`, `files`, `photos.save`) and `open`
  need no ask: the sheet or the other app is the yes. They, `clipboard.paste` and `lock` only
  work from a tap.
- Installing from Browse shows what the app can use. App › Allowed has a switch for each.
- `has('calendar')` is false when it isn't declared, isn't on this device, or is switched off.

| Name | What it does | Android | iOS | Mac | Windows |
| --- | --- | --- | --- | --- | --- |
| `remind` | Reminders that follow the account and ring on every device, listed in Reminders, with Done and Later | yes | yes | yes | yes |
| `notify` | Notifications on this device only, at most 64 waiting | yes | yes | yes | while Isolink runs |
| `calendar.add` | A new event through the calendar's own sheet | sheet | sheet | saved to the default calendar | .ics opened in Calendar |
| `calendar` | Read events | yes | yes | yes | – |
| `reminders` | An item in Apple's Reminders | – | yes | yes | – |
| `alarms` | An alarm or timer | clock app | notification | notification | notification |
| `contacts.pick` | One contact from the system picker | yes | yes | – | – |
| `files` | Open (up to 4 MB) and save files through the picker | yes | yes | yes | yes |
| `photos.save` | Save a picture to Photos | yes | yes | yes | save dialog |
| `open` | Directions, call, text or email in the person's own apps | yes | yes | yes | yes |
| `clipboard.paste` | Read the clipboard | yes | yes | yes | yes |
| `lock` | Fingerprint, face or passcode | yes | yes | Touch ID | – |
| `share` | Listed when something is shared to Isolink; `useShared()` has it | yes | yes | yes | yes |
| `shortcuts` | Not yet: `has('shortcuts')` is false everywhere | – | – | – | – |

Every app notification and reminder is titled with the app's name, never a person's.

```ts
import { remind, notify, calendar, reminders, alarms, contacts, files, photos, open, clipboard, lock,
         useShared } from 'isolink/system';

await remind.set({ key: item.id, text: 'Buy milk', at, repeat: 'weekly',
                   done: { table: 'tasks', row: item.id, set: { done: true } } });
remind.cancel(item.id); await remind.list();
await notify.schedule({ id: 'tea', title: 'Tea', body: 'Time’s up', at: Date.now() + 180_000 });
const added = await calendar.add({ title, start, end, allDay, place, notes, alert: 15 });
const week = await calendar.list({ from, to });   // [{ id, title, start, end, allDay, place, calendar }]
await reminders.add({ title, due, notes });
await alarms.set({ hour: 7, minute: 0, label: 'Up' }); await alarms.timer({ seconds: 180 });
const person = await contacts.pick();              // { name, phones, emails } or null
const file = await files.open({ types: ['csv'] }); // { name, size, text } or null; as: 'base64'
await files.save({ name: 'export.csv', text }); await photos.save({ name: 'card.png', base64 });
open.directions('Cafe Nero'); open.call(number); open.text(number, body); open.email({ to, subject, body });
const text = await clipboard.paste(); const ok = await lock.check();
const shared = useShared();                         // { text, files: [{ name, size }] } or null
```

`remind`'s `done` is what its Done button changes, in that app's database, under the person's role;
Later rings again in an hour. `repeat` takes `daily`, `weekdays`, `weekly`, `monthly` or a count
such as `m12` (every year) or `d2`.

### Apps Isolink comes with

`app/apps/<id>/` holds apps written like the store's: Timers, Birthdays and Plans. After changing
one, run `dart run tool/default_apps.dart` in `packages/isolink_js`, which builds
`app/assets/apps/<id>.isoapp`; `test/default_apps_test.dart` fails while they're out of date. They
show beside Shopping, Todo and Notes in Apps and open like a store app. Shopping, Todo and Notes are
the store's own apps; Isolink comes with a copy of each, built by the same tool from a store checkout.

### Upgrades

When a database is older than its app (`version`), the first Admin to open it upgrades it, as
ordinary edits that sync like any other:

1. The new schema is merged in. Fields and options are only ever added; one left out stays.
2. A field with `"from": "<old field>"` takes over the old one's values, by fixed rules (anything to text;
   text to a number when it holds one, to yes or no, to a date, to tags at commas, to a choice by
   name or id; one to many and back), and the old field is retired. A value that won't convert is
   left out.
3. An option with `"was": ["old", "ids"]` replaces those options in every row.
4. The code's `migrate` runs, per version in between, on each row:

```ts
export default defineApp({
  screens: { Home },
  migrate: {
    3: (row, table) => (table === 'habits' ? { ...row, goal: row.goal ?? 7 } : row),
  },
});
```

A migration can only write what the schema allows; a value it refuses stays as it was.

### Updates

Store apps update themselves, the way phone apps and theme packs do. Isolink looks at the store
every six hours, right after Isolink itself updates, and when Apps or one of Isolink's own apps
opens (at most every ten minutes), for a newer version of each app this device has a database
for. A newer version is kept, its databases upgrade as they next open, and a toast says it's up
to date. One that asks for something the installed version didn't (a device need, a website, a
key, or any other need) waits for the person's yes: home shows it as an update ready, as it does
a theme pack's, and so does Updates in Apps. Nothing is ever downgraded.

## Cards in the isolink language

A card's `js` (compiled TSX or `.iso`, calling `defineCard`) draws it instead of blocks or a
CardScript `script`; a card has one or the other. Its `init` and `actions` are replayed on every
phone in the same order, with the same `Math.random` and `Date.now`, so everyone reaches the same
state; an action that throws is turned down on the tapping phone and never sent. `View` draws the
state with `useCard()` (`state`, `act`, `me`). Older versions show the card's fallback text.
