Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
8e59b1d
F12-Q: move Android sync policy and lifecycle transport to companion
Fledgewing Nov 26, 2026
6b520bb
Merge feature/0.12 with reviewed UI fixes and cover command prerequisite
Fledgewing Nov 26, 2026
0cf0a25
Test legacy writer retirement before instantiation
Fledgewing Nov 26, 2026
e9b9335
Preserve disabled and unverified annotations and fix sync diagnostics
Fledgewing Nov 26, 2026
bf11053
Keep native override timestamps across delayed worker dispatch
Fledgewing Nov 26, 2026
2ae30f4
Preserve lifecycle replay order when importing generations
Fledgewing Nov 26, 2026
28aae78
Preserve account state history and Custom policy under the sync owner
Fledgewing Nov 26, 2026
df69f62
Reject delayed decisions after native document or mode changes
Fledgewing Nov 26, 2026
cbc2873
Keep stale captures from reclaiming the active sidecar lease
Fledgewing Nov 26, 2026
c3910b6
Merge latest feature/0.12 Settings slice alongside companion sync
Fledgewing Nov 26, 2026
882a8ce
Merge latest feature/0.12 Series slice alongside companion sync
Fledgewing Nov 26, 2026
e0de809
Merge feature/0.12 companion-owned covers alongside sync
Fledgewing Nov 26, 2026
65e1791
Merge feature/0.12 Reader controls alongside companion sync
Fledgewing Nov 26, 2026
87958e0
Merge feature/0.12 Stats and Clock presentation alongside sync
Fledgewing Nov 26, 2026
cc0200d
Merge catalog ownership prerequisite into sync cutover
Fledgewing Nov 26, 2026
62394d7
Merge Storage foundation into sync cutover
Fledgewing Nov 26, 2026
b5ae9cb
Merge First Run upgrade safety into sync cutover
Fledgewing Nov 26, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,8 @@ CrossInk 2.x bridge and the later stable BookSync releases become available (`xt
The guard scans production resources and shared Settings/UI data too; About credit prose may name its credited project.
See `docs/design/backend-independence.md` for adapter registration and legacy follow-ups.
A transport cutover must checkpoint every unacknowledged lifecycle phase before retiring
its source queue. Never activate a replacement position writer while the legacy writer
its source queue. Android sync now uses only neutral Library companion commands; keep policy,
durable decision state and all five lifecycle phases in the companion single owner. Never activate a replacement position writer while the legacy writer
can still drain that document; a durable position queue alone is not a lifecycle migration.

- **Nothing interrupts reading.** While a book is open in the foreground, nothing from BookSync,
Expand Down
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@ Generated support counts (settings included): ✅ supported, 🟡 partial, ❌ m

| Platform | ✅ | 🟡 | ❌ | ➖ |
|---|---:|---:|---:|---:|
| Android (M8C / Boox) | 75 | 13 | 1 | 3 |
| X4 Pro | 55 | 12 | 13 | 12 |
| X4 classic | 54 | 12 | 13 | 13 |
| X3 | 20 | 16 | 43 | 13 |
| Android (M8C / Boox) | 76 | 13 | 1 | 3 |
| X4 Pro | 55 | 12 | 14 | 12 |
| X4 classic | 54 | 12 | 14 | 13 |
| X3 | 20 | 16 | 44 | 13 |
<!-- feature-counts:end -->

## Releases
Expand Down
2 changes: 1 addition & 1 deletion ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ design and mockup approval still apply.
| **Reusable filter sheet**: nine picker rows, companion-counted facets, removable chips and a local Home Book list action. | Android building; X4 Pro, X4, X3 after | building (maintainer-authorised Android F12-G) |
| **Reading statistics and Stats widgets**: server-first cross-device days, streaks, finish counts and goal targets, with labeled local hourly/session fallback and overlap-safe today totals; Home integration is implemented; local completion/goal settings follow. | Android building (approved 2026-11-25); X4 Pro, X4, X3 deferred to firmware implementation | building |
| **BookSync library interface**: all platform UIs use one interface with BookOrbit/Grimmory adapters, capability-gated features and neutral filters with cached-catalog fallback ([BookSync Home owned-client design](docs/design/backend-independence.md#1-owned-android-client-and-ledger)); maintainer rule 2026-11-26. | Android (KOReader plugin + companion), X4 Pro, X4, X3 | building (Android F12-A foundation and F12-L adapter enforcement; X4 Pro, X4, X3 planned) |
| **Server-free Android plugin**: move remaining cover, lifecycle, mirror, copies and finish requests into companion-owned adapter commands without losing queued work ([F12-Q checkpoints](docs/design/booksync-home/F12-Q-NOTES.md)). | Android first; X4 Pro, X4, X3 deferred under the maintainer's Android-first ruling | building (durable position queue prerequisite; transport cutover and migration still pending) |
| **Server-free Android plugin**: move remaining cover, lifecycle, mirror, copies and finish requests into companion-owned adapter commands without losing queued work ([F12-Q checkpoints](docs/design/booksync-home/F12-Q-NOTES.md)). | Android first; X4 Pro, X4, X3 deferred under the maintainer's Android-first ruling | building (companion-owned sync and durable lifecycle migration implemented on feature/0.12; parallel catalog/cover/finish cutover pending) |
| **Grouped BookSync settings on the reader**, with visible sync/power controls, three mode presets, companion battery estimates and one update-channel picker. | Android first (maintainer-authorised 2026-11-25); X4 Pro, X4, X3 later | building (F12-D; measured battery and reading-preset integration follow their slices) |
| **Equivalent settings controls**: expose the [parity gap 1](docs/FEATURES.md#prioritised-parity-bugs) controls, including a sleep sync budget aligned with Android's 10/15/20 s choices. | X4 Pro, X4 | planned (0.12) |
| **BookSync status-bar preset**: add one preset over the existing native controls ([parity gap 2](docs/FEATURES.md#prioritised-parity-bugs)). | X4 Pro, X4 | planned (0.12) |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,15 @@ class CommandProvider : ContentProvider() {
return answer(true)
}
if (!KoreaderTrust.check(ctx, uid)) return answer(false, "caller")
if (method == "${Contract.PACKAGE}.call.SYNC_PREVIEW") {
val encoded=extras?.getString("args")?.takeIf { it.length<=8192 } ?: return answer(false,"budget")
val args=LuaValue.parseTransport(encoded) as? Map<*, *> ?: return answer(false,"invalid")
val start=System.nanoTime()
val body=LuaValue.encode(LibraryAccount.positionPreview(args))
OLog.i("sync.preview ms=${(System.nanoTime()-start)/1_000_000}")
if(body.size>16384) return answer(false,"budget")
return answer(true).apply { putString("body",String(body,Charsets.UTF_8)) }
}
if (method == DEVICE_SETTINGS) {
DeviceSettings.refreshAsync()
return answer(true).apply { putString("body",LuaValue.transportText(DeviceSettings.snapshot())) }
Expand All @@ -79,7 +88,8 @@ class CommandProvider : ContentProvider() {
val encoded = extras?.getString("args")?.takeIf { it.length <= 8192 } ?: return answer(false,"budget")
val op = extras.getString("op") ?: return answer(false,"missing")
return try {
val args = LuaValue.parseTransport(encoded) as? Map<*, *> ?: return answer(false,"invalid")
val parsed=LuaValue.parseTransport(encoded)
val args=when(parsed) { is Map<*, *> -> parsed; emptyList<Any>() -> emptyMap<Any,Any>(); else -> return answer(false,"invalid") }
answer(true).apply { putString("id",ServerCommands.start(ctx,op,args)) }
} catch (_: Exception) { answer(false,"invalid") }
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,27 @@ object LibraryAccount {
private val queue = Executors.newSingleThreadExecutor { r -> Thread(r, "booksync-server").apply { isDaemon = true } }
private val main = Handler(Looper.getMainLooper())
private var adapter: ServerAdapter? = null
private class Published(val state: Map<String, Any?> = emptyMap(), val owner: String? = null, val stats: Map<*, *>? = null, val fallback: RemoteReadingStats? = null)
@Volatile private var syncOwner: SyncOwner? = null
private var syncRetryScheduled=false
private fun syncOwner(ctx: Context): SyncOwner = syncOwner ?: SyncOwner(
LifecycleQueue(AndroidSql(File(ctx.filesDir,"sync-journal.db"))),
File(android.os.Environment.getExternalStorageDirectory(),"koreader/settings")).also { syncOwner=it }
private fun retrySync(ctx: Context) {
val owner=syncOwner ?: return
val a=adapter ?: return
if(syncRetryScheduled || !owner.needsRetry(a)) return
syncRetryScheduled=true
main.postDelayed({ queue.execute {
syncRetryScheduled=false
runCatching { if(owner.needsRetry(a)) owner.drain(a) }
retrySync(ctx)
} },60000)
}
fun positionPreview(args: Map<*, *>): Map<String,Any?> {
val a=adapter ?: return mapOf("pending" to true)
return syncOwner?.preview(a.id,published.positionOwner,args) ?: mapOf("pending" to true)
}
private class Published(val state: Map<String, Any?> = emptyMap(), val owner: String? = null, val stats: Map<*, *>? = null, val fallback: RemoteReadingStats? = null, val positionOwner: String? = null)
@Volatile private var published = Published()
@Volatile private var loaded = false
private var nextRefreshAt = 0L
Expand All @@ -29,7 +49,7 @@ object LibraryAccount {
if (loaded) { main.post(done); return }
val app = ctx.applicationContext
queue.execute {
try { if (!loaded) { publish(adapter(app)); loaded = true } }
try { if (!loaded) { publish(adapter(app)); syncOwner(app).restorePreviews(adapter(app)); loaded = true } }
catch (_: Exception) { published = Published() }
finally { main.post(done) }
}
Expand All @@ -45,7 +65,7 @@ object LibraryAccount {
private fun publish(a: ServerAdapter) {
val state = a.state(); val owner = a.owner()
require(LuaValue.encode(state).size <= 16384)
published = Published(state, owner, owner?.let(a::stats),a.fallbackReadingStats())
published = Published(state, owner, owner?.let(a::stats),a.fallbackReadingStats(),a.positionOwner())
}
private fun command(ctx: Context, work: (ServerAdapter) -> Unit, done: (String?) -> Unit, cleanup: () -> Unit = {}, invalidate: Boolean = true) {
val app = ctx.applicationContext
Expand All @@ -54,7 +74,7 @@ object LibraryAccount {
var error: String? = null
try { work(adapter(app)) } catch (e: ServerFailure) { error = e.kind }
catch (_: Exception) { error = "unavailable" }
finally { cleanup() }
finally { cleanup(); runCatching { retrySync(app) } }
runCatching { adapter?.let(::publish) }.onFailure { published = Published(); error = "unavailable" }
if (invalidate) Worker.accountChanged(app)
OLog.i("server.command ms=${(System.nanoTime()-start)/1_000_000}")
Expand All @@ -70,7 +90,12 @@ object LibraryAccount {
fun useAccountLogin(ctx: Context, kind: String, done: (String?) -> Unit) = command(ctx, { it.useAccountLogin(kind) }, done)
fun position(ctx: Context, document: String, update: Map<String,Any?>? = null, done: (Map<String,Any?>?,String?) -> Unit) {
var result: Map<String,Any?>? = null
command(ctx, { result = it.position(document,update) }, { done(result,it) }, invalidate = false)
// Writes go through the same owner/policy journal as lifecycle captures.
command(ctx, { result = if(update==null) it.position(document,null) else syncOwner(ctx.applicationContext).write(it,document,update) }, { done(result,it) }, invalidate = false)
}
fun sync(ctx: Context, op: String, args: Map<*, *>, done: (Map<String,Any?>?,String?)->Unit) {
var result: Map<String,Any?>?=null
command(ctx,{ result=syncOwner(ctx.applicationContext).command(it,op,args) },{ done(result,it) },invalidate=false)
}
fun catalog(ctx: Context, page: Int = 1, limit: Int = 24, done: (Map<String,Any?>?,String?) -> Unit) {
var result: Map<String,Any?>? = null
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package net.fledgewing.orbitcompanion

/** Sole worker's durable five-phase journal. Payloads/checkpoints belong to the adapter and
* never enter the UI read model. Every phase commits separately, including remote-pending data. */
class LifecycleQueue(val sql: Sql) {
companion object {
val PHASES = listOf("match","stats","annotations","state","progress")
const val WINDOW = 24
const val MAX_BYTES = 200 * 1024 * 1024
}
data class Entry(val id: String, val adapter: String, val owner: String, val document: String,
val payload: ByteArray, val acknowledged: Set<String>, val checkpoint: ByteArray,
val source: String?, val retired: Boolean)
init {
sql.exec("CREATE TABLE IF NOT EXISTS lifecycle_jobs (sequence INTEGER PRIMARY KEY AUTOINCREMENT,id TEXT NOT NULL UNIQUE,adapter TEXT NOT NULL,owner TEXT NOT NULL,document TEXT NOT NULL,payload BLOB NOT NULL,checkpoint BLOB NOT NULL,source TEXT,retired INTEGER NOT NULL DEFAULT 0,done INTEGER NOT NULL DEFAULT 0)")
sql.exec("CREATE UNIQUE INDEX IF NOT EXISTS lifecycle_source ON lifecycle_jobs(adapter,source) WHERE source IS NOT NULL")
sql.exec("CREATE INDEX IF NOT EXISTS lifecycle_owner ON lifecycle_jobs(adapter,owner,done,sequence)")
sql.exec("CREATE TABLE IF NOT EXISTS lifecycle_acks (id TEXT NOT NULL,phase TEXT NOT NULL,PRIMARY KEY(id,phase))")
sql.exec("CREATE TABLE IF NOT EXISTS sync_records (adapter TEXT NOT NULL,owner TEXT NOT NULL,document TEXT NOT NULL,body BLOB NOT NULL,PRIMARY KEY(adapter,owner,document))")
sql.exec("CREATE TABLE IF NOT EXISTS sync_imports (adapter TEXT NOT NULL,source TEXT NOT NULL,job TEXT NOT NULL,proof BLOB NOT NULL,retired INTEGER NOT NULL DEFAULT 0,PRIMARY KEY(adapter,source))")
}
fun enqueue(adapter: String, owner: String, document: String, payload: ByteArray,
acknowledged: Set<String> = emptySet(), checkpoint: ByteArray = LuaValue.encode(emptyMap<String,Any>()),
source: String? = null, proof: ByteArray = byteArrayOf()): String = sql.transaction {
require(adapter.isNotBlank() && owner.isNotBlank() && document.isNotBlank())
require(acknowledged.all { it in PHASES } && payload.size <= MAX_BYTES && checkpoint.size <= MAX_BYTES)
if (source != null) imported(adapter,source)?.let { return@transaction it }
check(sql.query("SELECT COUNT(*) FROM lifecycle_jobs WHERE done=0") { it.long(0)!! }.single()<1000) { "lifecycle queue full" }
check(sql.query("SELECT COALESCE(SUM(length(payload)+length(checkpoint)),0) FROM lifecycle_jobs WHERE done=0") { it.long(0)!! }.single()+payload.size+checkpoint.size<=MAX_BYTES) { "lifecycle byte limit" }
val id = java.util.UUID.randomUUID().toString()
sql.exec("INSERT INTO lifecycle_jobs(id,adapter,owner,document,payload,checkpoint,source) VALUES (?,?,?,?,?,?,?)",id,adapter,owner,document,payload,checkpoint,source)
for (phase in acknowledged) sql.exec("INSERT INTO lifecycle_acks VALUES (?,?)",id,phase)
if (source != null) sql.exec("INSERT INTO sync_imports(adapter,source,job,proof) VALUES (?,?,?,?)",adapter,source,id,proof)
id
}
fun imported(adapter: String, source: String): String? = sql.query("SELECT job FROM sync_imports WHERE adapter=? AND source=?",adapter,source) { it.text(0) }.firstOrNull()
fun importProof(adapter: String, source: String): ByteArray? = sql.query("SELECT proof FROM sync_imports WHERE adapter=? AND source=?",adapter,source) { it.bytes(0) }.firstOrNull()
fun imports(adapter: String): List<Pair<String,ByteArray>> = sql.query("SELECT source,proof FROM sync_imports WHERE adapter=? AND retired=0",adapter) { it.text(0)!! to it.bytes(1)!! }
fun retired(adapter: String, source: String) = sql.transaction {
sql.exec("UPDATE sync_imports SET retired=1 WHERE adapter=? AND source=?",adapter,source)
sql.exec("UPDATE lifecycle_jobs SET retired=1 WHERE adapter=? AND source=?",adapter,source)
}
fun window(adapter: String, owner: String): List<Entry> = sql.query(
"SELECT id,document,payload,checkpoint,source,retired FROM lifecycle_jobs WHERE adapter=? AND owner=? AND done=0 ORDER BY sequence LIMIT ?",adapter,owner,WINDOW) { row ->
val id=row.text(0)!!
Entry(id,adapter,owner,row.text(1)!!,row.bytes(2)!!,
sql.query("SELECT phase FROM lifecycle_acks WHERE id=?",id) { it.text(0)!! }.toSet(),row.bytes(3)!!,row.text(4),row.long(5)==1L)
}
fun acknowledge(id: String, phase: String, checkpoint: ByteArray) = sql.transaction {
require(phase in PHASES && checkpoint.size <= MAX_BYTES)
sql.exec("UPDATE lifecycle_jobs SET checkpoint=? WHERE id=?",checkpoint,id)
sql.exec("INSERT OR IGNORE INTO lifecycle_acks VALUES (?,?)",id,phase)
}
fun checkpoint(id: String, checkpoint: ByteArray) {
require(checkpoint.size <= MAX_BYTES)
sql.exec("UPDATE lifecycle_jobs SET checkpoint=? WHERE id=?",checkpoint,id)
}
fun finish(id: String) {
check(sql.query("SELECT COUNT(*) FROM lifecycle_acks WHERE id=?",id) { it.long(0)!! }.single()==PHASES.size.toLong())
// Imported payloads and provenance remain as a migration backup after delivery.
sql.transaction {
val imported=sql.query("SELECT source FROM lifecycle_jobs WHERE id=?",id) { it.text(0) }.firstOrNull()!=null
if(imported) sql.exec("UPDATE lifecycle_jobs SET done=1 WHERE id=?",id)
else { sql.exec("DELETE FROM lifecycle_acks WHERE id=?",id); sql.exec("DELETE FROM lifecycle_jobs WHERE id=?",id) }
}
}
fun pending(adapter: String, owner: String): Int = sql.query("SELECT COUNT(*) FROM lifecycle_jobs WHERE adapter=? AND owner=? AND done=0",adapter,owner) { it.long(0)!!.toInt() }.single()
fun pending(): Int = sql.query("SELECT COUNT(*) FROM lifecycle_jobs WHERE done=0") { it.long(0)!!.toInt() }.single()
fun contains(id: String): Boolean = sql.query("SELECT 1 FROM lifecycle_jobs WHERE id=? AND done=0",id) { true }.isNotEmpty()
fun records(adapter: String, owner: String): List<Pair<String,Map<String,Any?>>> = sql.query("SELECT document,body FROM sync_records WHERE adapter=? AND owner=? ORDER BY rowid DESC LIMIT 300",adapter,owner) {
val raw=LuaValue.parse(it.bytes(1)!!) as? Map<*, *>
it.text(0)!! to raw.orEmpty().entries.associate { e -> e.key.toString() to e.value }
}
fun record(adapter: String, owner: String, document: String): Map<*, *> = sql.query(
"SELECT body FROM sync_records WHERE adapter=? AND owner=? AND document=?",adapter,owner,document) { LuaValue.parse(it.bytes(0)!!) as? Map<*, *> }.firstOrNull().orEmpty()
fun record(adapter: String, owner: String, document: String, record: Map<String,Any?>) {
val body=LuaValue.encode(record); require(body.size <= 65536)
sql.exec("INSERT OR REPLACE INTO sync_records VALUES (?,?,?,?)",adapter,owner,document,body)
}
}

/** Opaque adapter checkpoint returned after one phase. A deferred phase remains unacknowledged. */
data class SyncPhaseResult(val checkpoint: ByteArray, val complete: Boolean = true)
Loading
Loading