/** * How far a signed-in device has got with its copy, written on the device's * own `device` row as it syncs (owner, 26 Oct 2026: sync status is the * phone's own device record, a card draws it, no new screen). * * A pass's figures are counted once, on its first page, and carried in its * cursor: `total` the live rows the phone holds at the pass's version, * `pass` the rows its pages carry (tombstones too), `passLive` the live ones * among them, and what the pages so far carried. A later page counts nothing: * what remains is the pass less what was sent. * * The object writes `synced_at`, `sync_version`, `sync_rows_total`, * `sync_rows_done` and `caught_up` (readonly columns: no assistant writes * them; the object's own writes take the engine directly). The phone writes * `sync_bytes`, `stalled_at` and `stalled_why` through `/v1/act`, the things * only it knows. A write is a change every device pulls, so the last page of a pass * that brought nothing but this row itself writes again only when the row * says otherwise, or a quarter of an hour on. */importtype { SILENT_STAMPS } from"./row_witness.ts";importtype { Engine, Outcome } from"./engine.ts";importtype { Store, StoredRow, SyncScope, SyncWindow } from"./store.ts";/** The table a device's own row lives in (the personal package's `device`). */exportconst DEVICE_TABLE = "device";/** * A caught-up device that pulled nothing new has its `synced_at` written again * at most this often (owner, 15 Nov 2026: a minute made every foreground pull * of every app a write; the card's "last synced" may be this old while idle). */exportconst RESTATE_MS = 15 * 60_000;/** One pass's figures, counted on its first page and carried page to page. */exportinterfacePassFigures { total: number; pass: number; passLive: number; sent: number; sentLive: number;/** * Each table the pass carries rows of: `[rows, sent]`, the rows its pages * carry (tombstones too) and how many of them the pages so far carried * (owner, 2 Nov 2026: the deck's counter says "347 of 950 todos arriving" * while a tool's rows come). */ tables: Record<string, [number, number]>;}/** A pass's figures before its first page. */exportfunction startPass(store: Store, q: { since: number; upto: number; scope: SyncScope; windows: SyncWindow[] }): PassFigures {const tables: Record<string, [number, number]> = {};for (const [table, n] of store.passTables(q)) if (n > 0) tables[table] = [n, 0];return { ...store.syncCounts(q), sent: 0, sentLive: 0, tables };}/** The figures once `rows` have been carried. */exportfunction carried(f: PassFigures, rows: StoredRow[]): PassFigures {const tables: Record<string, [number, number]> = { ...f.tables };for (const r of rows) {const [n, sent] = tables[r.table] ?? [0, 0]; tables[r.table] = [Math.max(n, sent + 1), sent + 1]; }return { ...f, sent: f.sent + rows.length, sentLive: f.sentLive + rows.filter((r) => !r.deleted).length, tables };}/** Each table's rows in the pass and how many of them have come once this page has landed, as an answer says them (`SyncAnswer.tables`). */exportfunction tablesOf(f: PassFigures): Record<string, { rows: number; done: number }> {returnObject.fromEntries(Object.entries(f.tables).map(([table, [rows, done]]) => [table, { rows, done }]));}/** Where a pass stands after a page: the rows still ahead, and of the live rows it ends holding, how many it holds. */exportfunction standing(f: PassFigures, more: boolean): { total: number; remaining: number; done: number } {if (!more) return { total: f.total, remaining: 0, done: f.total };const ahead = Math.max(0, f.passLive - f.sentLive);return { total: f.total, remaining: Math.max(0, f.pass - f.sent), done: Math.max(0, f.total - ahead) };}/** Whether `f` is a pass's figures as a cursor carries them. */exportfunction isFigures(f: unknown): f is PassFigures {const whole = (n: unknown): boolean => typeof n === "number" && Number.isInteger(n) && n >= 0;if (!f || typeof f !== "object") returnfalse;const o = f asRecord<string, unknown>;const tables = o.tables asRecord<string, unknown> | undefined;const pair = (p: unknown): boolean => Array.isArray(p) && p.length === 2 && whole(p[0]) && whole(p[1]);return whole(o.total) && whole(o.pass) && whole(o.passLive) && whole(o.sent) && whole(o.sentLive) && !!tables && typeof tables === "object" && Object.values(tables).every(pair);}/** What a phone says of itself on a sync page (`?device_name=&platform=&app_version=`), for the row the object files it under. */exportinterfaceDeviceFacts { name: string; platform: string | null; app_version: string | null;}/** The facts a page's query names; null without a name, which the row needs. */exportfunction factsOf(params: URLSearchParams): DeviceFacts | null {const said = (key: string): string | null => params.get(key)?.trim() || null;const name = said("device_name");return name ? { name, platform: said("platform"), app_version: said("app_version") } : null;}/** * The row a signed-in device is filed under when the object holds none for * its credential's `device_id`: made here, once — every later page finds it * by `ownDevice` — so its sync is written from its first page. Null when the * page named no facts to make it from. */exportfunction fileDevice( deviceId: string, facts: DeviceFacts | null, now: Date, write: (fn: (engine: Engine, version: number, outcome: Outcome) => void) => void,): StoredRow | null {if (!facts) returnnull;let made: StoredRow | null = null; write((engine, version, outcome) => { made = ownDevice(engine.store, deviceId) ?? engine.create(DEVICE_TABLE, { device_id: deviceId, ...facts, approved_at: now.toISOString() }, version, outcome); });return made;}/** * Restate a held row from the facts a device names on `GET /v1/me`, once a * pass: the name, platform and app version it gives now, and `updated_at` moved * to now even when every fact is as held — a device that imports and never * syncs (the Mac) is seen fresh from this alone. A fact the call leaves out * keeps what the row holds. */exportfunction refreshDevice( held: StoredRow, facts: DeviceFacts, write: (fn: (engine: Engine, version: number, outcome: Outcome) => void) => void,): void {// A silent stamp (no change row): every key is on row_witness SILENT_STAMPS.device, which the restore audit leaves out.const patch: DeviceStamp = { name: facts.name };if (facts.platform) patch.platform = facts.platform;if (facts.app_version) patch.app_version = facts.app_version; write((engine, version, outcome) => {const row = engine.store.get(DEVICE_TABLE, held.id);if (!row) return;const next = engine.update(row, patch, version, outcome);// Nothing differed, so the engine wrote nothing: the row is still touched.if (next === row) outcome.changed.push(engine.store.update(row, row.data, row.owner, version)); });}/** Whether `facts` say otherwise than `held` does: a fact the call leaves out keeps what the row holds. */exportfunction restates(held: StoredRow, facts: DeviceFacts): boolean {const d = held.data;return d.name !== facts.name || (facts.platform !== null && d.platform !== facts.platform) || (facts.app_version !== null && d.app_version !== facts.app_version);}/** The live `device` row of `deviceId`: not revoked, the newest approval first. */exportfunction ownDevice(store: Store, deviceId: string): StoredRow | null {const rows = store.list(DEVICE_TABLE, { column: "device_id", equals: deviceId }).filter((r) => !r.data.revoked_at); rows.sort((a, b) => String(b.data.approved_at ?? "").localeCompare(String(a.data.approved_at ?? "")) || a.id.localeCompare(b.id));return rows[0] ?? null;}/** * Write one page's standing on the device's row. `rows` are what the page * carried, `version` the answer's, `more` whether another page follows; the * write runs in `write`'s transaction under its version. Answers whether it wrote. */exportfunction recordPage( held: StoredRow, page: { rows: StoredRow[]; version: number; more: boolean; figures: PassFigures; now: Date }, write: (fn: (engine: Engine, version: number, outcome: Outcome) => void) => void,): boolean {const { total, done } = standing(page.figures, page.more);if (!page.more && !worthWriting(held, page.rows, total, page.now)) returnfalse;// A silent stamp (no change row): every key is on row_witness SILENT_STAMPS.device.const patch: DeviceStamp = { synced_at: page.now.toISOString(), sync_version: page.version, sync_rows_total: total, sync_rows_done: done, caught_up: !page.more, }; write((engine, version, outcome) => {const row = engine.store.get(DEVICE_TABLE, held.id);if (row) engine.update(row, patch, version, outcome); });returntrue;}/** The last page of a pass that carried nothing but this row itself writes only when the row says otherwise, or `RESTATE_MS` on. */function worthWriting(held: StoredRow, rows: StoredRow[], total: number, now: Date): boolean {const ownOnly = rows.every((r) => r.table === DEVICE_TABLE && r.id === held.id);if (!ownOnly) returntrue;const d = held.data;if (d.caught_up !== true || d.sync_rows_total !== total || d.sync_rows_done !== total) returntrue;const at = typeof d.synced_at === "string" ? Date.parse(d.synced_at) : NaN;return !(now.getTime() - at < RESTATE_MS);}/** A patch the object writes on a device row with no change row: only fields on row_witness SILENT_STAMPS.device. */typeDeviceStamp = Partial<Record<(typeof SILENT_STAMPS)["device"][number], unknown>>;