Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
8 changes: 8 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,11 @@ CrossInk 2.x bridge and the later stable BookSync releases become available (`xt
- **UI calls BookSync's library interface.** Binding on the KOReader plugin, Android companion
and Xteink overlay. Maintainer rule 2026-11-26, verbatim:
"all API calls the UI makes should be to our own interface so that we can plumb BookOrbit / Grimmory separately."
Personal reading data follows the maintainer ruling (2026-11-26), verbatim:
"I would build it so that all UI calls for that kind of data go through our interface, which then chooses where to fetch / aggregate data from. We start with on-device info and can extend to server but the ui never needs to change."
Request a personal-data kind, never a source. Companion providers declare capabilities,
merge in registration order and deduplicate neutral identities; missing/failing providers
are skipped. Future remote providers register inside their server adapter, never in UI.
UI code calls only BookSync's library interface; BookOrbit and Grimmory are adapters behind it.
Gate server-dependent features on adapter capabilities, never server identity. Filters are
neutral objects that adapters translate, with local fallback on the cached catalog.
Expand Down Expand Up @@ -80,6 +85,9 @@ CrossInk 2.x bridge and the later stable BookSync releases become available (`xt

## Screen and widget performance budgets

Highlight and A year ago also inherit one-row/16 KiB budgets. Companion providers own
sidecar parsing, calendar selection, aggregation and dedupe; Lua never scans personal data.

Local optional widgets inherit one-row/16 KiB budgets too: companion-owned vocabulary selection
and reading messages; native frontlight scalars only in Library. Paint never scans local history.

Expand Down
2 changes: 1 addition & 1 deletion ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ CrossInk 2.x only; 1.6 is retired).
| Outcome | Platforms | Status |
| Finish the server-free catalog cutover: companion-owned copies, grouping, settings recommendations and end-of-book snapshots/outboxes. | Android (Xteink deferred under Android-first ruling) | building on feature/0.12 (F12-Q2 step 4) |
|---|---|---|
| Word of the day, local Reading buddy and hardware Light picker widgets; Highlight and A year ago await authorized server snapshots. | Android; X4 Pro/X4/X3 deferred to firmware | building (device acceptance pending) |
| Word of the day, local Reading buddy, hardware Light, Highlight and A year ago picker widgets through companion projections and a source-aggregating personal-data interface. | Android; X4 Pro/X4/X3 deferred to firmware | building (device acceptance pending) |
| Server-free Android catalog operations: companion-owned covers, refresh, copies, recommendations and end-of-book snapshots and commands. | Android; X4 Pro, X4, X3 later under Android-first ruling | building: covers, mirror planning and query/store reads migrated; copies, grouping, recommendations and finish pending |
| Independent optional account, sync and OPDS logins, encrypted credentials, origin-aware sign-out and account-wide reading statistics through the library interface. | Android; X4 Pro, X4, X3 later | building (Android F12-K foundation and F12-N plugin screens implemented; device acceptance and firmware follow) |
| Configure one Book list widget with presets, paged counted sources and local Custom filters in the Home editor. | Android building; X4 Pro, X4, X3 follow Android | building (approved design rev 16; device acceptance pending) |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,16 @@ import java.security.MessageDigest
* scans and parses native sidecars; LibraryReadModel still bounds every published window. */
class DeviceLibrary(private val roots: List<File>) : ServerAdapter {
override val id = "device"
companion object { const val OWNER = "device-local" }
private val books by lazy {
roots.distinctBy { it.canonicalPath }.flatMap { root ->
if (!root.isDirectory) emptyList() else root.walkTopDown().onEnter {
companion object {
const val OWNER = "device-local"
fun files(roots: List<File>): Sequence<File> = roots.distinctBy { it.canonicalPath }.asSequence().flatMap { root ->
if (!root.isDirectory) emptySequence() else root.walkTopDown().onEnter {
BulkWork.checkpoint()
Places.inside(it,listOf(root)) != null && !java.nio.file.Files.isSymbolicLink(it.toPath()) && !it.name.endsWith(".sdr")
}.filter { it.isFile && it.extension.lowercase() in setOf("epub","pdf","mobi","azw","azw3","fb2","djvu","cbz","cbr","txt") &&
Places.inside(it,listOf(root)) != null }.map(::book).toList()
}.distinctBy { it["key"] }
}.filter { it.isFile && it.extension.lowercase() in setOf("epub","pdf","mobi","azw","azw3","fb2","djvu","cbz","cbr","txt") && Places.inside(it,listOf(root)) != null }
}.distinctBy { it.canonicalPath }
}
private val books by lazy { files(roots).map(::book).toList() }
private fun sidecar(file: File) = File(file.parentFile,"${file.nameWithoutExtension}.sdr")
private fun book(file: File): Map<String,Any?> {
BulkWork.checkpoint()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
// SPDX-License-Identifier: MIT
package net.fledgewing.orbitcompanion

import java.io.File
import java.time.Instant
import java.time.ZoneId

/** Read-only borrowed device data; executed solely on the companion worker. */
class DevicePersonalReading(private val roots: List<File>, private val statistics: File,
private val open: (File) -> Sql = { AndroidSql(it, readOnly = true) }) : PersonalReadingSource {
override val capabilities = PersonalReading.KINDS
override fun read(kind: String, now: Long): List<PersonalReadingRecord> = when(kind) {
"highlight" -> highlights()
"yearago" -> if (!statistics.isFile) emptyList() else open(statistics).use { yearago(it, now) }
else -> emptyList()
}
private fun highlights(): List<PersonalReadingRecord> {
val out = linkedMapOf<String, PersonalReadingRecord>()
for (book in DeviceLibrary.files(roots).sortedBy { it.canonicalPath }) {
BulkWork.checkpoint()
val file = File(book.parentFile, "${book.nameWithoutExtension}.sdr/metadata.${book.extension}.lua")
if (!file.isFile || file.length() > 1048576 || Places.inside(file, roots) == null) continue
val data = try {
val literal = file.readText(Charsets.ISO_8859_1).replaceFirst(Regex("\\A(?:--[^\\n]*\\n)?\\s*return\\s+"), "")
LuaValue.parse(literal.toByteArray(Charsets.ISO_8859_1)) as? Map<*, *>
} catch (e: Exception) { if(e is InterruptedException) throw e; null } ?: continue
val title = (data["doc_props"] as? Map<*, *>)?.get("title") as? String ?: LuaValue.str(book.nameWithoutExtension)
val annotations = when(val a=data["annotations"]) { is List<*> -> a; is Map<*,*> -> a.entries.sortedBy { it.key.toString() }.map { it.value }; else -> emptyList<Any>() }
for (raw in annotations) {
val a = raw as? Map<*, *> ?: continue
val passage = a["text"] as? String ?: continue
if (passage.isBlank() || a["pos0"] == null) continue // exclude bookmarks and notes without a passage
val identity = book.canonicalPath + ":" + a["pos0"] + ":" + passage
out.putIfAbsent(identity, PersonalReadingRecord(identity, mapOf(
"passage" to LuaValue.boundedText(LuaValue.utf8(passage), 900),
"source" to LuaValue.boundedText(LuaValue.utf8(title), 160),
"book" to mapOf("title" to LuaValue.boundedText(LuaValue.utf8(title),160), "local_path" to LuaValue.str(book.canonicalPath)))))
}
}
return out.values.toList()
}
companion object {
/** Same calendar day one year back in the device zone; Feb 29 clamps to Feb 28.
* SQL aggregates every visit, but decodes only the selected book's single display row. */
fun yearago(db: Sql, now: Long, zone: ZoneId = ZoneId.systemDefault()): List<PersonalReadingRecord> {
val day = Instant.ofEpochSecond(now).atZone(zone).toLocalDate().minusYears(1)
val start = day.atStartOfDay(zone).toEpochSecond()
val end = day.plusDays(1).atStartOfDay(zone).toEpochSecond()
return db.query("""WITH visits AS (
SELECT p.id_book,p.page,p.start_time,p.rowid AS visit_id,
MIN(?,p.start_time+MIN(p.duration,86400))-MAX(?,p.start_time) AS seconds
FROM page_stat_data p WHERE p.duration>0 AND p.start_time>0 AND p.start_time<?
AND p.start_time+MIN(p.duration,86400)>?)
SELECT b.id,substr(b.title,1,160),SUM(p.seconds),
(SELECT q.page FROM visits q WHERE q.id_book=b.id ORDER BY q.start_time DESC,q.visit_id DESC LIMIT 1)
FROM visits p JOIN book b ON b.id=p.id_book GROUP BY b.id
ORDER BY SUM(p.seconds) DESC,b.id LIMIT 1""",end,start,end,start) {
val minutes = (it.long(2) ?: 0)/60
val page = it.long(3)
PersonalReadingRecord("history:${it.long(0)}:$day", mapOf("source" to "On this reader",
"book_title" to LuaValue.str(it.text(1) ?: "Unknown book"), "minutes" to minutes, "days_read" to 1,
"stop_page" to page, "summary" to LuaValue.str("$minutes min · 1 day · " + (page?.let { n -> "stopped at p. $n" } ?: "Position unavailable")),
"date" to day.toString()))
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ class LibraryReadModel(
private val accountStats: (String) -> Map<*, *>? = { null },
private val vocabulary: () -> java.io.File = { java.io.File(SleepScreen.dir().parentFile, "vocabulary_builder.sqlite3") },
private val adapter: ServerAdapter? = null,
private val personalDevice: (() -> PersonalReadingSource)? = null,
) {
companion object {
const val MAX_BYTES = 16384
Expand All @@ -33,6 +34,11 @@ class LibraryReadModel(
java.io.File(store.root.parentFile?.parentFile?.parentFile ?: store.root,it)
} + DeviceStorage.downloadRoot(store.root)) else adapter ?: ServerAdapters.forStore(store, clock = clock,
fallbackReadingStats = fallbackReadingStats, accountState = accountState, accountStats = accountStats)
val personal by lazy {
val roots = DeviceStorage.folders.map { java.io.File(store.root.parentFile?.parentFile?.parentFile ?: store.root,it) } + DeviceStorage.downloadRoot(store.root)
PersonalReading(listOf(personalDevice?.invoke() ?: DevicePersonalReading(roots, java.io.File(store.root.parentFile,"statistics.sqlite3"))) +
if (local) emptyList() else projection.personalReadingSources(owner))
}
val localStats by lazy { readingStats() }
val storage by lazy { DeviceStorage(store, projection) }
val power by lazy { battery() }
Expand All @@ -49,6 +55,7 @@ class LibraryReadModel(
"storage.summary" -> storage.summary(owner,(args["exclude_path"] as? String)?.let(LuaValue::utf8),(args["current_folder"] as? String)?.let(LuaValue::utf8))
"reader.controls" -> ReaderControls.project(args["native"] as? Map<*, *> ?: emptyMap<Any, Any>())

"personal.reading" -> personal.window(args["kind"] as? String ?: "", clock())
"reading.stats" -> stats
"local.word" -> LocalWidgets.word(vocabulary(), clock())
"local.buddy" -> LocalWidgets.buddy(localStats)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// SPDX-License-Identifier: MIT
package net.fledgewing.orbitcompanion

/** Worker-only providers return neutral records. Registration order wins duplicate identities.
* Providers may read saved data only: acquisition is a separate worker operation. */
interface PersonalReadingSource {
val capabilities: Set<String>
fun read(kind: String, now: Long): List<PersonalReadingRecord>
}
data class PersonalReadingRecord(val identity: String, val fields: Map<String, Any?>)

class PersonalReading(private val sources: List<PersonalReadingSource>) {
companion object { val KINDS = setOf("highlight", "yearago") }
fun window(kind: String, now: Long): Map<String, Any?> {
require(kind in KINDS)
val merged = linkedMapOf<String, PersonalReadingRecord>()
var succeeded = false
for (source in sources) {
if (kind !in source.capabilities) continue
try {
val records = source.read(kind, now)
records.forEach { merged.putIfAbsent(it.identity, it) }
succeeded = true
} catch (e: Exception) { if (e is InterruptedException) throw e }
}
val day = java.time.Instant.ofEpochSecond(now).atZone(java.time.ZoneId.systemDefault()).toLocalDate().toEpochDay()
val records = merged.values.toList()
// Round-robin over a stable pool: no repetition within a complete cycle, no process state.
val selected = if (records.isEmpty()) null else records[if (kind == "highlight") Math.floorMod(day, records.size.toLong()).toInt() else 0]
val result = (selected?.fields ?: emptyMap()) + mapOf("state" to if (selected != null) "ready" else if (succeeded) "empty" else "error",
"message" to LuaValue.str(if (kind == "yearago") "No reading from a year ago on this device yet" else "Save a highlight while reading."),
"row_count" to 1, "freshness" to mapOf("saved" to succeeded))
return if (LuaValue.encode(result).size <= LibraryReadModel.MAX_BYTES) result
else mapOf("state" to "error", "row_count" to 1, "message" to "Reading data exceeds this widget's budget")
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import java.io.File
* normalize protocol data before returning it; unsupported operations are explicit. Renderers
* use LibraryReadModel, never this transport-facing interface. */
interface ServerAdapter {
fun personalReadingSources(owner: String): List<PersonalReadingSource> = emptyList()
fun recommendedSettings(): List<Map<String,Any?>> = emptyList()
val id: String
fun project(owner: String, request: Map<*, *>): Map<String, Any?> = unsupported()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,33 @@ class LocalWidgetsTest {
}
val adapter=object:ServerAdapter {
override val id="fixture"
override fun personalReadingSources(owner:String)=listOf(object:PersonalReadingSource {
override val capabilities=setOf("highlight","yearago")
override fun read(kind:String,now:Long)=listOf(PersonalReadingRecord("toy",mapOf("passage" to "Toy saved passage")))
})
override fun project(owner:String,request:Map<*,*>):Map<String,Any?> = error("no server projection")
}
var reads=0
val model=LibraryReadModel(store,{86400},{},readingStats={reads++; mapOf("state" to "empty")},
vocabulary={java.io.File(dir,"missing.sqlite3")},adapter=adapter)
vocabulary={java.io.File(dir,"missing.sqlite3")},adapter=adapter,personalDevice={object:PersonalReadingSource {
override val capabilities=PersonalReading.KINDS
override fun read(kind:String,now:Long)=emptyList<PersonalReadingRecord>()
}})
val requests=listOf("local.word","local.buddy","local.light").map { op ->
String(LuaValue.encode(mapOf("op" to op,"limit" to 1,"bytes" to 16384)),Charsets.ISO_8859_1)
}
val personalRequests=listOf("highlight","yearago").map { kind ->
String(LuaValue.encode(mapOf("op" to "personal.reading","kind" to kind,"limit" to 1,"bytes" to 16384)),Charsets.ISO_8859_1)
}
assertTrue(model.publish("fixture",personalRequests))
val personal=sql.query("SELECT body FROM library_views WHERE owner=?","fixture") { LuaValue.parse(it.bytes(0)!!) as Map<*,*> }
assertEquals(2,personal.size); assertTrue(personal.all { it["passage"]=="Toy saved passage" })
assertTrue(model.publish(DeviceLibrary.OWNER,personalRequests))
val localPersonal=sql.query("SELECT body FROM library_views WHERE owner=?",DeviceLibrary.OWNER) { LuaValue.parse(it.bytes(0)!!) as Map<*,*> }
assertTrue(localPersonal.all { it["state"]=="empty" && it["passage"]==null })
assertTrue(model.publish("fixture",requests)); assertEquals(1,reads)
val rows=sql.query("SELECT body FROM library_views") { it.bytes(0)!! }
assertEquals(3,rows.size)
assertEquals(7,rows.size)
for(body in rows) {
assertTrue(body.size<=16384)
val result=LuaValue.parse(body) as Map<*,*>
Expand All @@ -39,7 +55,7 @@ class LocalWidgetsTest {
assertFalse(model.publish("another-owner",requests))
assertTrue(model.publish(DeviceLibrary.OWNER,requests))
assertEquals(2,reads)
assertEquals(3,sql.query("SELECT body FROM library_views WHERE owner=?",DeviceLibrary.OWNER) { it.bytes(0)!! }.size)
assertEquals(5,sql.query("SELECT body FROM library_views WHERE owner=?",DeviceLibrary.OWNER) { it.bytes(0)!! }.size)
} } finally { dir.deleteRecursively() }
}
@Test fun vocabularyIsOneBoundedDailyRecordWithContextAndSource() {
Expand Down
Loading
Loading