Skip to content

Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.

Address PR review: compaction, graph threading, link resolution (#156)

Rishabh Bajpaie3f99a05ede4
diff --git a/app/src/main/java/com/gotcha/agent/AgentEngine.kt b/app/src/main/java/com/gotcha/agent/AgentEngine.kt
index 3f368f1..17d52aa 100644
--- a/app/src/main/java/com/gotcha/agent/AgentEngine.kt
+++ b/app/src/main/java/com/gotcha/agent/AgentEngine.kt
@@ -500,6 +500,11 @@ class AgentEngine(
val summary = response.choices.firstOrNull()?.message?.textContent
if (!summary.isNullOrBlank()) {
history.clear()
+ // Compaction must not drop the memory context the Index 0
+ // pointer promises: restore the startup message first so the
+ // request that triggered compaction still carries SOUL.md and
+ // MEMORY.md (issue #156 review).
+ MemoryStore.buildStartupMessage()?.let { history.add(it) }
history.add(ChatMessage(role = "assistant", content = JsonPrimitive(summary)))
if (preserveLast != null) {
history.add(preserveLast)
diff --git a/app/src/main/java/com/gotcha/data/MemoryStore.kt b/app/src/main/java/com/gotcha/data/MemoryStore.kt
index 288185e..352c375 100644
--- a/app/src/main/java/com/gotcha/data/MemoryStore.kt
+++ b/app/src/main/java/com/gotcha/data/MemoryStore.kt
@@ -112,7 +112,7 @@ object MemoryStore {
appendLine("<soul_md>")
if (soul != null) {
appendLine(soul.text)
- if (soul.truncated > 0) appendLine("... truncated, ${soul.truncated} chars omitted ...")
+ if (soul.truncated) appendLine("... truncated, showing first $SOUL_CAP_CHARS chars ...")
} else {
appendLine("(missing - continue with Personal Info)")
}
@@ -121,7 +121,7 @@ object MemoryStore {
appendLine("<memory_md>")
if (index != null) {
appendLine(index.text)
- if (index.truncated > 0) appendLine("... truncated, ${index.truncated} chars omitted ...")
+ if (index.truncated) appendLine("... truncated, showing first $MEMORY_CAP_CHARS chars ...")
} else {
appendLine("(missing - continue with Personal Info)")
}
@@ -188,8 +188,10 @@ object MemoryStore {
/**
* Builds the node-link graph: one node per markdown file plus one per raw
- * file, edges from [[links]] resolved against relative paths first
- * (areas/work.md) then bare names (work.md), deduplicated.
+ * file, edges from [[links]] resolved source-relative first
+ * (notes/plan from notes/trip.md), then vault-relative (areas/work.md),
+ * then a bare name only when it is unique. Dangling and self links and
+ * ambiguous bare names produce no edge. Deduplicated.
*
* Node ids are memory-relative paths (areas/work.md, raw/memo.mp3), so two
* sections can hold same-named files without colliding. Link targets are
@@ -199,13 +201,7 @@ object MemoryStore {
fun buildGraph(snapshot: SecondBrainSnapshot): BrainGraph {
val nodes = mutableListOf<BrainNode>()
val byFull = mutableMapOf<String, String>()
- val byBase = mutableMapOf<String, String>()
fun norm(path: String): String = path.lowercase().removeSuffix(".md").removeSuffix(".markdown")
- fun addNode(id: String, label: String, kind: String) {
- nodes.add(BrainNode(id, label, kind))
- byFull.putIfAbsent(norm(id), id)
- byBase.putIfAbsent(norm(id.substringAfterLast('/')), id)
- }
fun relId(file: BrainFile, fallback: String): String {
val abs = file.absolutePath
if (abs.isNotBlank()) {
@@ -218,6 +214,10 @@ object MemoryStore {
}
data class Source(val id: String, val file: BrainFile)
val sources = mutableListOf<Source>()
+ fun addNode(id: String, label: String, kind: String) {
+ nodes.add(BrainNode(id, label, kind))
+ byFull.putIfAbsent(norm(id), id)
+ }
fun addSource(file: BrainFile?, fallbackId: String, label: String, kind: String) {
if (file == null) return
val id = relId(file, fallbackId)
@@ -231,16 +231,34 @@ object MemoryStore {
snapshot.people.forEach { addSource(it, "people/${it.name}", it.name.removeSuffix(".md"), "person") }
snapshot.notes.forEach { addSource(it, "notes/${it.name}", it.name.removeSuffix(".md"), "note") }
snapshot.raw.forEach { addSource(it, "raw/${it.name}", it.name, "raw") }
- fun resolve(target: String): String? {
- val normTarget = norm(target.trim())
- if (normTarget.isEmpty()) return null
- return byFull[normTarget] ?: byBase[normTarget] ?: byBase[normTarget.substringAfterLast('/')]
+ fun resolve(target: String, sourceId: String): String? {
+ val raw = target.trim()
+ if (raw.isEmpty()) return null
+ val sourceDir = sourceId.substringBeforeLast('/', "")
+ // (a) Relative to the source file's directory, then (b) vault-relative.
+ val candidates = buildList {
+ if (sourceDir.isNotEmpty()) {
+ add("$sourceDir/$raw")
+ add("$sourceDir/$raw.md")
+ add("$sourceDir/$raw.markdown")
+ }
+ add(raw)
+ add("$raw.md")
+ add("$raw.markdown")
+ }
+ candidates.forEach { candidate ->
+ byFull[norm(candidate)]?.let { return it }
+ }
+ // (c) Bare-name fallback only when it names exactly one node.
+ val base = norm(raw).substringAfterLast('/')
+ val matches = nodes.filter { norm(it.id).substringAfterLast('/') == base }.map { it.id }
+ return matches.singleOrNull()
}
val edges = mutableSetOf<BrainEdge>()
sources.forEach { source ->
if (!source.file.isMarkdown) return@forEach
parseWikiLinks(fullTextForLinks(source.file)).forEach { target ->
- val toId = resolve(target)
+ val toId = resolve(target, source.id)
if (toId != null && toId != source.id) edges.add(BrainEdge(source.id, toId))
}
}
@@ -408,7 +426,7 @@ object MemoryStore {
return try {
if (!dir.exists() || !dir.isDirectory) return emptyList()
dir.listFiles()
- ?.filter { it.isFile && it.name.endsWith(".md") }
+ ?.filter { it.isFile && it.name.substringAfterLast('.', "").lowercase() == "md" }
?.sortedBy { it.name.lowercase() }
?.mapNotNull { loadBrainFile(it) }
.orEmpty()
@@ -431,20 +449,20 @@ object MemoryStore {
}
}
- internal data class CappedText(val text: String, val truncated: Int)
+ internal data class CappedText(val text: String, val truncated: Boolean)
+ /**
+ * Bounded read for session startup: streams at most cap+1 chars so a huge
+ * or malformed file can never stall a run or exhaust the heap.
+ */
internal fun readCapped(file: File, cap: Int): CappedText? {
- return try {
- if (!file.exists()) return null
- val raw = file.readText().trim()
- if (raw.isEmpty()) return null
- if (raw.length <= cap) {
- CappedText(raw, 0)
- } else {
- CappedText(raw.take(cap), raw.length - cap)
- }
- } catch (_: Exception) {
- null
+ val text = readUpTo(file, cap) ?: return null
+ val trimmed = text.trim()
+ if (trimmed.isEmpty()) return null
+ return if (text.length <= cap) {
+ CappedText(trimmed, false)
+ } else {
+ CappedText(trimmed.take(cap), true)
}
}
diff --git a/app/src/main/java/com/gotcha/ui/SecondBrainScreen.kt b/app/src/main/java/com/gotcha/ui/SecondBrainScreen.kt
index 3571d4c..8f114be 100644
--- a/app/src/main/java/com/gotcha/ui/SecondBrainScreen.kt
+++ b/app/src/main/java/com/gotcha/ui/SecondBrainScreen.kt
@@ -40,6 +40,7 @@ import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.drawText
import androidx.compose.ui.text.font.FontFamily
@@ -189,7 +190,52 @@ fun SecondBrainScreen(onBack: () -> Unit) {
*/
@Composable
private fun SecondBrainGraphView(snapshot: MemoryStore.SecondBrainSnapshot) {
- val graph = remember(snapshot) { MemoryStore.buildGraph(snapshot) }
+ // Graph building re-reads files and runs the quadratic layout: off the
+ // main thread with a loading state so big vaults cannot freeze Settings.
+ var prepared by remember(snapshot) { mutableStateOf<PreparedGraph?>(null) }
+ LaunchedEffect(snapshot) {
+ prepared = withContext(Dispatchers.Default) {
+ val graph = MemoryStore.buildGraph(snapshot)
+ val indexById = graph.nodes.mapIndexed { index, node -> node.id to index }.toMap()
+ val pairs = graph.edges.mapNotNull { edge ->
+ val a = indexById[edge.fromId]
+ val b = indexById[edge.toId]
+ if (a != null && b != null) a to b else null
+ }
+ val iterations = (16000 / maxOf(1, graph.nodes.size)).coerceIn(40, 160)
+ val points = MemoryStore.forceLayout(graph.nodes.size, pairs, iterations)
+ val depths = List(graph.nodes.size) { nodeZ(it) }
+ // Turn the flat layout cloud onto its side: spread runs front-to-back
+ // (z) so the starting side view shows the full cloud, depth runs across.
+ val sideways = points.indices.map { i -> Offset(depths[i], points[i].y) }
+ val sidewaysDepths = points.indices.map { i -> points[i].x }
+ val (confined, confinedZ) = MemoryStore.confineToBrain(sideways, sidewaysDepths)
+ PreparedGraph(graph, confined, confinedZ)
+ }
+ }
+ val ready = prepared
+ if (ready == null) {
+ Text(
+ stringResource(R.string.second_brain_graph_loading),
+ style = MaterialTheme.typography.bodyMedium,
+ modifier = Modifier.testTag("settings_second_brain_graph_loading")
+ )
+ return
+ }
+ GraphCanvas(snapshot = snapshot, prepared = ready)
+}
+
+private data class PreparedGraph(
+ val graph: MemoryStore.BrainGraph,
+ val layout: List<Offset>,
+ val layoutZ: List<Float>
+)
+
+@Composable
+private fun GraphCanvas(snapshot: MemoryStore.SecondBrainSnapshot, prepared: PreparedGraph) {
+ val graph = prepared.graph
+ val layout = prepared.layout
+ val layoutZ = prepared.layoutZ
var selectedId by remember(graph) { mutableStateOf<String?>(null) }
var zoom by remember(graph) { mutableStateOf(1f) }
// Starting view is a three-quarter turn: cerebellum and brainstem sit at
@@ -201,23 +247,6 @@ private fun SecondBrainGraphView(snapshot: MemoryStore.SecondBrainSnapshot) {
// True while a double-tap-drag is spinning the globe; the transform
// detector ignores slide input meanwhile so one motion never does both.
val yawLock = remember(graph) { mutableStateOf(false) }
- val placed = remember(graph) {
- val indexById = graph.nodes.mapIndexed { index, node -> node.id to index }.toMap()
- val pairs = graph.edges.mapNotNull { edge ->
- val a = indexById[edge.fromId]
- val b = indexById[edge.toId]
- if (a != null && b != null) a to b else null
- }
- val points = MemoryStore.forceLayout(graph.nodes.size, pairs)
- val depths = List(graph.nodes.size) { nodeZ(it) }
- // Turn the flat layout cloud onto its side: spread runs front-to-back
- // (z) so the starting side view shows the full cloud, depth runs across.
- val sideways = points.indices.map { i -> Offset(depths[i], points[i].y) }
- val sidewaysDepths = points.indices.map { i -> points[i].x }
- MemoryStore.confineToBrain(sideways, sidewaysDepths)
- }
- val layout: List<Offset> = placed.first
- val layoutZ: List<Float> = placed.second
val degree = remember(graph) {
graph.nodes.associate { node ->
node.id to graph.edges.count { it.fromId == node.id || it.toId == node.id }
@@ -629,11 +658,14 @@ private fun neuronScreenRadius(width: Float, height: Float): Float {
private data class BrainFiring(val edgeIdx: Int, val startMs: Long, val durationMs: Long, val reverse: Boolean)
/** Curve control point shared by thread drawing and pulse travel. */
+/** Curve control point: bend scales with the edge length (capped), never with
+ * canvas position, so equal links bend equally wherever they sit. */
private fun edgeControl(from: Offset, to: Offset): Offset {
val mid = (from + to) / 2f
val normal = Offset(-(to.y - from.y), to.x - from.x)
val normalLen = normal.getDistance().coerceAtLeast(1f)
- return mid + normal / normalLen * (from.getDistance() * 0.12f + 18f)
+ val edgeLen = (to - from).getDistance().coerceAtMost(400f)
+ return mid + normal / normalLen * (edgeLen * 0.12f + 18f)
}
/** Point on a quadratic bezier at t, for segmented gradient edges. */
@@ -671,28 +703,6 @@ private fun androidx.compose.ui.graphics.drawscope.DrawScope.drawBrainShell(map:
620f * bump * cos(lat) * sin(lon)
)
}
- fun sampleSphere(
- center: OffsetTriple,
- radius: Float,
- lonSteps: Int = 16,
- latSteps: Int = 5
- ): List<OffsetTriple> {
- val out = mutableListOf<OffsetTriple>()
- for (li in 0 until lonSteps) {
- val lon = 2f * Math.PI.toFloat() * li / lonSteps
- for (si in 0..latSteps) {
- val lat = -1.2f + 2.4f * si / latSteps
- out.add(
- OffsetTriple(
- center.x + radius * cos(lat) * cos(lon),
- center.y + radius * sin(lat),
- center.z + radius * cos(lat) * sin(lon)
- )
- )
- }
- }
- return out
- }
// Sample the surface, project, silhouette via convex hull.
val samples = mutableListOf<Offset>()
val lonSteps = 28
@@ -905,7 +915,10 @@ private fun BrainSection(heading: String, file: MemoryStore.BrainFile, tag: Stri
fontWeight = FontWeight.Bold,
modifier = Modifier
.fillMaxWidth()
- .clickable { expanded = !expanded }
+ .clickable(
+ role = Role.Button,
+ onClickLabel = if (expanded) "Collapse" else "Expand"
+ ) { expanded = !expanded }
.padding(vertical = 4.dp)
)
if (expanded) {
@@ -929,7 +942,10 @@ private fun BrainFileList(heading: String, files: List<MemoryStore.BrainFile>, t
fontWeight = FontWeight.Bold,
modifier = Modifier
.fillMaxWidth()
- .clickable { expanded = !expanded }
+ .clickable(
+ role = Role.Button,
+ onClickLabel = if (expanded) "Collapse" else "Expand"
+ ) { expanded = !expanded }
.padding(vertical = 4.dp)
)
if (expanded) {
@@ -948,7 +964,10 @@ private fun BrainFileList(heading: String, files: List<MemoryStore.BrainFile>, t
fontWeight = FontWeight.Medium,
modifier = Modifier
.fillMaxWidth()
- .clickable { fileExpanded = !fileExpanded }
+ .clickable(
+ role = Role.Button,
+ onClickLabel = if (fileExpanded) "Collapse" else "Expand"
+ ) { fileExpanded = !fileExpanded }
.padding(vertical = 2.dp)
.testTag("settings_second_brain_${tag}_$index")
)
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index ad9d6b4..fc659fa 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -86,6 +86,7 @@
<string name="second_brain_open_failed">No app on this phone can open that file type.</string>
<string name="second_brain_tab_list">List</string>
<string name="second_brain_tab_graph">Graph</string>
+ <string name="second_brain_graph_loading">Growing the brain…</string>
<string name="second_brain_graph_hint">Drag to slide, two fingers to zoom and rotate, double-tap and drag to spin the brain. Tap a neuron to focus its connections, double-tap to reset.</string>
<string name="second_brain_graph_reset">Reset view</string>
<string name="second_brain_graph_neighbors"> · %1$d connected</string>
diff --git a/app/src/test/java/com/gotcha/agent/AgentEngineOverheadTest.kt b/app/src/test/java/com/gotcha/agent/AgentEngineOverheadTest.kt
index 922d5e3..d1e8dca 100644
--- a/app/src/test/java/com/gotcha/agent/AgentEngineOverheadTest.kt
+++ b/app/src/test/java/com/gotcha/agent/AgentEngineOverheadTest.kt
@@ -243,6 +243,50 @@ class AgentEngineOverheadTest {
engine.history.any { it.role == "user" && it.textContent == "hi" }
)
}
+
+ /**
+ * Issue #156 review — successful compaction must not drop the memory
+ * context for the request that triggered it. The outgoing model request
+ * after compaction carries exactly one [memory_startup] message.
+ */
+ @Test
+ fun `compaction preserves the memory startup message`() = runTest {
+ // Point memory at an isolated dir so the test never touches real files.
+ val memoryDir = File(workDir, "memory-test").apply { mkdirs() }
+ val previousRoot = runCatching { com.gotcha.data.GotchaStorage.rootPath }.getOrNull()
+ com.gotcha.data.GotchaStorage.rootPath = File(memoryDir, "Gotcha").absolutePath
+ try {
+ com.gotcha.data.MemoryStore.ensureDefaults(Settings())
+ engine.tokenCount = (Settings().maxContextTokens * 0.85).toInt()
+ enqueueCompactionSummary("Compacted.")
+ enqueueTextReplyWithoutUsage("done")
+ engine.history += com.gotcha.llm.ChatMessage(
+ role = "user",
+ content = kotlinx.serialization.json.JsonPrimitive("hi")
+ )
+ engine.run(AgentMode.OPERATOR)
+ // Two server hits: the compaction summary call, then the real turn.
+ assertEquals(2, server.requestCount)
+ server.takeRequest()
+ val mainRequest = server.takeRequest().body.readUtf8()
+ val histDump = engine.history.map { m -> m.role + ":" + m.textContent.contains(com.gotcha.data.MemoryStore.STARTUP_MARKER) }
+ // Count real startup messages (content starting with the marker),
+ // not the pointer block merely naming it.
+ val startupHits = "\"content\":\"\\[memory_startup\\]".toRegex()
+ .findAll(mainRequest).count()
+ assertEquals(
+ "post-compaction request must carry exactly one memory startup message; history=$histDump",
+ 1,
+ startupHits
+ )
+ } finally {
+ if (previousRoot != null) {
+ com.gotcha.data.GotchaStorage.rootPath = previousRoot
+ } else {
+ com.gotcha.data.GotchaStorage.resetRootPathForTests()
+ }
+ }
+ }
}
/**
diff --git a/app/src/test/java/com/gotcha/data/MemoryStoreTest.kt b/app/src/test/java/com/gotcha/data/MemoryStoreTest.kt
index 07f9a4c..a9f7437 100644
--- a/app/src/test/java/com/gotcha/data/MemoryStoreTest.kt
+++ b/app/src/test/java/com/gotcha/data/MemoryStoreTest.kt
@@ -151,6 +151,45 @@ class MemoryStoreTest {
assertEquals("areas/work.md", edge!!.toId)
}
+ @Test
+ fun `bare links prefer the source directory`() {
+ MemoryStore.ensureDefaults(Settings())
+ GotchaStorage.memoryNotesDir().mkdirs()
+ GotchaStorage.memoryPeopleDir().mkdirs()
+ File(GotchaStorage.memoryNotesDir(), "plan.md").writeText("Note plan.")
+ File(GotchaStorage.memoryPeopleDir(), "plan.md").writeText("Person plan.")
+ File(GotchaStorage.memoryNotesDir(), "trip.md").writeText("Trip. See [[plan]].")
+ val snap = MemoryStore.loadSnapshot()
+ val graph = MemoryStore.buildGraph(snap)
+ val edge = graph.edges.singleOrNull { it.fromId == "notes/trip.md" }
+ assertNotNull(edge)
+ assertEquals("notes/plan.md", edge!!.toId)
+ }
+
+ @Test
+ fun `ambiguous bare names draw no edge`() {
+ MemoryStore.ensureDefaults(Settings())
+ GotchaStorage.memoryNotesDir().mkdirs()
+ GotchaStorage.memoryPeopleDir().mkdirs()
+ File(GotchaStorage.memoryNotesDir(), "plan.md").writeText("Note plan.")
+ File(GotchaStorage.memoryPeopleDir(), "plan.md").writeText("Person plan.")
+ File(GotchaStorage.memoryAreasDir(), "hub.md").writeText("Hub. See [[plan]].")
+ val snap = MemoryStore.loadSnapshot()
+ val graph = MemoryStore.buildGraph(snap)
+ assertTrue(graph.edges.none { it.fromId == "areas/hub.md" })
+ }
+
+ @Test
+ fun `startup read stays bounded on huge files`() {
+ MemoryStore.ensureDefaults(Settings())
+ val big = "y".repeat(2_000_000)
+ GotchaStorage.soulFile().writeText(big)
+ val capped = MemoryStore.readCapped(GotchaStorage.soulFile(), MemoryStore.SOUL_CAP_CHARS)
+ assertNotNull(capped)
+ assertTrue(capped!!.truncated)
+ assertTrue(capped.text.length <= MemoryStore.SOUL_CAP_CHARS)
+ }
+
@Test
fun `graph keeps same-named files apart`() {
MemoryStore.ensureDefaults(Settings())