Skip to content

feat(usage): sync usage and config between computers with libSQL #1585

Closed

Description

@igorjs

Summary

Keep usage data and configuration in sync between two computers (home and work) with a libSQL synced store. Each machine keeps its own settings, and usage stays separated by account and by machine.

Decisions so far

The owner chose a live libSQL store over exchanging files. The owner wants to scope it down and come back to it later.

Each usage row carries an account and a machine. Limits belong to the account. Two scopes follow:

  • Account scope: cost and context against the limits. Sums the rows from every machine that used the account.
  • Machine scope: live sessions, local telemetry, and the cost of a local agent. One account on one machine.

One machine can host several accounts, so the account and machine split must also work on a single machine.

Configuration syncs too, with a per-machine overlay: shared defaults plus a layer keyed by a machine id. Keys such as update.mode, systemPrompt.enabled, attribution.enabled, hooks.policyGuard.enabled and usage.ui.state are per user or per machine.

Both machines should run the same version. update.mode auto exists, but it falls back to a notice on Homebrew, Windows, pre-release builds, releases under one hour old and unwritable install directories, and it skips hooks, the statusline and CI. The store must refuse a newer schema with a clear message.

What the research found

  • libSQL embedded replicas read locally and forward writes to one remote primary. Local writes need offline: true. Turso Sync (the turso crate) lets both machines write offline and merges with last-push-wins. Both need Turso Cloud or a server you host. Source: https://docs.turso.tech/features/embedded-replicas/introduction and https://docs.turso.tech/sync/usage
  • libsql bundles its own C SQLite fork. A second SQLite in the same binary fails at link time with duplicate sqlite3_* symbols, so rusqlite =0.40.2 would go from five crates (crates/cli, code, common, data, telemetry). The API is async. The research did not confirm the musl and Windows builds or the binary size effect.
  • The turso engine is pre-1.0. The free Turso plan allows 5 GB of storage and 10M rows written per month.
  • The data worth sharing is small: usage_events, tool_invocation_events and a few telemetry tables. Their keys are Anthropic message ids, tool-use ids and session UUIDs, so rows from two machines do not collide. Memory, the code index, gate data and watch.db are rebuildable or machine-specific, so they stay out. usage_watermarks and usage_backfill_files are per-machine cursors and stay local.
  • telemetry_errors keys on a locally assigned sequence and would collide. Rows with AUTOINCREMENT ids (code worktrees, watch work, the account undo log) stay local too.

Risks to settle before building

  • Playbook says "nothing leaves your machine" (docs/guides/05-what-setup-installs.md:58-59, docs/guides/10-telemetry.md:5), and ADR 0025 rejects remote shared data. A sync needs a new ADR and an opt-in that is off by default.
  • Employer usage data on a personal host may break company policy. Check this first.
  • usage_events stores the raw sign-in email as the account key. The docs claim emails never reach the database (docs/internals/04-usage-dashboard.md:470), which is wrong for that table. The per-session fingerprint is token: plus 8 hex digits, 32 bits and unsalted. Use a longer salted id or a display name before data leaves a machine.
  • No machine id exists today.
  • A premise review recommended files first: each machine keeps rusqlite and exchanges append-only rows through a folder or git repo. It argued this meets the goal with no server and no engine swap. The owner chose libSQL, so the plan must justify that choice and handle the link conflict with rusqlite.
  • Schema skew between machines at different versions. The code already refuses a newer schema (crates/data/src/memory.rs:100).
  • Hooks and the statusline must not wait on the network.

Suggested order

  1. Finish account separation (PRs 1577 to 1584).
  2. Add a machine id and a machine column. This has value alone, because it makes the per-machine views correct without any sync.
  3. Write the ADR for opt-in sync and the privacy carve-out.
  4. Run /playbook:plan again to produce the implementation plan. A checkpoint with these decisions exists for the slug sync-usage-database-between-computers.

Out of scope

Memory facts, the code index, the gate database and watch.db.

