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.
Persistent memory second brain foundation (#156)
Rishabh Bajpai708b756a27dd
diff --git a/app/src/main/assets/skills/memory.json b/app/src/main/assets/skills/memory.jsonnew file mode 100644index 0000000..9d6b76f--- /dev/null+++ b/app/src/main/assets/skills/memory.json@@ -0,0 +1,9 @@+{+ "id": "memory",+ "targetPackageNames": ["*"],+ "title": "Persistent Memory Skills",+ "description": "How to use Gotcha persistent memory under Gotcha/memory.",+ "requiresTools": ["read_file"],+ "keywords": ["memory", "soul", "remember", "persona", "user card"],+ "instructions": "Gotcha persistent memory lives under Gotcha/memory next to chats. SOUL.md is identity and behavior. MEMORY.md is the master map with navigational addresses, never facts. user.md is synced from Settings Personal Info. Detail lives in people/, areas/, notes/ with frontmatter title, area, type, tags, updated.\n\nSession start: SOUL.md and MEMORY.md are already injected as [memory_startup] with absolute paths. Follow them for the whole chat. Load detail files only when the task needs them, with read_file or grep using ABSOLUTE paths. Never resolve memory paths relative to the chat working directory, which is a different folder. Never bulk read the folder.\n\nWrites: OPERATOR only with write_file or edit using absolute paths. In MONITOR, read only, never write. One fact in one place, link by path, never copy-paste content. Keep SOUL.md under 1500 chars and MEMORY.md under 1500 chars so session start stays cheap. Never store passwords, OTPs, API tokens, or private keys in memory files.\n\nAreas start as People, Work, Personal, Health. You may rename, add, or archive an area by editing MEMORY.md plus its hub file in areas/. Update MEMORY.md counts and links when you add a note that starts or advances a thread."+}diff --git a/app/src/main/java/com/gotcha/GotchaApp.kt b/app/src/main/java/com/gotcha/GotchaApp.ktindex 44896a5..2a085ac 100644--- a/app/src/main/java/com/gotcha/GotchaApp.kt+++ b/app/src/main/java/com/gotcha/GotchaApp.kt@@ -61,6 +61,16 @@ class GotchaApp : Application() {// pdfbox ships its glyph tables as Android assets; the resource loader// needs a Context before the first PDF text extraction (DocumentParser).com.gotcha.tools.DocumentParser.init(this)+ // Persistent memory (issue #156): create Gotcha/memory/ early so it+ // exists as soon as the app opens, not only on the first agent run.+ // Best-effort: without All-files access mkdirs() fails and the agent+ // run path retries later.+ Thread {+ runCatching {+ val settings = com.gotcha.data.SettingsRepository(this).load()+ com.gotcha.data.MemoryStore.ensureDefaults(settings)+ }+ }.start()setupUncaughtExceptionHandler()}diff --git a/app/src/main/java/com/gotcha/agent/AgentEngine.kt b/app/src/main/java/com/gotcha/agent/AgentEngine.ktindex cfaf6a2..3f368f1 100644--- a/app/src/main/java/com/gotcha/agent/AgentEngine.kt+++ b/app/src/main/java/com/gotcha/agent/AgentEngine.kt@@ -8,6 +8,7 @@ import com.gotcha.connectors.ConnectorRegistryimport com.gotcha.data.ChatHistoryRepositoryimport com.gotcha.data.ChatSessionimport com.gotcha.data.GotchaStorage+import com.gotcha.data.MemoryStoreimport com.gotcha.data.RunSummaryimport com.gotcha.data.Settingsimport com.gotcha.data.ToolSummary@@ -293,6 +294,37 @@ class AgentEngine(GotchaLog.d(TAG) { "setupWorkingDir: ${dir.absolutePath}" }}+ /**+ * Ensures persistent memory exists and injects the one-time per-chat+ * startup message (issue #156). The message is inserted at the head of+ * history so later turns carry it as ordinary history and the Index 0+ * system prefix stays cache-stable. No-op when history already carries+ * it or when memory files are unavailable.+ */+ internal fun ensureMemoryStartup() {+ MemoryStore.ensureDefaults(settings)+ if (history.any { MemoryStore.isStartupMessage(it) }) return+ val startup = MemoryStore.buildStartupMessage() ?: return+ if (history.isEmpty()) {+ history.add(startup)+ } else {+ history.add(0, startup)+ }+ }++ /**+ * Repairs a trimmed-away startup message at send time (review P2). The+ * stored history keeps the marker, but [trimmedHistory] may drop it from+ * the head under context pressure. In that case return a fresh startup+ * message to prepend after the Index 0 prompt; null when trimming kept+ * it or when memory is unavailable.+ */+ internal fun memoryRepairMessage(trimmed: List<ChatMessage>): ChatMessage? {+ if (trimmed.any { MemoryStore.isStartupMessage(it) }) return null+ if (history.none { MemoryStore.isStartupMessage(it) }) return null+ return MemoryStore.buildStartupMessage()+ }+/** LLM-generated short title, once available; set once per session. */var generatedTitle: String? = nullprivate set@@ -528,6 +560,7 @@ class AgentEngine(// The full fix is threading a cwd through ToolExecutor into the file// tools (FileResolver already accepts one); deferred for now.setupWorkingDir()+ ensureMemoryStartup()checkAndCompactHistory(llm)// Anti-loop guard: if consecutive tool rounds produce the byte-identical// set of tool-call names + results (e.g. a tool that keeps returning the@@ -577,13 +610,15 @@ class AgentEngine(events.onActivity("Thinking…")// Build message array optimized for prompt caching:- // 1. System prompt at Index 0 (instructions + static environment + connected accounts + user profile)- // 2. Conversation history (4-turn screen observation retention window)+ // 1. System prompt at Index 0 (instructions + static environment + connected accounts + user profile + memory pointer)+ // 2. Conversation history, headed by the one-time [memory_startup] system message (4-turn screen observation retention window)// 3. Working directory + current timestamp (system message at tail)// 4. Active skills index summary (user message at tail)val messages = buildList {add(systemPromptMessage(agent))- addAll(cullOldObservations(trimmedHistory()))+ val trimmed = cullOldObservations(trimmedHistory())+ memoryRepairMessage(trimmed)?.let { add(it) }+ addAll(trimmed)add(runContextMessage())addAll(activeSkillsMessages(agent))}@@ -1690,6 +1725,8 @@ class AgentEngine(append("</env>")append("\n\n")append(buildUserProfileString())+ append("\n\n")+ append(MemoryStore.buildMemoryPointerBlock())// Operator-only: tells the model it may record durable personal facts. Gated here// (not in buildUserProfileString) so Monitor, whose contract is read-only, never// sees a directive to mutate settings — and the tool is withheld from it anyway.diff --git a/app/src/main/java/com/gotcha/agent/ChatRunner.kt b/app/src/main/java/com/gotcha/agent/ChatRunner.ktindex a9a23ff..9288479 100644--- a/app/src/main/java/com/gotcha/agent/ChatRunner.kt+++ b/app/src/main/java/com/gotcha/agent/ChatRunner.kt@@ -173,6 +173,7 @@ class ChatRunner(private val app: Application) : AgentEvents {?: return@AgentEngine ToolResult.ok("No material change — profile left as is.")settingsRepository.save(merged.updated)settings = merged.updated+ com.gotcha.data.MemoryStore.syncUserFile(merged.updated)// Surface the change to the user: the profile is silently re-injected into every// future prompt, so a prompt-injected update_user_profile call must not go// unnoticed. A TOOL bubble in the transcript gives the user a chance to catch@@ -790,6 +791,7 @@ class ChatRunner(private val app: Application) : AgentEvents {/** Re-reads settings; call after the settings screen saves. */fun refreshSettings() {settings = settingsRepository.load()+ com.gotcha.data.MemoryStore.ensureDefaults(settings)client = if (settings.isConfigured) {LLMClient(apiKey = settings.effectiveApiKey,diff --git a/app/src/main/java/com/gotcha/data/GotchaStorage.kt b/app/src/main/java/com/gotcha/data/GotchaStorage.ktindex d4ea5ba..f4198ae 100644--- a/app/src/main/java/com/gotcha/data/GotchaStorage.kt+++ b/app/src/main/java/com/gotcha/data/GotchaStorage.kt@@ -29,6 +29,11 @@ object GotchaStorage {get() = overrideRootPath ?: File(Environment.getExternalStorageDirectory(), "Gotcha").absolutePathset(value) { overrideRootPath = value }+ /** Clears a test override so later tests see the real default again. */+ fun resetRootPathForTests() {+ overrideRootPath = null+ }+enum class Kind(val dirName: String) {PICTURES("Pictures"),RECORDINGS("Recordings"),@@ -38,6 +43,13 @@ object GotchaStorage {fun root(): File = File(rootPath)fun chatsRoot(): File = File(root(), "chats")+ fun memoryRoot(): File = File(root(), "memory")+ fun soulFile(): File = File(memoryRoot(), "SOUL.md")+ fun memoryIndexFile(): File = File(memoryRoot(), "MEMORY.md")+ fun memoryUserFile(): File = File(memoryRoot(), "user.md")+ fun memoryAreasDir(): File = File(memoryRoot(), "areas")+ fun memoryPeopleDir(): File = File(memoryRoot(), "people")+ fun memoryNotesDir(): File = File(memoryRoot(), "notes")fun callsRoot(): File = File(root(), "calls")fun archiveRoot(): File = File(root(), "old_chats")fun screenshotsRoot(): File = File(root(), "Screenshots")diff --git a/app/src/main/java/com/gotcha/data/MemoryStore.kt b/app/src/main/java/com/gotcha/data/MemoryStore.ktnew file mode 100644index 0000000..fb48248--- /dev/null+++ b/app/src/main/java/com/gotcha/data/MemoryStore.kt@@ -0,0 +1,226 @@+package com.gotcha.data++import com.gotcha.llm.ChatMessage+import kotlinx.serialization.json.JsonPrimitive+import java.io.File++/**+ * Persistent memory for Gotcha (issue #156).+ *+ * Mobile adaptation of the second-brain pattern: a small master map+ * (MEMORY.md) with navigational addresses to detail files, plus SOUL.md+ * for identity. Stored under Gotcha/memory/ next to chats.+ *+ * Context budget: SOUL.md and MEMORY.md are capped and injected once per+ * chat as a [memory_startup] system message. Detail files are lazy loaded+ * with read_file/grep. The stable <memory> pointer in the system prompt+ * costs about 60 tokens per turn.+ */+object MemoryStore {++ const val SOUL_CAP_CHARS = 1500+ const val MEMORY_CAP_CHARS = 1500++ /** Marker identifying the injected startup message in history. */+ const val STARTUP_MARKER = "[memory_startup]"++ /** Stable pointer block appended to the Index 0 system prompt. */+ fun buildMemoryPointerBlock(): String = buildString {+ val root = runCatching { GotchaStorage.memoryRoot().absolutePath }.getOrNull() ?: "Gotcha/memory"+ appendLine("<memory>")+ appendLine("Persistent memory at $root.")+ appendLine(+ "If memory files exist, SOUL.md and MEMORY.md contents are in a " ++ "[memory_startup] system message after this prompt; if that message is absent, " ++ "memory is unavailable and you continue with Personal Info."+ )+ appendLine(+ "Follow MEMORY.md links with read_file or grep using ABSOLUTE paths. " ++ "Never resolve memory paths relative to the chat working directory. " ++ "Never bulk read the folder."+ )+ appendLine(+ "Writes allowed only in OPERATOR with write_file or edit using absolute paths. " ++ "In MONITOR, read only."+ )+ appendLine("Full protocol: call search_skills('memory').")+ append("</memory>")+ }++ /** True when at least one memory file is readable. */+ fun isAvailable(): Boolean {+ return readCapped(GotchaStorage.soulFile(), 1) != null ||+ readCapped(GotchaStorage.memoryIndexFile(), 1) != null+ }++ /**+ * Best-effort creation of the memory tree. Safe to call repeatedly and+ * safe to call without All-files access (mkdirs may fail; callers ignore).+ */+ fun ensureDefaults(settings: Settings) {+ runCatching {+ val root = GotchaStorage.memoryRoot()+ root.mkdirs()+ GotchaStorage.memoryAreasDir().mkdirs()+ GotchaStorage.memoryPeopleDir().mkdirs()+ GotchaStorage.memoryNotesDir().mkdirs()++ val soul = GotchaStorage.soulFile()+ if (!soul.exists()) {+ soul.writeText(defaultSoul())+ }+ val index = GotchaStorage.memoryIndexFile()+ if (!index.exists()) {+ index.writeText(defaultMemoryIndex())+ }+ ensureAreaHubs()+ syncUserFile(settings)+ }+ }++ /** Rewrites user.md from Personal Info. Called on startup and on profile updates. */+ fun syncUserFile(settings: Settings) {+ runCatching {+ GotchaStorage.memoryRoot().mkdirs()+ GotchaStorage.memoryUserFile().writeText(buildUserFile(settings))+ }+ }++ /**+ * Builds the one-time per-chat startup message with capped SOUL.md and+ * MEMORY.md contents. Returns null when both files are missing or empty+ * so old installs without storage access behave as before.+ */+ fun buildStartupMessage(): ChatMessage? {+ val soul = readCapped(GotchaStorage.soulFile(), SOUL_CAP_CHARS)+ val index = readCapped(GotchaStorage.memoryIndexFile(), MEMORY_CAP_CHARS)+ if (soul == null && index == null) return null+ val root = runCatching { GotchaStorage.memoryRoot().absolutePath }.getOrNull() ?: "Gotcha/memory"+ val body = buildString {+ appendLine(STARTUP_MARKER)+ appendLine(+ "Paths (use ABSOLUTE paths with read_file; " ++ "do not resolve relative to the chat working directory):"+ )+ appendLine(" $root/SOUL.md")+ appendLine(" $root/MEMORY.md")+ appendLine(" $root/user.md")+ appendLine()+ appendLine("<soul_md>")+ if (soul != null) {+ appendLine(soul.text)+ if (soul.truncated > 0) appendLine("... truncated, ${soul.truncated} chars omitted ...")+ } else {+ appendLine("(missing - continue with Personal Info)")+ }+ appendLine("</soul_md>")+ appendLine()+ appendLine("<memory_md>")+ if (index != null) {+ appendLine(index.text)+ if (index.truncated > 0) appendLine("... truncated, ${index.truncated} chars omitted ...")+ } else {+ appendLine("(missing - continue with Personal Info)")+ }+ appendLine("</memory_md>")+ appendLine()+ appendLine("Rules:")+ appendLine("1. SOUL.md is identity. Follow it for the whole chat.")+ appendLine("2. MEMORY.md is the map. Load detail files only when the task needs them.")+ appendLine("3. If a file is missing, continue with Personal Info and note it once.")+ appendLine("4. user.md is synced from Settings Personal Info. Do not duplicate it into notes.")+ }+ return ChatMessage(role = "system", content = JsonPrimitive(body))+ }++ /** True when [msg] is the injected memory startup message. */+ fun isStartupMessage(msg: ChatMessage): Boolean =+ msg.role == "system" && msg.textContent.contains(STARTUP_MARKER)++ internal data class CappedText(val text: String, val truncated: Int)++ 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+ }+ }++ internal fun buildUserFile(settings: Settings): String = buildString {+ appendLine("---")+ appendLine("title: User")+ appendLine("type: user-card")+ appendLine("---")+ appendLine()+ appendLine("# User")+ appendLine()+ if (settings.userName.isNotBlank()) appendLine("- Name: ${settings.userName.trim()}")+ if (settings.userLocation.isNotBlank()) appendLine("- Location: ${settings.userLocation.trim()}")+ if (settings.userOccupation.isNotBlank()) appendLine("- Occupation: ${settings.userOccupation.trim()}")+ if (settings.userBackground.isNotBlank()) {+ appendLine("- Background: ${settings.userBackground.replace(Regex("\\s+"), " ").trim().take(500)}")+ }+ if (settings.userResponseStyle.isNotBlank()) {+ appendLine("- Reply style: ${settings.userResponseStyle.replace(Regex("\\s+"), " ").trim().take(200)}")+ }+ appendLine("- Reply language: ${settings.preferredLanguage}")+ appendLine("- Preferred currency: ${settings.preferredCurrency}")+ }++ private fun defaultSoul(): String = buildString {+ appendLine("# SOUL")+ appendLine()+ appendLine("Who Gotcha is for this user. Edit this file to set persona and behavior.")+ appendLine("It is read at the start of every new chat, before the first reply.")+ appendLine()+ appendLine("## Identity")+ appendLine()+ appendLine("- Assistant name: Gotcha")+ appendLine("- Tone: helpful, concise")+ }++ private fun defaultMemoryIndex(): String = buildString {+ val root = runCatching { GotchaStorage.memoryRoot().absolutePath }.getOrNull() ?: "Gotcha/memory"+ appendLine("# MEMORY")+ appendLine()+ appendLine("Master map. Facts live in detail files, not here.")+ appendLine("Always open these with ABSOLUTE paths; the chat working directory is a different folder.")+ appendLine()+ appendLine("## Areas")+ appendLine()+ appendLine("- People: $root/people/")+ appendLine("- Work: $root/areas/work.md")+ appendLine("- Personal: $root/areas/personal.md")+ appendLine("- Health: $root/areas/health.md")+ appendLine()+ appendLine("## Links")+ appendLine()+ appendLine("- User card: $root/user.md")+ appendLine("- Identity: $root/SOUL.md")+ appendLine("- Notes: $root/notes/")+ }++ private fun ensureAreaHubs() {+ val root = runCatching { GotchaStorage.memoryRoot().absolutePath }.getOrNull() ?: "Gotcha/memory"+ val areas = mapOf(+ "people.md" to "# People\n\nContact cards live in $root/people/. Open with absolute paths.\n",+ "work.md" to "# Work\n\nProjects and work threads. Detail notes live in $root/notes/. Open with absolute paths.\n",+ "personal.md" to "# Personal\n\nHome, routine, finance admin. Detail notes live in $root/notes/. Open with absolute paths.\n",+ "health.md" to "# Health\n\nHealth context the user chooses to keep. Never store diagnoses as facts.\n"+ )+ areas.forEach { (name, body) ->+ val file = File(GotchaStorage.memoryAreasDir(), name)+ if (!file.exists()) {+ runCatching { file.writeText(body) }+ }+ }+ }+}diff --git a/app/src/main/java/com/gotcha/ui/PermissionsSection.kt b/app/src/main/java/com/gotcha/ui/PermissionsSection.ktindex ad1b3f0..94a2572 100644--- a/app/src/main/java/com/gotcha/ui/PermissionsSection.kt+++ b/app/src/main/java/com/gotcha/ui/PermissionsSection.kt@@ -67,7 +67,14 @@ fun PermissionsSection(val runtimeLauncher = rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()- ) { /* permission state is re-read on next ON_RESUME via resumeSignal */ }+ ) {+ // Re-read permission state from Android right away: the system dialog+ // does not reliably pause/resume the activity (floating dialog on some+ // OEM builds, instant return when already granted), so waiting for the+ // next ON_RESUME leaves the toggle showing stale state and snapping+ // back after the user taps it.+ resumeSignal+++ }// Health Connect only reports granted permissions through a suspend call, so its row// cannot re-read live state like the others — it reads this value instead, refresheddiff --git a/app/src/test/java/com/gotcha/data/MemoryStoreTest.kt b/app/src/test/java/com/gotcha/data/MemoryStoreTest.ktnew file mode 100644index 0000000..4bfdbaa--- /dev/null+++ b/app/src/test/java/com/gotcha/data/MemoryStoreTest.kt@@ -0,0 +1,112 @@+package com.gotcha.data++import com.gotcha.llm.ChatMessage+import kotlinx.serialization.json.JsonPrimitive+import org.junit.After+import org.junit.Assert.assertFalse+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Before+import org.junit.Test+import java.io.File+import java.nio.file.Files++class MemoryStoreTest {++ private lateinit var tmpRoot: File+ private var savedOverride: String? = null++ @Before+ fun setUp() {+ tmpRoot = Files.createTempDirectory("gotcha-memory-test").toFile()+ savedOverride = try {+ GotchaStorage.rootPath+ } catch (_: Exception) {+ null+ }+ GotchaStorage.rootPath = File(tmpRoot, "Gotcha").absolutePath+ }++ @After+ fun tearDown() {+ tmpRoot.deleteRecursively()+ if (savedOverride != null) {+ GotchaStorage.rootPath = savedOverride!!+ } else {+ GotchaStorage.resetRootPathForTests()+ }+ }++ @Test+ fun `ensureDefaults creates memory tree and seeds files`() {+ MemoryStore.ensureDefaults(Settings(userName = "Ada"))+ assertTrue(GotchaStorage.memoryRoot().isDirectory)+ assertTrue(GotchaStorage.soulFile().exists())+ assertTrue(GotchaStorage.memoryIndexFile().exists())+ assertTrue(GotchaStorage.memoryUserFile().readText().contains("Ada"))+ assertTrue(File(GotchaStorage.memoryAreasDir(), "work.md").exists())+ }++ @Test+ fun `startup message contains capped soul and memory index`() {+ MemoryStore.ensureDefaults(Settings())+ GotchaStorage.soulFile().writeText("S".repeat(2000))+ val msg = MemoryStore.buildStartupMessage()+ assertNotNull(msg)+ val text = msg!!.textContent+ assertTrue(text.contains(MemoryStore.STARTUP_MARKER))+ assertTrue(text.contains("truncated"))+ assertTrue(MemoryStore.isStartupMessage(msg))+ }++ @Test+ fun `startup message null when files missing`() {+ assertNull(MemoryStore.buildStartupMessage())+ }++ @Test+ fun `non startup message is not detected`() {+ val other = ChatMessage(role = "system", content = JsonPrimitive("hello"))+ assertFalse(MemoryStore.isStartupMessage(other))+ }++ @Test+ fun `pointer block is stable and cheap`() {+ val first = MemoryStore.buildMemoryPointerBlock()+ val second = MemoryStore.buildMemoryPointerBlock()+ assertTrue(first == second)+ assertTrue(first.contains("<memory>"))+ assertTrue(first.length < 800)+ }++ @Test+ fun `syncUserFile reflects profile changes`() {+ MemoryStore.ensureDefaults(Settings(userName = "Ada"))+ MemoryStore.syncUserFile(Settings(userName = "Grace", userOccupation = "Engineer"))+ val text = GotchaStorage.memoryUserFile().readText()+ assertTrue(text.contains("Grace"))+ assertFalse(text.contains("Ada"))+ }++ @Test+ fun `user file includes reply style`() {+ MemoryStore.syncUserFile(Settings(userResponseStyle = "No bullet lists."))+ assertTrue(GotchaStorage.memoryUserFile().readText().contains("No bullet lists."))+ }++ @Test+ fun `startup message uses absolute paths`() {+ MemoryStore.ensureDefaults(Settings())+ val text = MemoryStore.buildStartupMessage()!!.textContent+ assertTrue(text.contains(GotchaStorage.memoryRoot().absolutePath))+ assertFalse(text.contains("Paths:\n Gotcha/memory/"))+ }++ @Test+ fun `pointer block is conditional on availability`() {+ val pointer = MemoryStore.buildMemoryPointerBlock()+ assertTrue(pointer.contains("if that message is absent"))+ assertTrue(pointer.contains("ABSOLUTE paths"))+ }+}