Repository navigation
Description
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 (thetursocrate) 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 libsqlbundles its own C SQLite fork. A second SQLite in the same binary fails at link time with duplicatesqlite3_*symbols, sorusqlite =0.40.2would 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
tursoengine 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_eventsand 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 andwatch.dbare rebuildable or machine-specific, so they stay out.usage_watermarksandusage_backfill_filesare per-machine cursors and stay local. telemetry_errorskeys on a locally assignedsequenceand would collide. Rows withAUTOINCREMENTids (codeworktrees, watchwork, 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_eventsstores 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 istoken: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
- Finish account separation (PRs 1577 to 1584).
- Add a machine id and a machine column. This has value alone, because it makes the per-machine views correct without any sync.
- Write the ADR for opt-in sync and the privacy carve-out.
- Run
/playbook:planagain to produce the implementation plan. A checkpoint with these decisions exists for the slugsync-usage-database-between-computers.
Out of scope
Memory facts, the code index, the gate database and watch.db.
Activity
igorjs commentedon Nov 6, 2026
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
usage_eventsandtool_invocation_eventscarry anaccountcolumn (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.crates/telemetry/src/tui/data.rs:428,crates/telemetry/src/query.rs:300,323,371,639).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.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.rusqlite =0.40.2(bundled) sits in five crates (crates/cli,code,common,data,telemetry), in 49 files (41 insrc/, 8 intests/). WU-0 reports exact call-site counts per crate. There is no shared connection layer.libsqlbundles its own SQLite, and two SQLite libraries fail to link in one binary (external reports, rechecked in WU-12). ThelibsqlAPI is async and the workspace has no async runtime.Goals
usage_events) and of a shared configuration snapshot to a libSQL store, with a per-machine overlay.tool_invocation_eventsand the four telemetry tables carry the machine and stay local in this version.Non-goals
watch.db.Approaches considered
libsqldirectly. 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.pbsynchelper that useslibsqland shares no code with the shipped crates. Kept as the fallback. It duplicates SQL and needs its own copies of the table code.playbook-storein place ofrusqlite. The crate is a thin shim that keeps rusqlite's names, so call sites change theiruseline and little else. The shim re-exports rusqlite, and the code uses parts of rusqlite that libsql cannot copy (&dyn ToSqlslices,unchecked_transaction, borrowed statements over async rows). Alibsqlengine therefore sits behind a cargo feature, and the expected outcome is that it serves only thepbsynchelper.playbookadopts it only if WU-0 maps every API item and WU-12 passes the overhead bar.Decision
Approach C. Segments S0 to S3 move the whole workspace behind
playbook-storewith no behavior change. A CI guard then fails anyrusqliteimport 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
libsqlbuilds 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 ispbsynconly. 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 norepo,branch,cwdor file path, and never the raw email. The account goes as a salted hash. The salt lives in the remoteshared_metatable 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, packageplaybook-store):Connection,Transaction,params!,Row,OpenFlags,Error, the busy-retry helper now incrates/common/src/sqlite.rs:23, and aschemamodule with the open-time version check copied fromcrates/data/src/memory.rs:166-169. Two mutually exclusive cargo features:engine-rusqlite(the default) andengine-libsql(arrives in WU-12). Building with both fails with acompile_error!.disallowed-typesplus a CI grep) forbidsrusqliteoutsidecrates/store.crates/telemetrygainsmachine.rsand amachinecolumn on six tables (usage_events,tool_invocation_events,telemetry_requests,telemetry_tools,telemetry_errors,telemetry_metrics). Stamping happens beside the account atingest.rs:78,96.crates/telemetry/src/tui) getsMachineSelbesideAccountSel(tui/account.rs, on the account stack). The worker query tuple carries it (tui/worker.rs:63).data::loadfilters machine panels, and account panels read all rows.crates/sync(new) builds thepbsyncbinary onplaybook-storewithdefault-features = false, features = ["engine-libsql"]. A CI step runscargo tree -p pbsyncand fails whenrusqliteappears. The cli passes it the list of shareable config keys as a file, sopbsyncimports nothing fromcrates/cli.SHARED_KEYSallowlist in code sync as asharedsnapshot. 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 applyaccepts it after showing the diff.playbookandpbsyncin separate cargo invocations, so cargo feature unification never links both engines into one binary.Files to Create/Modify
membersand[workspace.lints.clippy])crates/store,crates/sync, enabledisallowed_typesCargo.tomland every rusqlite use)playbook-storeplaybook synccommandspbsynchelperdisallowed-typeslist forrusqliteSegments (suggested PRs)
S3 is over 500 because the cli crate holds the most call sites.
/playbook:implementmay 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:implementmay split it. The ports in S1 to S3 run in order because each one changesCargo.lock.Deliverables (Work Units)
rusqliteimport remains in telemetryrusqliteimport remains in coderusqliteimport remains in clirusqliteimport outside the storeplaybook usage machineprints a stable id and namemachine, backfill runs oncexcycles this machine, one machine, all machinesplaybook synccommands and keyspbsyncParallel Groups
Cargo.lockand 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
membersonly; each crate keeps its own pin, for examplecrates/data/Cargo.toml:18)rusqlite =0.40.2that keeps its names (Connection,Transaction,params!,Row,OpenFlags,Error,ErrorCode). Move the busy-retry helper fromcrates/common/src/sqlite.rs:23(retriesDatabaseBusyandDatabaseLocked) and the telemetry copy atcrates/telemetry/src/db.rs:58-76(retriesDatabaseBusyonly) 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 ToSqlslices,Transaction::new_uncheckedandunchecked_transaction,transaction_with_behavior,pragma_update,execute_batch,busy_timeout,types::ValueRef,prepare, FTS5MATCH) with its libsql equivalent ornone. Addscripts/check-port-diff.sh: overgit diff -U0it fails when a changed line is outsideuselines and type paths, or when a test file changes any line other than auseor dependency line. Carrypublish = falseand[lints] workspace = true.rusqliteis an optional dependency enabled only by theengine-rusqlitefeature, andcrates/store/src/lib.rscarries the one#![allow(clippy::disallowed_types)].SQLITE_BUSYmaps 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 FTS5MATCHreturns 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 runsscripts/check-port-diff.sh: it fails on a non-import change, fails on a test-file change outsideuselines, and passes on an import-only change. Each test uses its own temp folder (test name plus process id).WU-1: Port common and data
sqlite.rs, crates/data/Cargo.toml,memory.rs,config.rs,migrate.rsuse rusqlite::withuse playbook_store::. No behavior change.scripts/check-port-diff.shpasses on the PR.rusqliteimport remains in the two crates.WU-2, WU-3, WU-4: Port telemetry, code index and cli
Cargo.tomland every file that namesrusqlite(open functions: telemetrydb.rs:88, codedb.rs:367,623,738, cliconfig/store.rs:94,gate/db.rs:173,watch/store.rs:127,state/mod.rs:44)uselines, the golden file still matches, andscripts/check-port-diff.shpasses. Snapshot and CLI tests are unchanged.WU-5: Guard
disallowed-types), root Cargo.toml[workspace.lints.clippy](line 16), .github/workflows/rust-ci.yml, docs/internals noterusqlitetypes outsidecrates/storewithdisallowed-types, and add a script as a second check that also scanstests/directories andCargo.tomldependency 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 incrates/telemetry/tests/and run the builtpbsyncbinary as a subprocess, read from aPBSYNC_BINvariable. CI buildspbsyncand exportsPBSYNC_BINfirst, as the pbdoc step does (rust-ci.yml:305-318), because cargo builds a binary only for its own crate's tests. They never linkplaybook-sync, so no crate links both engines andcrates/synckeeps no edge to rusqlite or telemetry.use rusqlite::, a fully qualifiedrusqlite::Connectionwith nouse, aCargo.tomldependency line, and a cleancrates/storefile that must pass. A second test readsclippy.tomland asserts that it lists therusqlitetypes. No violating file is committed.WU-6: Schema version on open
schema_versionrow inmeta. A stored version above ours returns an error that names both versions and the update command. Copy the message shape ofcrates/data/src/memory.rs:166-169. Follow ADR 0016 for migrations.schema_versionon a fresh database stamps it. A non-integer value returns a named error with no writes.playbook doctorshows a store schema row.WU-21: Unify the busy-retry policy
tests/usage_boundary.rs, whichcrates/common/src/sqlite.rs:12cites and main does not contain. The two helpers retry different errors today (DatabaseBusyandDatabaseLockedagainstDatabaseBusyonly). Keep the superset policy (retry onDatabaseBusyandDatabaseLocked), change the telemetry caller to it, and state the change in the PR because it changes behavior on the ingest and statusline paths.budgetduration elapses (fake clock; the helper takes aDurationbudget,crates/common/src/sqlite.rs:23-26). A non-retryable error fails at once.DatabaseLockedretries on both paths. The ingest and statusline suites pass.WU-7: Machine id and name
/playbook:implement: the account stack (PRs 1577 to 1584) is merged and released, soplaybook usage account listexists.uuidandhostnamecrates 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.--namepersists and the id stays. A stored creation hostname that differs from the injected current hostname is reported by a function that WU-17 calls atsync enable. The file mode is 0600 (unix only).WU-8: Machine column, stamp and backfill
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)ensure_machine_columnon the six tables. Local primary keys stay as they are, becauseALTER TABLE ADD COLUMNcannot change a key. The unit bumps theusage.dbschema_versionby 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 ofBACKFILL_BATCH_ROWS(5,000) so it never holds one long write against hooks and the statusline. The upsert keeps the largeroutput_tokensas today. The four telemetry tables get no account column: their panels are machine scope.ingest.rsand 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.machineand the backfill runs once.WU-9: Machine selector in pbtop
AccountSelexists only on its branch.MachineSel {This, Key, All}besideAccountSel. The keyxcycles it. The other letters near it are taken:mandMselect the month ranges (keys.rs:301,311), andais the account selector.xis unbound inkeys.rs; the unit re-checks before use. The worker tuple carries it. The title shows the machine name. The choice saves inusage.ui.state.xshows a single entry. The choice persists and a reopen restores it. A corrupt saved state falls back toThis. The machine name appears in the title text. Pressingxcycles This, Key, All, This.WU-10: Scope-correct panels
_allviews. Telemetry-derived panels (Agents, Skills, Tools, Health) are machine scope, so no account join is needed.WU-11: ADR 0061 and wording
playbook sync disable). Correct the dashboard doc:usage_eventsstores the email today.playbook prose checkis clean. The ADR passes the ADR quality gate.WU-12: libsql engine and evidence gate
engine-libsql), crates/sync skeleton, .github/workflows/rust-ci.yml (jobsync-targets), docs/internals/sync-evidence.mdlibsqlengine behind the store API with a blocking wrapper. A CI job buildspbsyncfor the five release targets (macOS arm64 and x64, Linux gnu and musl static, Windows x64) and pushesSYNC_EVIDENCE_ROWS(10,000) rows to a localsqldortursodb --sync-server.pbsyncstays underPBSYNC_MAX_BYTES(12 MiB). Each bar compares against a rusqlite baseline run in the same job: one warm-up, then the median ofEVIDENCE_RUNS(5). The 10,000 row push takes at mostPUSH_SLOWDOWN_MAX(3) times the rusqlite insert of the same rows. Opening a database and running one query with the libsql engine costs at mostENGINE_OPEN_OVERHEAD_MS(10) more than rusqlite (median minus median) on the statusline path. Thesqldserver 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. Arusqliteprocess reads the file the libsql engine wrote with no error.cargo tree -p pbsynclists norusqlite.--workspacecommand (nextestrust-ci.yml:323-324, clippy:285,293,cargo check:652, andjustfile:65,66,88,89) excludesplaybook-sync, which builds, lints and tests in its own job, so feature unification never links both engines.crates/syncdepends onplaybook-storewithdefault-features = false, features = ["engine-libsql"], onsha2andserde, and on no other workspace crate. It does not depend onplaybook-telemetry, which pulls the store with default features. It carries its own SQL forusage_events.playbookbinary may adopt the libsql engine. If it fails, onlypbsyncdoes. The report records which.crates/syncdepends on the store withdefault-features = false.WU-13: Remote schema and client
shared_meta(key,value),shared_usage_eventsandshared_config_snapshots, each with primary key(machine, local key)and aschema_version(shared_metahas its own key). The prefixshared_marks the libSQL store; the local copies in WU-22 end in_remote. First enable creates the salt inshared_meta. Every run compares the local salt copy withshared_meta: a mismatch stops the run with a message to runsync purgeon this machine. Each shared row also carriespushed_at(UTC seconds from the pusher's injected clock) and the app's ownschema_version. WU-13 also creates the local tablessync_watermarksandsync_stateinusage.dbwithCREATE IF NOT EXISTSand bumps theusage.dbschema_versionby 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.shared_metastops with the purge message, and a matching salt proceeds. The new local tables are created once and a second run changes nothing.WU-14: Push
sync_watermarksSYNC_BATCH_ROWS(500) rows. Send only allowed columns: norepo,branch,cwd, paths or raw email. The account issha256(salt + account). Only accounts insync.accountsgo (entries are the account keys as stored inusage_events.account, kept in local global config and never sent). The unit adds thesha2crate with an exact pin after the repo's dependency vetting.pbsyncreadssync.url,sync.accountsand the token variable name from the settings file that WU-17 writes. Send only columns named in a per-tableSYNC_COLUMNSallowlist in code, so a new column stays local until someone adds it. Watermarks use rowid, not timestamps. Each run also re-sends the lastSYNC_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 whenoutput_tokensis larger and keeps the other columns, as the local upsert does (crates/telemetry/src/db.rs:220-227). In the same branch it setspushed_atto the current time, so a grown row moves past every pull cursor. Push skips any row whosemachineis empty (an interrupted backfill). A failed push never blocks hooks, the statusline or ingest, because onlypbsyncandplaybook sync nowrun it. The watermark advances only after the remote commit.output_tokenskeeps 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 atSYNC_BACKOFF_MAX_SECONDS(900). The clock is a parameter. A column added to the local table and absent fromSYNC_COLUMNSdoes not appear in the remote row. A row that grows inside the resend window is re-sent and the remote keeps the largeroutput_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 fromtool_invocation_events,telemetry_requests,telemetry_tools,telemetry_errorsortelemetry_metricsappears in any remote table. A run of consecutive failures waits 30, 60, 120, 240, 480, 900, 900 seconds (base 30, doubling, capSYNC_BACKOFF_MAX_SECONDS), asserted as an exact list on the injected clock. A row with an emptymachineis not sent. A grown row gets a newpushed_at, and a pull whose cursor already passed the oldpushed_atstill receives it. The remote payload holds neither the machine display name nor the creation hostname. Seeded table-driven cases need no new dependency.WU-22: Remote copies, views and alias table
usage_events_remotekeyed(machine, event_id)with an index onevent_id, anaccount_aliases(hash, key)table, and the viewusage_events_all. The view returns one whole row perevent_id: the row with the largeroutput_tokens, and the local row on a tie (the real upsert atcrates/telemetry/src/db.rs:220-227overwrites six token and cost columns together, and only whenoutput_tokensgrows, so mixing those columns across rows is wrong). The unit bumps theusage.dbschema_versionby one (WU-6 introduced it, WU-8 and WU-13 also bump it). The remote copy storesrepoandbranchas 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 fromaccount_aliases, or readssynced:<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.event_idgives exactly one row (row-count assertion). A larger remoteoutput_tokenswins with its own cost, a tie picks the local row, and two copies with differing cost return one whole row. An unresolved hash shows assynced: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. Ausage.dbat 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'srepoandbranchcolumns 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_MAX2 times 1 plusEVIDENCE_NOISE_MARGIN_PERCENT20 percent), as medians ofEVIDENCE_RUNSon the same runner. The per-PR suite checks row counts only.WU-15: Pull
(machine, event_id), overwriting the token and cost columns only whenoutput_tokensis larger, machine set to the origin. Pull pages by the keyset(pushed_at, event_id)withSYNC_BATCH_ROWSrows per page, so rows sharing onepushed_atare never skipped. The cursor per remote machine is the largestpushed_atseen minusSYNC_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 localusage_events_remotecopy (created in WU-22), never into the local table. When the sameevent_idexists locally, the view keeps the row with the largeroutput_tokens, and pull counts the overlap. Skip rows whose machine equals the local id (self-echo). Computesha256(salt + account)for every distinctusage_events.accountvalue and every account inaccount_nameswhen that table exists (pbsync reads both fromusage.db, and imports nothing fromcrates/cli), using the same string form that push hashes, and upsert the result intoaccount_aliases, so a remote row of the same account resolves to the local account. The local copy of the salt lives in a localsync_statetable. Salt rotation is not supported: the guide says to runpurge --allon one machine,purgeon every other machine, and enable again.account_aliases, and a hash with no local account stays unresolved. The sameevent_idfrom 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 onepushed_atall arrive. A smaller-output_tokensduplicate 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 fromaccount_namesgets an alias.WU-16: Shared config snapshot
SHARED_KEYSallowlist, defined incrates/cli/src/config/keys.rsnext toUSER_KEYS, intoshared_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 everysync.*key. A pull writes a proposal file and changes no value.shared_config_snapshots. A test walks every key inkeys.rsand asserts each is classified shared or local, so a new key fails the build until classified. A pulled snapshot carrying a key outsideSHARED_KEYSis rejected. The include list written to the key file equalsSHARED_KEYSexactly. Nosync.*key appears there, and a pulled snapshot carryingsync.enabledorsync.urlis rejected. A pull writes a proposal,config applythen sets the local value, and nothing changes before apply.WU-17:
playbook synccommands and keyssync enable,disable,purge,status,now,config apply.disablestops syncing and keeps the data.purgedeletes this machine's remote rows first. If that fails, local state is kept,sync.enabledstays false and the command exits non-zero. After it succeeds,purgeclears the localusage_events_remote,account_aliases,sync_stateandsync_watermarksand keeps the local usage data. A plainpurgekeeps the shared salt, and re-enable reuses it.purge --allasks for a yes and also deletes every machine's rows and the salt inshared_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 fromsync.accountsonly stops new pushes, and the guide says so.playbook syncpassessync.url,sync.accountsand the token variable name topbsyncthrough 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, fromSHARED_KEYSalone (the include list) plus the exclusion list.USER_KEYSplays 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.enableprints 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).sync.enabledreads false, andsync nowand apbsyncrun without enable make zero requests to the fake remote. Nosync.url:enablefails with the fix. Token variable unset:statussays so. Answering no to the consent leavessync.enabledfalse. A project-tiersync.urlis rejected. A copiedmachine.jsonwith another hostname triggers the prompt. Answering yes setssync.enabledand writes the consent record. A hostname mismatch with the fresh-id choice writes a new id, and with the stop choice leavessync.enabledfalse.statusprints each state.nowpushes against the fake remote. Afterdisable, nothing runs, andpurgeempties the copies, aliases, salt and watermarks.purgewhile enabled stops sync first, a secondpurgeis a no-op, and re-enable afterpurgereuses the shared salt and re-sends every row. With two machines seeded in the fake remote,purgeon A removes only A's rows and keeps B's rows and theshared_metasalt,purge --allremoves 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, leavessync.enabledfalse and exits non-zero.purge --accountremoves only that account's rows. The settings file has mode 0600 and holds no token.--helpand an end-to-end test against the fake remote.WU-18: Doctor and status rows
PROBES:129), usage statusintervalSecondsminus 1, exactly, and plus 1, and zero pending rows is a case.playbook doctor checkreports sync only when it is enabled.WU-19: Package
pbsyncpbsyncin its own cargo invocation, attest it likepbdoc, enforcePBSYNC_MAX_BYTES, install it only when sync is enabled, and update it with the main binary.PBSYNC_MAX_BYTESpasses 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.WU-20: Two-machine e2e and docs
sqld, and a guide with the policy warning and the account allowlist.sqldjob runs through the ignored-tests pattern atjustfile:96and the daily cron atrust-ci.yml:34-35. It binds an ephemeral port, uses a fresh database name per run, asserts row counts per machine, and ends withpurge --allin a teardown that also runs after a failed assertion (a drop guard), and a test asserts the database name is unique per run.playbook prose checkis clean.Testing Strategy
playbook-syncjob.sqld, outside nextest.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)
playbookor onlypbsyncruns the libsql engine. OPEN.sqld) is a URL setting. OPEN: the owner picks one.repo,branch,cwdand paths, and hashes the account. OPEN: the owner may want repo names for the Projects panel.usage_eventsincludessession_idandagent. OPEN: the owner may want them hashed or dropped.purge. This is intended, and the status line shows the age of the last sync.event_id, which they do.Confidence + open items
libsqlbuilds for Linux musl static and Windows x64 underPBSYNC_MAX_BYTES, verified by WU-12 before S9 starts.ENGINE_OPEN_OVERHEAD_MSto the statusline path, verified by WU-12. The result decides the engine location./playbook:implement.usage.db, so they cannot refuse the new columns. Say so in the release notes.docs(adr): record opt-in usage sync (#1622)
refactor(store): add the playbook-store crate over rusqlite (#1623)
Merge branch 'main' into feat/gh-1585-machine-id
Merge branch 'main' into feat/gh-1585-machine-id
Merge branch 'main' into refactor/gh-1585-port-common-data
refactor(store): move common and data onto playbook-store (#1629)
Merge branch 'main' into feat/gh-1585-machine-id
feat(usage): add a stable machine id and name (#1626)
Merge branch 'main' into refactor/gh-1585-port-telemetry
refactor(store): move telemetry onto playbook-store (#1633)
Merge branch 'main' into test/gh-1585-machine-independent-tests
32 remaining items
Merge branch 'main' into ci/gh-1585-package-pbsync
ci(release): package the pbsync binary with the main release (#1683)
feat(config): classify which config keys may sync between machines (#…
Merge branch 'main' into feat/gh-1585-install-pbsync
feat(update): install and update pbsync beside the playbook binary (#…
Merge branch 'main' into feat/gh-1585-pbsync-purge
feat(pbsync): add the purge command (#1687)
feat(config): apply a synced config proposal after showing the diff (#…
Merge branch 'main' into feat/gh-1585-pbsync-config
feat(pbsync): push and pull the shared config snapshot (#1689)
docs(sync): link the guide from the config keys page (#1585)
docs(sync): add the usage sync guide and correct the privacy wording (#…
igorjs commentedon Nov 17, 2026
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.