Activity

  1. added
    enhancement
    design
    later
    on Nov 6, 2026
  2. igorjs commented on Nov 6, 2026

    @igorjs
    MemberAuthor

    Sync usage and config between computers with libSQL (issue 1585)

    Implementation Plan

    Status: Proposed | Date: 2026-11-06 | Issue: #1585

    Background

    The owner uses playbook on a home and a work computer. The machines run different projects and different Claude accounts (personal Max, company Enterprise). Limits belong to the account, and usage belongs to the machine. Today every number stays on the machine that made it, so a view of one account across both machines does not exist. The owner chose libSQL as the shared store, and chose to isolate all database access behind one crate first, so the engine can change later in one place.

    Problem

    1. usage_events and tool_invocation_events carry an account column (crates/telemetry/src/db.rs:20,39). The four telemetry tables (telemetry_requests, telemetry_tools, telemetry_errors, telemetry_metrics, crates/telemetry/src/telemetry_db.rs:16,49,59,70) carry no account. No table carries a machine.
    2. pbtop mixes account scope and machine scope panels with no way to choose (crates/telemetry/src/tui/data.rs:428, crates/telemetry/src/query.rs:300,323,371,639).
    3. usage.db and config.db have no schema version check. memory.db (crates/data/src/memory.rs:166-169) and the code index (crates/code/src/db.rs:546-551) refuse a newer schema version (the code index refuses an older one too), and usage.db and config.db have no check. Two machines on different versions can corrupt a shared store.
    4. Docs say nothing leaves the machine (docs/guides/05-what-setup-installs.md:58-59, docs/guides/10-telemetry.md:5), and ADR 0025:179 rejects remote or shared learning across users.
    5. rusqlite =0.40.2 (bundled) sits in five crates (crates/cli, code, common, data, telemetry), in 49 files (41 in src/, 8 in tests/). WU-0 reports exact call-site counts per crate. There is no shared connection layer. libsql bundles its own SQLite, and two SQLite libraries fail to link in one binary (external reports, rechecked in WU-12). The libsql API is async and the workspace has no async runtime.

    Goals

    1. All SQLite access goes through one crate, so the engine changes in one place.
    2. Every usage and telemetry row carries a machine, and usage rows carry an account. Account scope sums all machines. Machine scope filters to one.
    3. An opt-in sync of usage rows (usage_events) and of a shared configuration snapshot to a libSQL store, with a per-machine overlay. tool_invocation_events and the four telemetry tables carry the machine and stay local in this version.
    4. An older binary refuses a newer schema with a clear message.
    5. Sync is off by default, has an ADR, and sends no paths, repo names or raw emails.

    Non-goals

    1. No sync of memory facts, the code index, the gate databases or watch.db.
    2. No change to hooks or the statusline behavior: they stay local and synchronous.
    3. No new account fingerprint scheme. The account stack (PRs 1577 to 1584) owns it and is a prerequisite.
    4. No hosted service run by this project.

    Approaches considered

    • A. Port every call site to libsql directly. Rejected: every call site changes once, then changes again if the engine changes. The async API and the missing runtime hit hooks and the statusline.
    • B. A separate pbsync helper that uses libsql and shares no code with the shipped crates. Kept as the fallback. It duplicates SQL and needs its own copies of the table code.
    • C. A storage crate first (chosen), then swap the engine inside it. Every crate imports playbook-store in place of rusqlite. The crate is a thin shim that keeps rusqlite's names, so call sites change their use line and little else. The shim re-exports rusqlite, and the code uses parts of rusqlite that libsql cannot copy (&dyn ToSql slices, unchecked_transaction, borrowed statements over async rows). A libsql engine therefore sits behind a cargo feature, and the expected outcome is that it serves only the pbsync helper. playbook adopts it only if WU-0 maps every API item and WU-12 passes the overhead bar.
    • D. Files only (JSONL export and import). The premise review recommended it. The owner chose libSQL, so D is a non-goal. The row format of WU-14 keeps D possible.

    Decision

    Approach C. Segments S0 to S3 move the whole workspace behind playbook-store with no behavior change. A CI guard then fails any rusqlite import outside that crate. Schema safety, machine identity and the pbtop machine scope follow, because they help even if sync never ships.

    An evidence gate (WU-12) comes before any sync code. It proves libsql builds for all five release targets, stays under a size bar, and adds little startup time on the statusline path. Its result decides the engine location. The expected result is pbsync only. A failed bar stops the plan at S8 and returns to this document.

    Scope rule from the owner: limits and cost-versus-limit panels sum all machines of an account. Live sessions, local telemetry and local agent cost show one machine. One machine can host several accounts, so account and machine are separate filters.

    Sync rules: the remote primary key is (machine, local key), so rows from two machines cannot collide. Sync sends no repo, branch, cwd or file path, and never the raw email. The account goes as a salted hash. The salt lives in the remote shared_meta table and each new machine fetches it. A per-account allowlist (sync.accounts, empty by default) decides which accounts sync, so the work account stays local until the owner adds it.

    Architecture

    • crates/store (new, package playbook-store): Connection, Transaction, params!, Row, OpenFlags, Error, the busy-retry helper now in crates/common/src/sqlite.rs:23, and a schema module with the open-time version check copied from crates/data/src/memory.rs:166-169. Two mutually exclusive cargo features: engine-rusqlite (the default) and engine-libsql (arrives in WU-12). Building with both fails with a compile_error!.
    • A deny rule (clippy disallowed-types plus a CI grep) forbids rusqlite outside crates/store.
    • crates/telemetry gains machine.rs and a machine column on six tables (usage_events, tool_invocation_events, telemetry_requests, telemetry_tools, telemetry_errors, telemetry_metrics). Stamping happens beside the account at ingest.rs:78,96.
    • pbtop (crates/telemetry/src/tui) gets MachineSel beside AccountSel (tui/account.rs, on the account stack). The worker query tuple carries it (tui/worker.rs:63). data::load filters machine panels, and account panels read all rows.
    • crates/sync (new) builds the pbsync binary on playbook-store with default-features = false, features = ["engine-libsql"]. A CI step runs cargo tree -p pbsync and fails when rusqlite appears. The cli passes it the list of shareable config keys as a file, so pbsync imports nothing from crates/cli.
    • Config sync: only keys named in an explicit SHARED_KEYS allowlist in code sync as a shared snapshot. A key not in the list stays local, so a new key never leaks by default. Paths and machine-bound keys (docs.anydocPath, launcher.shortName, watch.allowedAuthors, usage.ui.state) are not in the list. A pull writes a proposal. playbook sync config apply accepts it after showing the diff.
    • Release builds compile playbook and pbsync in separate cargo invocations, so cargo feature unification never links both engines into one binary.

    Files to Create/Modify

    File Action Purpose
    Cargo.toml (root members and [workspace.lints.clippy]) modify add crates/store, crates/sync, enable disallowed_types
    crates/store/** create storage shim, schema check, later libsql engine
    crates/common, data, telemetry, code, cli (Cargo.toml and every rusqlite use) modify import playbook-store
    crates/telemetry/src/machine.rs, db.rs, telemetry_db.rs, ingest.rs, run.rs, command.rs, entry.rs create/modify machine id, column, stamp, commands
    crates/telemetry/src/tui/machine.rs, app.rs, keys.rs, worker.rs, data.rs, view.rs, crates/telemetry/src/query.rs create/modify machine selector and scope filters
    crates/cli/src/config/store.rs, keys.rs, crates/cli/src/doctor/check.rs modify schema version, sync keys, doctor rows
    crates/cli/src/sync/** create playbook sync commands
    crates/sync/** create pbsync helper
    clippy.toml create disallowed-types list for rusqlite
    .github/workflows/release.yml, rust-ci.yml modify guard, targets, size bar, packaging
    docs/adr/0061-opt-in-usage-sync.md create the decision record
    docs/guides/05-what-setup-installs.md, 10-telemetry.md, docs/internals/04-usage-dashboard.md, docs/reference/config-keys.md, docs/reference/cli-and-config.md, docs/guides/17-sync.md modify/create wording and guide

    Segments (suggested PRs)

    Seg Title Work Units Requires Concern Est. lines
    S0 Store crate, common and data WU-0, WU-1 none storage shim ~450
    S1 Telemetry on the store WU-2 S0 port one crate ~350
    S2 Code index on the store WU-3 S1 port one crate ~300
    S3 CLI on the store, plus guard WU-4, WU-5 S2 port and enforce ~700
    S4 Schema safety and retry policy WU-6, WU-21 S3 open-time checks ~350
    S5 Machine identity WU-7, WU-8 S4 schema and ingest ~350
    S6 Machine scope in pbtop WU-9, WU-10, WU-22 S5 read side ~700
    S7 Decision and wording WU-11 none ADR and docs ~300
    S8 Evidence gate WU-12 S3, S7 libsql proof ~450
    S9 Sync core WU-13, WU-14, WU-15 S5, S6, S8 remote, push, pull ~900
    S10 Config sync WU-16 S9 shared snapshot ~350
    S11 CLI and doctor WU-17, WU-18 S9 user surface ~450
    S12 Packaging and e2e WU-19, WU-20 S10, S11 release and tests ~450

    S3 is over 500 because the cli crate holds the most call sites. /playbook:implement may split it by module. S6 is over 500 because the views and the selector share the same panels. S9 is over 500 for three units that only make sense together, and /playbook:implement may split it. The ports in S1 to S3 run in order because each one changes Cargo.lock.

    Deliverables (Work Units)

    WU Title Files Requires Segment Parallel group Done When
    WU-0 Store crate shim crates/store/**, root Cargo.toml none S0 none the shim wraps rusqlite with its names, call sites counted exactly in a report, with both busy-retry helpers kept as named store helpers
    WU-1 Port common and data crates/common/, crates/data/ WU-0 S0 none both crates import the store only, tests unchanged and green
    WU-2 Port telemetry crates/telemetry/** WU-1 S1 none no rusqlite import remains in telemetry
    WU-3 Port code index crates/code/** WU-2 S2 none no rusqlite import remains in code
    WU-4 Port cli crates/cli/** WU-3 S3 none no rusqlite import remains in cli
    WU-5 Guard clippy.toml (new), root Cargo.toml lints, rust-ci.yml, docs/internals WU-4 S3 none CI fails on any rusqlite import outside the store
    WU-6 Schema version on open crates/store/src/schema.rs, telemetry db.rs, cli config/store.rs, doctor/check.rs WU-4, WU-5 S4 none a newer schema is refused with named versions
    WU-21 Unify the busy-retry policy crates/store, crates/telemetry/src/db.rs, crates/common/src/sqlite.rs WU-5, WU-6 S4 none one policy, statusline and ingest tests pass
    WU-7 Machine id and name crates/telemetry/src/machine.rs, lib.rs, command.rs, entry.rs none S5 none playbook usage machine prints a stable id and name
    WU-8 Machine column, stamp, backfill telemetry db.rs, telemetry_db.rs, ingest.rs, run.rs WU-6, WU-7 S5 none six tables carry machine, backfill runs once
    WU-9 Machine selector in pbtop tui/machine.rs, app.rs, keys.rs, worker.rs, view.rs WU-8 S6 none x cycles this machine, one machine, all machines
    WU-10 Scope-correct panels tui/data.rs, query.rs WU-9 S6 none account panels sum machines, machine panels filter
    WU-11 ADR 0061 and wording docs/adr/0061-*.md, docs/guides/05, 10, internals/04 none S7 none ADR accepted, docs describe the opt-in
    WU-12 libsql engine and evidence gate crates/store (feature), crates/sync skeleton, rust-ci.yml, docs/internals/sync-evidence.md WU-5, WU-11 S8 none bars below met on all five targets, engine location decided
    WU-13 Remote schema and client crates/sync/src/remote.rs, schema.rs WU-8, WU-12 S9 none schema created, salt shared, idempotent
    WU-14 Push crates/sync/src/push.rs WU-8, WU-13 S9 none push twice writes 0 new rows
    WU-22 Remote copies, views and alias table crates/telemetry/src/db.rs, query.rs, tui/data.rs WU-8, WU-10 S6 none views return one row per event and pbtop reads them
    WU-15 Pull crates/sync/src/pull.rs WU-14, WU-22 S9 none two simulated machines converge
    WU-16 Shared config snapshot crates/sync/src/config.rs WU-15 S10 none proposal written, never auto-applied
    WU-17 playbook sync commands and keys crates/cli/src/sync/**, config/keys.rs WU-15 S11 none enable, disable, status, now work
    WU-18 Doctor and status rows doctor/check.rs, usage status WU-17 S11 none doctor shows sync state with a fix command
    WU-19 Package pbsync release.yml, install and update code WU-16, WU-18 S12 none release carries the helper, size gate enforced
    WU-20 Two-machine e2e and docs crates/sync/tests/**, docs/guides/17-sync.md, config-keys.md, cli-and-config.md WU-19 S12 none e2e green, docs cover every command

    Parallel Groups

    • None. The ports share Cargo.lock and most later units edit the same few files, so every unit runs in order of its Requires column.

    Per-Work-Unit Detail

    WU-0: Store crate shim

    • Requires: nothing
    • Files: crates/store/Cargo.toml, src/lib.rs (new), scripts/check-port-diff.sh (new), root Cargo.toml (members only; each crate keeps its own pin, for example crates/data/Cargo.toml:18)
    • Changes: a thin crate over rusqlite =0.40.2 that keeps its names (Connection, Transaction, params!, Row, OpenFlags, Error, ErrorCode). Move the busy-retry helper from crates/common/src/sqlite.rs:23 (retries DatabaseBusy and DatabaseLocked) and the telemetry copy at crates/telemetry/src/db.rs:58-76 (retries DatabaseBusy only) into the store as two named helpers. WU-21 merges them later, because the merge changes behavior. Publish a report with the exact call-site count per crate and a table of every rusqlite API item the code uses (OptionalExtension, &dyn ToSql slices, Transaction::new_unchecked and unchecked_transaction, transaction_with_behavior, pragma_update, execute_batch, busy_timeout, types::ValueRef, prepare, FTS5 MATCH) with its libsql equivalent or none. Add scripts/check-port-diff.sh: over git diff -U0 it fails when a changed line is outside use lines and type paths, or when a test file changes any line other than a use or dependency line. Carry publish = false and [lints] workspace = true. rusqlite is an optional dependency enabled only by the engine-rusqlite feature, and crates/store/src/lib.rs carries the one #![allow(clippy::disallowed_types)].
    • Test scenarios (red first, characterization tests on real temp files): SQLITE_BUSY maps to the busy error only after the retry budget and succeeds when the lock clears inside it (two connections on one file; the test releases the lock at a fixed step and the sleep is injected). A write on a read-only open returns the read-only code. A seeded FTS5 MATCH returns exact ids in order. A dropped transaction rolls back. A golden file holds the SQL text and PRAGMA values captured on main for the open functions. A temp git repo fixture runs scripts/check-port-diff.sh: it fails on a non-import change, fails on a test-file change outside use lines, and passes on an import-only change. Each test uses its own temp folder (test name plus process id).
    • Done When:
      • The shim compiles, the characterization tests and golden file pass, the API table and exact counts are committed, and the diff script has a fixture test.

    WU-1: Port common and data

    • Requires: WU-0
    • Files: crates/common/Cargo.toml and sqlite.rs, crates/data/Cargo.toml, memory.rs, config.rs, migrate.rs
    • Changes: replace use rusqlite:: with use playbook_store::. No behavior change.
    • Test scenarios: the existing tests pass unchanged, the WU-0 characterization tests and golden file pass, and scripts/check-port-diff.sh passes on the PR.
    • Done When:
      • No rusqlite import remains in the two crates.

    WU-2, WU-3, WU-4: Port telemetry, code index and cli

    • Requires: WU-1 (WU-2), WU-2 (WU-3), WU-3 (WU-4)
    • Files: each crate's Cargo.toml and every file that names rusqlite (open functions: telemetry db.rs:88, code db.rs:367,623,738, cli config/store.rs:94, gate/db.rs:173, watch/store.rs:127, state/mod.rs:44)
    • Changes: the same mechanical replacement as WU-1. Keep each PR to one crate.
    • Test scenarios: existing suites pass with test files changing only use lines, the golden file still matches, and scripts/check-port-diff.sh passes. Snapshot and CLI tests are unchanged.
    • Done When:
      • Each crate imports the store only.

    WU-5: Guard

    • Requires: WU-4
    • Files: clippy.toml (new, disallowed-types), root Cargo.toml [workspace.lints.clippy] (line 16), .github/workflows/rust-ci.yml, docs/internals note
    • Changes: forbid rusqlite types outside crates/store with disallowed-types, and add a script as a second check that also scans tests/ directories and Cargo.toml dependency lines. Integration tests use the store as a dev-dependency. The WU-12 and WU-15 tests that need a rusqlite writer or a telemetry reader live in crates/telemetry/tests/ and run the built pbsync binary as a subprocess, read from a PBSYNC_BIN variable. CI builds pbsync and exports PBSYNC_BIN first, as the pbdoc step does (rust-ci.yml:305-318), because cargo builds a binary only for its own crate's tests. They never link playbook-sync, so no crate links both engines and crates/sync keeps no edge to rusqlite or telemetry.
    • Test scenarios: a nextest test builds a temp tree and runs the script over it: a stray use rusqlite::, a fully qualified rusqlite::Connection with no use, a Cargo.toml dependency line, and a clean crates/store file that must pass. A second test reads clippy.toml and asserts that it lists the rusqlite types. No violating file is committed.
    • Done When:
      • CI fails on a stray import and passes on main.

    WU-6: Schema version on open

    • Requires: WU-4, WU-5
    • Files: crates/store/src/schema.rs, crates/telemetry/src/db.rs, crates/cli/src/config/store.rs, crates/cli/src/doctor/check.rs
    • Changes: a schema_version row in meta. A stored version above ours returns an error that names both versions and the update command. Copy the message shape of crates/data/src/memory.rs:166-169. Follow ADR 0016 for migrations.
    • Test scenarios: a database stamped one version higher is refused and nothing is written. An equal or older version opens and upgrades. An absent schema_version on a fresh database stamps it. A non-integer value returns a named error with no writes.
    • Done When:
      • playbook doctor shows a store schema row.

    WU-21: Unify the busy-retry policy

    • Requires: WU-5, WU-6
    • Files: crates/store/src/lib.rs, crates/telemetry/src/db.rs (:58-76), crates/common/src/sqlite.rs (:23-33)
    • Changes: do not depend on tests/usage_boundary.rs, which crates/common/src/sqlite.rs:12 cites and main does not contain. The two helpers retry different errors today (DatabaseBusy and DatabaseLocked against DatabaseBusy only). Keep the superset policy (retry on DatabaseBusy and DatabaseLocked), change the telemetry caller to it, and state the change in the PR because it changes behavior on the ingest and statusline paths.
    • Test scenarios (red first): exhaustion returns the busy error once the budget duration elapses (fake clock; the helper takes a Duration budget, crates/common/src/sqlite.rs:23-26). A non-retryable error fails at once. DatabaseLocked retries on both paths. The ingest and statusline suites pass.
    • Done When:
      • One helper with the superset policy remains, and the three scenarios above pass.

    WU-7: Machine id and name

    • Requires: nothing in this plan. Precondition checked by /playbook:implement: the account stack (PRs 1577 to 1584) is merged and released, so playbook usage account list exists.
    • Files: crates/telemetry/src/machine.rs (new), lib.rs, command.rs, entry.rs
    • Changes: generate a UUIDv4 once (the generator is a parameter; the unit adds the uuid and hostname crates with exact pins after the repo's dependency vetting) and store it in the data folder (machine.json, owner-only permissions) with the hostname at creation. An editable display name defaults to the hostname and never leaves the machine. playbook usage machine [--name NAME] prints id and name.
    • Test scenarios (red first): two reads return the same id. A fixed generator yields the expected id shape. A corrupt file gives a clear error without overwriting. --name persists and the id stays. A stored creation hostname that differs from the injected current hostname is reported by a function that WU-17 calls at sync enable. The file mode is 0600 (unix only).
    • Done When:
      • The id survives restarts and does not derive from a path or hostname.

    WU-8: Machine column, stamp and backfill

    • Requires: WU-6, WU-7
    • Files: crates/telemetry/src/db.rs (open_db :88, upsert_usage_event :214, insert_tool_event :324), telemetry_db.rs (:221,253,271,293), writer.rs (:143-153, the live insert path of the four telemetry tables), ingest.rs (:78,96), run.rs (:89-90)
    • Changes: ensure_machine_column on the six tables. Local primary keys stay as they are, because ALTER TABLE ADD COLUMN cannot change a key. The unit bumps the usage.db schema_version by one, so an older binary refuses the changed database. Ingest and the live writer stamp the local id. A one-time backfill sets the local id on rows with an empty machine, in batches of BACKFILL_BATCH_ROWS (5,000) so it never holds one long write against hooks and the statusline. The upsert keeps the larger output_tokens as today. The four telemetry tables get no account column: their panels are machine scope.
    • Test scenarios (red first): an old database gains the column and local rows get the id. A re-ingest adds no duplicates. The larger output tokens still win. Running the backfill twice writes 0 rows the second time and changes no machine value. Table cases at 0, 1, 5,000 and 5,001 rows per PR, and 200,000 rows in the nightly job. A row inserted through ingest.rs and through the live writer, for each of the six tables, after the column exists carries the local machine id, and a query by machine returns it. The backfill takes a between-batch callback: the test writes a row from the callback and asserts it commits after batch N, with no sleeps. A backfill killed mid-batch resumes and ends with no duplicate stamps.
    • Done When:
      • All six tables carry machine and the backfill runs once.

    WU-9: Machine selector in pbtop

    • Requires: WU-8. Precondition: the account stack is merged and released, because AccountSel exists only on its branch.
    • Files: crates/telemetry/src/tui/machine.rs (new), app.rs, keys.rs, worker.rs, view.rs
    • Changes: MachineSel {This, Key, All} beside AccountSel. The key x cycles it. The other letters near it are taken: m and M select the month ranges (keys.rs:301,311), and a is the account selector. x is unbound in keys.rs; the unit re-checks before use. The worker tuple carries it. The title shows the machine name. The choice saves in usage.ui.state.
    • Test scenarios (red first): snapshot tests of title and help for each choice. With one machine only, x shows a single entry. The choice persists and a reopen restores it. A corrupt saved state falls back to This. The machine name appears in the title text. Pressing x cycles This, Key, All, This.
    • Done When:
      • The selector works and survives a restart.

    WU-10: Scope-correct panels

    • Requires: WU-9
    • Files: crates/telemetry/src/tui/data.rs (:428,439,446), query.rs (:300,323,371,627,639)
    • Changes: Budget, Projection, Burnup, Spend, Tokens and Models read all machines of the chosen account. Live, Agents, Skills, Tools, Health, Sessions and Projects filter to the chosen machine. The budget label reads "manual, local" until WU-22 adds remote rows. Panels filter the base tables by machine and account. WU-22 later switches the account-scope panels to the _all views. Telemetry-derived panels (Agents, Skills, Tools, Health) are machine scope, so no account join is needed.
    • Test scenarios (red first): table-driven over 0, 1 and 2 machines and 0, 1 and 2 accounts: account panels sum, machine panels filter, and two accounts on one machine exclude each other.
    • Done When:
      • A fixture with two machines and two accounts passes both scopes.

    WU-11: ADR 0061 and wording

    • Requires: nothing
    • Files: docs/adr/0061-opt-in-usage-sync.md (new), docs/guides/05-what-setup-installs.md:58-59, docs/guides/10-telemetry.md:5, docs/internals/04-usage-dashboard.md:169 (the email is read at ingest) and :470 (the telemetry privacy claim), ADR 0025 cross-link
    • Changes: record approach C (the number is 0061 because 0060 is the Tree-sitter record in draft), the privacy rules, and the opt-in carve-out ("nothing leaves your machine unless you turn on sync"). State the threat model of the salted account hash: the salt sits in the same remote as the data, so the hash only stops casual reading and does not stop a dictionary guess over known emails. State that transcripts must stay machine-local, and how to revoke access (rotate the token at the provider, then run playbook sync disable). Correct the dashboard doc: usage_events stores the email today.
    • Test scenarios: playbook prose check is clean. The ADR passes the ADR quality gate.
    • Done When:
      • ADR accepted and the three doc lines updated.

    WU-12: libsql engine and evidence gate

    • Requires: WU-5, WU-11
    • Files: crates/store (feature engine-libsql), crates/sync skeleton, .github/workflows/rust-ci.yml (job sync-targets), docs/internals/sync-evidence.md
    • Changes: a libsql engine behind the store API with a blocking wrapper. A CI job builds pbsync for the five release targets (macOS arm64 and x64, Linux gnu and musl static, Windows x64) and pushes SYNC_EVIDENCE_ROWS (10,000) rows to a local sqld or tursodb --sync-server.
    • Bars (named constants in the CI job): all five targets build. pbsync stays under PBSYNC_MAX_BYTES (12 MiB). Each bar compares against a rusqlite baseline run in the same job: one warm-up, then the median of EVIDENCE_RUNS (5). The 10,000 row push takes at most PUSH_SLOWDOWN_MAX (3) times the rusqlite insert of the same rows. Opening a database and running one query with the libsql engine costs at most ENGINE_OPEN_OVERHEAD_MS (10) more than rusqlite (median minus median) on the statusline path. The sqld server binds an ephemeral port. The overhead and push bars run in the nightly job, not on every PR. The job pins its runner label, and a bar fails when the median exceeds the bar times (1 + EVIDENCE_NOISE_MARGIN_PERCENT/100), with the margin at 20 percent: the 10 ms bar fails above 12 ms and the 3x push bar above 3.6x. A rusqlite process reads the file the libsql engine wrote with no error. cargo tree -p pbsync lists no rusqlite.
    • CI and crates: every --workspace command (nextest rust-ci.yml:323-324, clippy :285,293, cargo check :652, and justfile:65,66,88,89) excludes playbook-sync, which builds, lints and tests in its own job, so feature unification never links both engines. crates/sync depends on playbook-store with default-features = false, features = ["engine-libsql"], on sha2 and serde, and on no other workspace crate. It does not depend on playbook-telemetry, which pulls the store with default features. It carries its own SQL for usage_events.
    • Decision rule: if the overhead bar passes, the playbook binary may adopt the libsql engine. If it fails, only pbsync does. The report records which.
    • Test scenarios: named scenarios: rusqlite reads a file the libsql engine wrote, a libsql writer and a rusqlite reader share one WAL file, and busy retry works across engines. A failed bar reopens this plan.
    • Done When:
      • The report is committed with measured numbers, the engine location is recorded, and crates/sync depends on the store with default-features = false.

    WU-13: Remote schema and client

    • Requires: WU-8, WU-12
    • Files: crates/sync/src/remote.rs, schema.rs
    • Changes: remote tables shared_meta(key,value), shared_usage_events and shared_config_snapshots, each with primary key (machine, local key) and a schema_version (shared_meta has its own key). The prefix shared_ marks the libSQL store; the local copies in WU-22 end in _remote. First enable creates the salt in shared_meta. Every run compares the local salt copy with shared_meta: a mismatch stops the run with a message to run sync purge on this machine. Each shared row also carries pushed_at (UTC seconds from the pusher's injected clock) and the app's own schema_version. WU-13 also creates the local tables sync_watermarks and sync_state in usage.db with CREATE IF NOT EXISTS and bumps the usage.db schema_version by one, so an older binary refuses a database that pbsync has touched. A remote schema newer than the binary stops the run with a named message. A local schema newer than the remote also stops the run with a named message and zero remote writes.
    • Test scenarios (red first): an empty remote: create is idempotent. A second client reads the same salt. Two clients creating the salt at once, released from a barrier with no sleeps: insert-if-absent, and the loser reads a salt equal to the winner's. A newer remote version refuses. A local version above the remote gives the named refusal and zero remote writes. A machine whose local salt differs from shared_meta stops with the purge message, and a matching salt proceeds. The new local tables are created once and a second run changes nothing.
    • Done When:
      • Two clients on one local file agree on salt and version.

    WU-14: Push

    • Requires: WU-8, WU-13
    • Files: crates/sync/src/push.rs, local table sync_watermarks
    • Changes: batches of SYNC_BATCH_ROWS (500) rows. Send only allowed columns: no repo, branch, cwd, paths or raw email. The account is sha256(salt + account). Only accounts in sync.accounts go (entries are the account keys as stored in usage_events.account, kept in local global config and never sent). The unit adds the sha2 crate with an exact pin after the repo's dependency vetting. pbsync reads sync.url, sync.accounts and the token variable name from the settings file that WU-17 writes. Send only columns named in a per-table SYNC_COLUMNS allowlist in code, so a new column stays local until someone adds it. Watermarks use rowid, not timestamps. Each run also re-sends the last SYNC_RESEND_WINDOW_SECONDS (3600) of rows, because a local row can grow after its first write. The remote does an upsert that overwrites the token and cost columns only when output_tokens is larger and keeps the other columns, as the local upsert does (crates/telemetry/src/db.rs:220-227). In the same branch it sets pushed_at to the current time, so a grown row moves past every pull cursor. Push skips any row whose machine is empty (an interrupted backfill). A failed push never blocks hooks, the statusline or ingest, because only pbsync and playbook sync now run it. The watermark advances only after the remote commit.
    • Test scenarios (red first): an account not on the allowlist sends nothing. A second push writes 0 rows. A row with a path leaves no path in the remote. Batch sizes 0, 1, 500 and 501 push complete. A remote duplicate with a larger and with a smaller output_tokens keeps the larger. The remote is a parameter that can fail on the Nth batch: the watermark stops at the last committed batch and a re-run converges with zero duplicates. An unreachable remote leaves the watermark unchanged and the local command succeeds, with backoff capped at SYNC_BACKOFF_MAX_SECONDS (900). The clock is a parameter. A column added to the local table and absent from SYNC_COLUMNS does not appear in the remote row. A row that grows inside the resend window is re-sent and the remote keeps the larger output_tokens, with boundary cases on the injected clock: a row 3,600 seconds old is re-sent and one 3,601 seconds old is not. No remote row holds a raw email. After a push, no row from tool_invocation_events, telemetry_requests, telemetry_tools, telemetry_errors or telemetry_metrics appears in any remote table. A run of consecutive failures waits 30, 60, 120, 240, 480, 900, 900 seconds (base 30, doubling, cap SYNC_BACKOFF_MAX_SECONDS), asserted as an exact list on the injected clock. A row with an empty machine is not sent. A grown row gets a new pushed_at, and a pull whose cursor already passed the old pushed_at still receives it. The remote payload holds neither the machine display name nor the creation hostname. Seeded table-driven cases need no new dependency.
    • Done When:
      • Push is idempotent and column-complete.

    WU-22: Remote copies, views and alias table

    • Requires: WU-8, WU-10
    • Files: crates/telemetry/src/db.rs, query.rs, tui/data.rs
    • Changes: create usage_events_remote keyed (machine, event_id) with an index on event_id, an account_aliases(hash, key) table, and the view usage_events_all. The view returns one whole row per event_id: the row with the larger output_tokens, and the local row on a tie (the real upsert at crates/telemetry/src/db.rs:220-227 overwrites six token and cost columns together, and only when output_tokens grows, so mixing those columns across rows is wrong). The unit bumps the usage.db schema_version by one (WU-6 introduced it, WU-8 and WU-13 also bump it). The remote copy stores repo and branch as empty strings, because the base table declares them NOT NULL (crates/telemetry/src/db.rs:23-24). The view shows (not synced) for them and for the Projects, Tools, Agents, Skills and Health panels of another machine. It is inert until WU-15 pulls rows. The account of a remote row comes from account_aliases, or reads synced:<first 8 hex of the hash> when no alias exists, so it shows as its own entry in the account selector. Switch the account-scope panels to the views. The budget label reads "all machines" when remote rows exist.
    • Test scenarios (red first): a remote-only row is visible. The same event_id gives exactly one row (row-count assertion). A larger remote output_tokens wins with its own cost, a tie picks the local row, and two copies with differing cost return one whole row. An unresolved hash shows as synced: plus exactly 8 lowercase hex digits, and adding an alias re-resolves without a new pull. The budget label reads "all machines" with remote rows and "manual, local" without. A usage.db at version N-1 upgrades to N with its rows intact, a database at N+1 is refused with zero writes, and a fresh database stamps N. Another machine's Projects and Tools panels show (not synced) and the view's repo and branch columns hold the placeholder. The WU-10 suite reruns unchanged against the views. A nightly job (outside nextest, pinned runner) runs a 500,000-row timing test: the Spend, Burnup and Models range queries through the view fail above 2.4 times the base-table query (VIEW_SLOWDOWN_MAX 2 times 1 plus EVIDENCE_NOISE_MARGIN_PERCENT 20 percent), as medians of EVIDENCE_RUNS on the same runner. The per-PR suite checks row counts only.
    • Done When:
      • Account panels sum all machines and the budget label matches with and without remote rows.

    WU-15: Pull

    • Requires: WU-14, WU-22
    • Files: crates/sync/src/pull.rs
    • Changes: pull rows whose machine differs from the local id and upsert them by (machine, event_id), overwriting the token and cost columns only when output_tokens is larger, machine set to the origin. Pull pages by the keyset (pushed_at, event_id) with SYNC_BATCH_ROWS rows per page, so rows sharing one pushed_at are never skipped. The cursor per remote machine is the largest pushed_at seen minus SYNC_RESEND_WINDOW_SECONDS, so rows that grew after their first push come again. A pusher clock that is more than that window behind can hide rows, and the guide states the limit. Insert into the local usage_events_remote copy (created in WU-22), never into the local table. When the same event_id exists locally, the view keeps the row with the larger output_tokens, and pull counts the overlap. Skip rows whose machine equals the local id (self-echo). Compute sha256(salt + account) for every distinct usage_events.account value and every account in account_names when that table exists (pbsync reads both from usage.db, and imports nothing from crates/cli), using the same string form that push hashes, and upsert the result into account_aliases, so a remote row of the same account resolves to the local account. The local copy of the salt lives in a local sync_state table. Salt rotation is not supported: the guide says to run purge --all on one machine, purge on every other machine, and enable again.
    • Test scenarios (red first): two temp databases and a local libsql file as the fake remote: after push and pull both ends hold the same rows, a second round writes 0, and a clash is counted without a duplicate. A self-echo row is skipped. A remote row of an account that exists locally resolves through account_aliases, and a hash with no local account stays unresolved. The same event_id from two machines stores two remote rows and shows one row in the view. After a pull the local table row counts are unchanged. The remote fails on the Nth pull page: upserts and the cursor commit in one transaction, the cursor stops at the last committed page, and a re-run converges with zero skipped rows and zero duplicates. Pull batch sizes 0, 1, 500 and 501 all arrive complete, and 501 rows sharing one pushed_at all arrive. A smaller-output_tokens duplicate pulled for an existing remote row leaves tokens and cost unchanged. A concurrent rusqlite ingest writer and a pbtop-style reader both run during a pull batch without error, driven by the between-batch callback from WU-8 (the callback writes an ingest row after batch N and the test asserts it commits, with no sleeps), and each pull batch commits in its own short transaction under the 5-second busy timeout. A row that grows after its first pull is updated on the next pull. An account known only from account_names gets an alias.
    • Done When:
      • Two simulated machines converge.

    WU-16: Shared config snapshot

    • Requires: WU-15
    • Files: crates/sync/src/config.rs
    • Changes: push the keys in the SHARED_KEYS allowlist, defined in crates/cli/src/config/keys.rs next to USER_KEYS, into shared_config_snapshots, using a key list file {"include":[...],"exclude":[...]} whose format this unit defines and tests with a fixture (WU-17 writes it). The exclusion list always holds every sync.* key. A pull writes a proposal file and changes no value.
    • Test scenarios (red first): a per-user key stays on the machine. A machine-path key is absent from shared_config_snapshots. A test walks every key in keys.rs and asserts each is classified shared or local, so a new key fails the build until classified. A pulled snapshot carrying a key outside SHARED_KEYS is rejected. The include list written to the key file equals SHARED_KEYS exactly. No sync.* key appears there, and a pulled snapshot carrying sync.enabled or sync.url is rejected. A pull writes a proposal, config apply then sets the local value, and nothing changes before apply.
    • Done When:
      • Local values win until the owner applies a proposal.

    WU-17: playbook sync commands and keys

    • Requires: WU-15
    • Files: crates/cli/src/sync/** (new), config/keys.rs, main.rs
    • Changes: sync enable, disable, purge, status, now, config apply. disable stops syncing and keeps the data. purge deletes this machine's remote rows first. If that fails, local state is kept, sync.enabled stays false and the command exits non-zero. After it succeeds, purge clears the local usage_events_remote, account_aliases, sync_state and sync_watermarks and keeps the local usage data. A plain purge keeps the shared salt, and re-enable reuses it. purge --all asks for a yes and also deletes every machine's rows and the salt in shared_meta, and a machine that keeps the old salt stops with the purge message on its next run. purge --account <key> deletes this machine's remote rows for one account. Removing an account from sync.accounts only stops new pushes, and the guide says so. playbook sync passes sync.url, sync.accounts and the token variable name to pbsync through a settings file in the data folder (owner-only, no token), and the token reaches it through the environment variable it names. The command also writes the key list file that WU-16 reads, from SHARED_KEYS alone (the include list) plus the exclusion list. USER_KEYS plays no part in building it. Keys: sync.enabled (false), sync.url, sync.accounts (empty), sync.tokenEnv (the name of the environment variable that holds the token, so playbook stores no token), sync.intervalSeconds (900). All are global-tier only. enable prints what leaves the machine, asks for a yes, and compares the stored creation hostname with the current one: on a mismatch it offers a fresh machine id or a stop (a cloned disk would otherwise give two machines one id).
    • Test scenarios (red first): on a fresh data folder sync.enabled reads false, and sync now and a pbsync run without enable make zero requests to the fake remote. No sync.url: enable fails with the fix. Token variable unset: status says so. Answering no to the consent leaves sync.enabled false. A project-tier sync.url is rejected. A copied machine.json with another hostname triggers the prompt. Answering yes sets sync.enabled and writes the consent record. A hostname mismatch with the fresh-id choice writes a new id, and with the stop choice leaves sync.enabled false. status prints each state. now pushes against the fake remote. After disable, nothing runs, and purge empties the copies, aliases, salt and watermarks. purge while enabled stops sync first, a second purge is a no-op, and re-enable after purge reuses the shared salt and re-sends every row. With two machines seeded in the fake remote, purge on A removes only A's rows and keeps B's rows and the shared_meta salt, purge --all removes B's rows and the salt, and B's next run stops with the purge message. A purge against a failing remote keeps local state, leaves sync.enabled false and exits non-zero. purge --account removes only that account's rows. The settings file has mode 0600 and holds no token.
    • Done When:
      • Every command has --help and an end-to-end test against the fake remote.

    WU-18: Doctor and status rows

    • Requires: WU-17
    • Files: crates/cli/src/doctor/check.rs (PROBES :129), usage status
    • Changes: rows for sync enabled, last success, rows pending, and schema skew, each with a fix command.
    • Test scenarios (red first): table tests per state: off, healthy, stale, skew. The clock is a parameter. The stale boundary is tested at intervalSeconds minus 1, exactly, and plus 1, and zero pending rows is a case.
    • Done When:
      • playbook doctor check reports sync only when it is enabled.

    WU-19: Package pbsync

    • Requires: WU-16, WU-18
    • Files: .github/workflows/release.yml (near the pbdoc size budget), install and update code
    • Changes: build pbsync in its own cargo invocation, attest it like pbdoc, enforce PBSYNC_MAX_BYTES, install it only when sync is enabled, and update it with the main binary.
    • Test scenarios (red first): a size at PBSYNC_MAX_BYTES passes and one byte over fails (injected size). A dry-run release builds and attests the helper. The downloader is injected, and a disabled install makes zero calls.
    • Done When:
      • The release carries the helper and the size gate fails above the bar.

    WU-20: Two-machine e2e and docs

    • Requires: WU-19
    • Files: crates/sync/tests/**, docs/guides/17-sync.md (the number 16 is taken), docs/reference/config-keys.md, cli-and-config.md
    • Changes: an e2e with two data folders and a fake remote, a nightly job against a real sqld, and a guide with the policy warning and the account allowlist.
    • Test scenarios (red first): the e2e covers enable, push, pull, version skew refusal, disable and purge. A non-allowlisted account sends nothing, and the remote payload holds no path and no raw email. The nightly sqld job runs through the ignored-tests pattern at justfile:96 and the daily cron at rust-ci.yml:34-35. It binds an ephemeral port, uses a fresh database name per run, asserts row counts per machine, and ends with purge --all in a teardown that also runs after a failed assertion (a drop guard), and a test asserts the database name is unique per run.
    • Done When:
      • Docs list every command and key, and playbook prose check is clean.

    Testing Strategy

    • Every new-behavior unit (WU-6 to WU-22) writes its failing tests first. Ports (WU-1 to WU-4) add no tests and pass the existing suites plus the WU-0 characterization tests.
    • Every test uses its own temp folder (test name plus process id) and takes the clock and id generator as parameters. No test uses a fixed port or a network.
    • Unit tests per module on real SQLite files in temp folders, with no database mocks.
    • S0 to S3 add no behavior. The existing suites are the regression test, and a diff review checks that only import lines changed.
    • Seeded table-driven tests for push and pull idempotency and the column filter (no path, repo or raw email in any remote row). No new test dependency.
    • A two-machine simulation with a local libsql file as the fake remote runs on every PR in the playbook-sync job.
    • Snapshot tests for the pbtop selector and the doctor rows.
    • A nightly job against a real sqld, outside nextest.
    • Cross-version tests: a database stamped a higher version is refused, and an older one upgrades.

    Routing note

    Recommend /playbook:adr: yes, and WU-11 is that ADR. The decision is hard to reverse (remote schema, privacy promise) and its reasons are not obvious.

    Assumptions (auto-design)

    1. The owner's decisions in the session stand: libSQL store, usage and config sync, per-machine overlay, account and machine keys, storage crate first.
    2. Approach C (store crate, then engine swap) over a standalone helper. The evidence gate decides whether playbook or only pbsync runs the libsql engine. OPEN.
    3. Hosting (Turso Cloud or a self-hosted sqld) is a URL setting. OPEN: the owner picks one.
    4. Sync excludes repo, branch, cwd and paths, and hashes the account. OPEN: the owner may want repo names for the Projects panel.
    5. The work account stays off the allowlist until the owner adds it. OPEN: company policy has not been checked.
    6. A pulled config is a proposal and is not applied automatically.
    7. The machine id is a random UUID, not derived from hardware.
    8. The sync column allowlist for usage_events includes session_id and agent. OPEN: the owner may want them hashed or dropped.
    9. Disabled sync leaves the pulled copies visible in pbtop until purge. This is intended, and the status line shows the age of the last sync.
    10. Transcripts stay machine-local. A shared transcript folder would double-count unless the views deduplicate by event_id, which they do.

    Confidence + open items

    • Confidence: MEDIUM. The port segments rest on read code and a mechanical rule. The sync segments rest on external libSQL facts and an evidence gate that has not run.
    • Open items (verify downstream):
      • Whether libsql builds for Linux musl static and Windows x64 under PBSYNC_MAX_BYTES, verified by WU-12 before S9 starts.
      • Whether the libsql engine adds at most ENGINE_OPEN_OVERHEAD_MS to the statusline path, verified by WU-12. The result decides the engine location.
      • Whether a libsql process and a rusqlite process can safely share one WAL file, verified by WU-12.
      • Hosting choice and company policy for the work account, decided by the owner before WU-14 runs on the work computer.
      • Whether hashed repo names are acceptable for the Projects panel, decided by the owner during WU-14.
      • The account stack (PRs 1577 to 1584) merged and released before WU-7 starts, watched by /playbook:implement.
      • S4 must reach users in a release before S5 merges. Older binaries have no schema check for usage.db, so they cannot refuse the new columns. Say so in the release notes.
  3. 32 remaining items

  4. added
    collaborator-opened
    on Nov 9, 2026
  5. igorjs commented on Nov 17, 2026

    @igorjs
    MemberAuthor

    pbtop and pbsync cover the goal: usage and config sync between computers through pbsync, opt in and manual. ADR 0061 is accepted in #1861. If automatic sync turns out to be needed, I'll open a separate issue for it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    collaborator-openeddesignenhancementlater

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions