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.
Second Brain Phase 1: record schema, digest, history, timezone (#156)
Rishabh Bajpai8ee72107397f
diff --git a/app/src/main/assets/skills/memory.json b/app/src/main/assets/skills/memory.jsonindex c19ff6b..c24f02a 100644--- a/app/src/main/assets/skills/memory.json+++ b/app/src/main/assets/skills/memory.json@@ -1,9 +1,22 @@{"id": "memory",- "targetPackageNames": ["*"],+ "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. Raw drops (uploads, audio, images, documents in any format) live in raw/.\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\nLink nodes whenever possible: every note, person, area and raw file you create or update must link to the related nodes with Obsidian-style [[links]] (for example [[people/asha-sharma.md]] or [[notes/trip-plan.md]]), and update MEMORY.md so the graph stays connected. One fact in one place: link, never copy-paste content. The viewer draws these links as a node graph, so an unlinked file is an invisible island.\n\nRaw files: when the user shares or uploads a file worth keeping (a voice memo, photo, PDF, receipt, reference doc), save a copy into Gotcha/memory/raw/ with write_file when the content is small enough, and record its absolute path plus a one-line description in the related note and in MEMORY.md. For large files already on disk, do not duplicate them: record the absolute path in place instead. Never store passwords, OTPs, API tokens, or private keys anywhere in memory.\n\nWrites: OPERATOR only with write_file or edit using absolute paths. In MONITOR, read only, never write. Keep SOUL.md under 1500 chars and MEMORY.md under 1500 chars so session start stays cheap.\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."+ "requiresTools": [+ "read_file"+ ],+ "keywords": [+ "memory",+ "soul",+ "remember",+ "persona",+ "user card",+ "digest",+ "frontmatter",+ "second brain"+ ],+ "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/. Raw drops (uploads, audio, images, documents in any format) live in raw/.\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\nRecord schema: every file you create in people/, areas/ or notes/ MUST start with YAML frontmatter between --- lines: required title, area, type (person, note, meeting, decision, reference, area, contact-card), updated (ISO yyyy-MM-dd). Optional tags (slug list like [k99, cerebral-palsy]), source, source_file, stage, project, summary. area uses the MEMORY.md vocabulary (starts as People, Work, Personal, Health). Types belong to directories: areas/ holds type area hubs, people/ holds type person cards, notes/ holds note, meeting, decision or reference. tags are lowercase slugs: letters, digits and single hyphens only, never spaces, capitals or underscores. Writes with bad frontmatter are rejected by the tool with the reasons: fix them and retry. Facts live in the body with [[links]], never in the map.\n\nDigest workflow: when the user shares or uploads a file worth keeping, classify it. A durable insight becomes a note with frontmatter (source_file naming the raw file plus a [[raw/...]] link in a Sources section). Copy small or at-risk files into raw/ with write_file. Files over ~10 MB already on durable disk are linked in place: record the absolute path, never duplicate them. Never link temp, cache or staging paths: even huge files there must be copied into raw/ when the user asks to keep them. Always ask whether to keep the raw copy: yes means file it with a one-line description recorded in the owning note and MEMORY.md, no means digest from the given path without copying. Raw files are immutable: never edit, only delete once digested AND linked. Propose cleanup of raw files older than 30 days instead of letting them pile up. Trivial drops are deleted, never filed.\n\nHistory rule: dated notes (names starting yyyy-MM-dd) describe what was true THEN. Never rewrite their bodies when decisions change. New decisions go in new notes with a Superseded by [[path]] line at the top, linked both ways.\n\nTimezone: the device timezone is truth. Resolve every user-facing date and time in it with zone-aware conversion (never a hardcoded offset: it breaks at each DST changeover). Write absolute dates (2026-10-29) in notes, never relative ones.\n\nLink nodes whenever possible: every note, person, area and raw file you create or update must link to the related nodes with Obsidian-style [[links]] (for example [[people/asha-sharma.md]] or [[notes/trip-plan.md]]), and update MEMORY.md so the graph stays connected. One fact in one place: link, never copy-paste content. The viewer draws these links as a node graph, so an unlinked file is an invisible island.\n\nWrites: OPERATOR only with write_file or edit using absolute paths. In MONITOR, read only, never write. Operator memory writes happen silently without a separate approval step: say briefly what was remembered so the user can correct it. Destructive actions (delete, or rewriting a dated note) still need explicit confirmation first. Never store passwords, OTPs, API tokens, or private keys anywhere in memory. Keep SOUL.md under 1500 chars and MEMORY.md under 1500 chars so session start stays cheap.\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/. To create a new area, write areas/<name>.md first with area: <Name>, then file notes under it. 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/data/MemoryStore.kt b/app/src/main/java/com/gotcha/data/MemoryStore.ktindex 352c375..1162348 100644--- a/app/src/main/java/com/gotcha/data/MemoryStore.kt+++ b/app/src/main/java/com/gotcha/data/MemoryStore.kt@@ -17,7 +17,7 @@ import java.io.File* with read_file/grep. The stable <memory> pointer in the system prompt* costs about 60 tokens per turn.*/-@Suppress("TooManyFunctions")+@Suppress("TooManyFunctions", "LargeClass")object MemoryStore {const val SOUL_CAP_CHARS = 1500@@ -77,6 +77,7 @@ object MemoryStore {index.writeText(defaultMemoryIndex())}ensureAreaHubs()+ migrateLegacyHubs()syncUserFile(settings)}}@@ -132,6 +133,7 @@ object MemoryStore {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.")+ appendLine("5. Before writing memory, load the full protocol: search_skills('memory').")}return ChatMessage(role = "system", content = JsonPrimitive(body))}@@ -466,6 +468,314 @@ object MemoryStore {}}+ /**+ * Record schema for people/, areas/ and notes/ detail files (Phase 1).+ *+ * Every record carries YAML frontmatter between leading `---` lines:+ * required `title`, `area`, `type`, `updated` (ISO yyyy-MM-dd); optional+ * `tags` (slug list), `source` (where the fact came from), `source_file`+ * (raw file this was digested from), `stage`, `project`, `summary`.+ * SOUL.md, MEMORY.md, user.md and raw/ files are not records.+ */+ val RECORD_REQUIRED_KEYS = setOf("title", "area", "type", "updated")+ val RECORD_ALLOWED_KEYS = setOf(+ "title", "area", "type", "tags", "updated",+ "source", "source_file", "stage", "project", "summary"+ )++ /** Record types. Hub files in areas/ use `area`. */+ val RECORD_TYPES = setOf("person", "note", "meeting", "decision", "reference", "area", "contact-card")++ /** Starter area vocabulary. Users may add areas; validation also accepts existing hubs. */+ val STARTER_AREAS = setOf("People", "Work", "Personal", "Health")++ private val slugRegex = Regex("^[a-z0-9]+(?:-[a-z0-9]+)*$")+ private val isoDateRegex = Regex("^\\d{4}-\\d{2}-\\d{2}$")+ private val datedNameRegex = Regex("^\\d{4}-\\d{2}-\\d{2}")++ data class RecordValidation(val valid: Boolean, val errors: List<String>)++ /**+ * Validates a detail record's frontmatter and body. Returns every problem+ * found so the agent can speak the fix back. Pure string logic, no I/O+ * except the area-vocabulary check against existing hub files.+ *+ * @param dirKind top-level memory dir (`areas`, `people`, `notes`) for+ * type-vs-directory checks; null skips them.+ */+ fun validateRecord(fileName: String, content: String, dirKind: String? = null): RecordValidation {+ val errors = mutableListOf<String>()+ val lines = content.lines()+ if (lines.isEmpty() || lines[0].trim() != "---") {+ return RecordValidation(+ false,+ listOf(+ "$fileName: missing frontmatter. Start the file with a --- block " ++ "carrying ${RECORD_REQUIRED_KEYS.sorted().joinToString(", ")}."+ )+ )+ }+ val end = lines.drop(1).indexOfFirst { it.trim() == "---" }+ if (end < 0) {+ return RecordValidation(false, listOf("$fileName: frontmatter never closed with ---."))+ }+ val values = mutableMapOf<String, String>()+ parseFrontmatterLines(fileName, lines.drop(1).take(end), values, errors)+ val base = fileName.substringAfterLast('/').substringBeforeLast('.')+ checkRecordFields(fileName, base, dirKind, values, errors)+ val body = lines.drop(1 + end + 1).joinToString("\n").trim()+ if (body.isEmpty()) errors.add("$fileName: empty body. Facts live in the body, not the map.")+ return RecordValidation(errors.isEmpty(), errors)+ }++ /** Parses `key: value` lines into [values], collecting syntax problems. */+ private fun parseFrontmatterLines(+ fileName: String,+ fmLines: List<String>,+ values: MutableMap<String, String>,+ errors: MutableList<String>+ ) {+ var inBlock = false+ fmLines.forEach { raw ->+ if (inBlock) {+ // Continuation of a `key: |` block scalar: indented or blank+ // lines belong to the value, not to new keys.+ if (raw.isBlank() || raw.startsWith(" ") || raw.startsWith("\t")) return@forEach+ inBlock = false+ }+ val line = raw.trim()+ if (line.isEmpty() || line.startsWith("#")) return@forEach+ val key = line.substringBefore(':', "").trim()+ if (!line.contains(':') || key.isEmpty()) {+ errors.add("$fileName: malformed frontmatter line '$line' (expected key: value).")+ return@forEach+ }+ if (values.containsKey(key)) errors.add("$fileName: duplicate frontmatter key '$key'.")+ val value = unquote(line.substringAfter(':').trim())+ values[key] = value+ if (value == "|" || value == ">") inBlock = true+ }+ }++ /** Strips one layer of surrounding single or double quotes, so `title: ""` counts as blank. */+ private fun unquote(value: String): String {+ if (value.length < 2) return value+ val doubleQuoted = value.startsWith('"') && value.endsWith('"')+ val singleQuoted = value.startsWith('\'') && value.endsWith('\'')+ if (doubleQuoted || singleQuoted) return value.substring(1, value.length - 1)+ return value+ }++ /** Checks keys, types, areas, dates and tags against the record schema. */+ private fun checkRecordFields(+ fileName: String,+ fileBase: String,+ dirKind: String?,+ values: Map<String, String>,+ errors: MutableList<String>+ ) {+ values.keys.filter { it !in RECORD_ALLOWED_KEYS }.sorted().forEach { key ->+ errors.add(+ "$fileName: unknown frontmatter key '$key' " ++ "(allowed: ${RECORD_ALLOWED_KEYS.sorted().joinToString(", ")})."+ )+ }+ RECORD_REQUIRED_KEYS.sorted().forEach { key ->+ if (values[key].isNullOrBlank()) errors.add("$fileName: missing required frontmatter key '$key'.")+ }+ values["type"]?.takeIf { it.isNotBlank() }?.let { type ->+ if (type !in RECORD_TYPES) {+ errors.add(+ "$fileName: unknown type '$type' " ++ "(allowed: ${RECORD_TYPES.sorted().joinToString(", ")})."+ )+ } else if (dirKind != null && !typeFitsDirectory(dirKind, type)) {+ errors.add(+ "$fileName: type '$type' does not belong in $dirKind/ " ++ "(areas/ holds type area, people/ holds person, notes/ holds notes)."+ )+ }+ }+ values["area"]?.takeIf { it.isNotBlank() }?.let { area ->+ // Bootstrap rule: writing areas/<name>.md with area <name> IS the+ // hub creation, so it passes before the hub exists.+ val bootstrapping = dirKind == "areas" && area.equals(fileBase, ignoreCase = true)+ if (!bootstrapping && !isKnownArea(area)) {+ errors.add(+ "$fileName: unknown area '$area'. Use an existing area hub or " ++ "create the area in MEMORY.md plus areas/ first."+ )+ }+ }+ values["updated"]?.takeIf { it.isNotBlank() }?.let { updated ->+ val valid = isoDateRegex.matches(updated) &&+ runCatching {+ java.time.LocalDate.parse(updated)+ true+ }.getOrDefault(false)+ if (!valid) {+ errors.add("$fileName: 'updated' must be an ISO date (yyyy-MM-dd), got '$updated'.")+ }+ }+ values["tags"]?.let { rawTags ->+ parseTags(rawTags).forEach { tag ->+ if (!slugRegex.matches(tag)) {+ errors.add(+ "$fileName: tag '$tag' breaks the slug rule " ++ "(lowercase letters, digits, single hyphens only)."+ )+ }+ }+ }+ if (values.containsKey("source") && values["source"].isNullOrBlank()) {+ errors.add("$fileName: 'source' is present but blank.")+ }+ }++ /** Parses a `tags:` value: inline `[a, b]` list or a single slug. */+ fun parseTags(raw: String): List<String> {+ val trimmed = raw.trim()+ if (trimmed.isEmpty()) return emptyList()+ if (trimmed.startsWith("[") && trimmed.endsWith("]")) {+ return splitInlineList(trimmed.removePrefix("[").removeSuffix("]"))+ }+ return listOf(unquote(trimmed)).filter { it.isNotEmpty() }+ }++ /** Splits an inline `[...]` list on commas outside quotes, so `["bad,tag"]` stays one value. */+ private fun splitInlineList(inner: String): List<String> {+ val out = mutableListOf<String>()+ val cur = StringBuilder()+ var quote: Char? = null+ fun flush() {+ val tag = unquote(cur.toString().trim())+ if (tag.isNotEmpty()) out.add(tag)+ cur.clear()+ }+ inner.forEach { ch ->+ when {+ quote != null && ch == quote -> {+ cur.append(ch)+ quote = null+ }+ quote == null && (ch == '"' || ch == '\'') -> {+ cur.append(ch)+ quote = ch+ }+ quote == null && ch == ',' -> flush()+ else -> cur.append(ch)+ }+ }+ flush()+ return out+ }++ /** True when [type] belongs in [dirKind]: hubs in areas/, cards in people/, notes in notes/. */+ private fun typeFitsDirectory(dirKind: String, type: String): Boolean = when (dirKind) {+ "areas" -> type == "area"+ "people" -> type == "person" || type == "contact-card"+ "notes" -> type == "note" || type == "meeting" || type == "decision" || type == "reference"+ else -> true+ }++ /** True when [area] matches the starter vocabulary or an existing hub file. */+ fun isKnownArea(area: String): Boolean {+ if (STARTER_AREAS.any { it.equals(area, ignoreCase = true) }) return true+ return runCatching {+ GotchaStorage.memoryAreasDir().listFiles()+ ?.filter { it.isFile }+ ?.map { it.nameWithoutExtension }+ ?.any { it.equals(area, ignoreCase = true) } ?: false+ }.getOrDefault(false)+ }++ /**+ * True when [file] is a people/areas/notes detail record: the only memory+ * files the schema (and the write gate) applies to.+ */+ fun isDetailRecord(file: File): Boolean = recordDirKind(file) != null++ /**+ * Top-level memory dir (`areas`, `people`, `notes`) for a detail record,+ * or null when [file] is not one. The write gates pass it to+ * [validateRecord] for type-vs-directory checks.+ */+ fun recordDirKind(file: File): String? {+ return runCatching {+ val root = GotchaStorage.memoryRoot().canonicalPath+ val path = file.canonicalPath+ if (!path.startsWith(root + File.separator)) return@runCatching null+ val rel = path.removePrefix(root + File.separator)+ val dir = rel.substringBefore('/', "")+ if (dir != "areas" && dir != "people" && dir != "notes") return@runCatching null+ val ext = file.name.substringAfterLast('.', "").lowercase()+ if (ext != "md" && ext != "markdown") return@runCatching null+ dir+ }.getOrNull()+ }++ /**+ * Digest helper: raw files older than [maxAgeDays] that the agent should+ * propose for cleanup (digested-and-linked raws are deleted, kept raws+ * are noted with their reason). Never deletes; only lists.+ */+ fun listStaleRaw(maxAgeDays: Int = 30, nowMillis: Long = System.currentTimeMillis()): List<File> {+ return try {+ val dir = GotchaStorage.memoryRawDir()+ if (!dir.exists() || !dir.isDirectory) return emptyList()+ val cutoff = nowMillis - maxAgeDays * 24L * 60 * 60 * 1000+ dir.listFiles()?.filter { it.isFile && it.lastModified() < cutoff }+ ?.sortedBy { it.name.lowercase() }.orEmpty()+ } catch (_: Exception) {+ emptyList()+ }+ }++ /**+ * Digest helper: copy-vs-link gate. Files over [RAW_LINK_THRESHOLD_BYTES]+ * are linked in place, never duplicated — except under ephemeral paths,+ * which must always be copied because the original can vanish.+ */+ const val RAW_LINK_THRESHOLD_BYTES = 10L * 1024 * 1024++ /** True for staging paths that can vanish: temp dirs, caches, `.tmp` files. */+ fun isEphemeralPath(path: String): Boolean {+ val lower = path.lowercase().replace('\\', '/')+ return lower.startsWith("/tmp/") || lower == "/tmp" ||+ lower.contains("/tmp/") || lower.contains("/cache/") ||+ lower.contains("/temp/") || lower.endsWith(".tmp") || lower.endsWith(".temp")+ }++ /**+ * History rule helper: dated notes (names starting yyyy-MM-dd) describe+ * what was true THEN and stay append-only. New decisions go in new notes+ * with `Superseded by [[path]]` links both ways, never rewrites.+ */+ fun isDatedNote(fileName: String): Boolean {+ val prefix = datedNameRegex.find(fileName)?.value ?: return false+ return runCatching {+ java.time.LocalDate.parse(prefix)+ true+ }.getOrDefault(false)+ }++ /**+ * Timezone rule: the device zone is truth. Formats [nowMillis] as an ISO+ * date in the device zone with DST-safe conversion (never a hardcoded+ * offset). Notes carry absolute dates, never relative ones.+ */+ fun deviceTimezoneId(): String =+ runCatching { java.time.ZoneId.systemDefault().id }.getOrNull() ?: "UTC"++ fun formatDateForMemory(nowMillis: Long = System.currentTimeMillis()): String {+ val instant = java.time.Instant.ofEpochMilli(nowMillis)+ return runCatching {+ java.time.LocalDate.ofInstant(instant, java.time.ZoneId.systemDefault()).toString()+ }.getOrDefault(+ java.time.LocalDate.ofInstant(instant, java.time.ZoneOffset.UTC).toString()+ )+ }+internal fun buildUserFile(settings: Settings): String = buildString {appendLine("---")appendLine("title: User")@@ -522,11 +832,35 @@ object MemoryStore {private fun ensureAreaHubs() {val root = runCatching { GotchaStorage.memoryRoot().absolutePath }.getOrNull() ?: "Gotcha/memory"+ val today = formatDateForMemory()+ fun hub(title: String, area: String, body: String): String = buildString {+ appendLine("---")+ appendLine("title: $title")+ appendLine("area: $area")+ appendLine("type: area")+ appendLine("tags: []")+ appendLine("updated: $today")+ appendLine("---")+ appendLine()+ append(body)+ }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"+ "people.md" to hub(+ "People", "People",+ "# People\n\nContact cards live in $root/people/. Open with absolute paths.\n"+ ),+ "work.md" to hub(+ "Work", "Work",+ "# Work\n\nProjects and work threads. Detail notes live in $root/notes/. Open with absolute paths.\n"+ ),+ "personal.md" to hub(+ "Personal", "Personal",+ "# Personal\n\nHome, routine, finance admin. Detail notes live in $root/notes/. Open with absolute paths.\n"+ ),+ "health.md" to hub(+ "Health", "Health",+ "# 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)@@ -535,4 +869,39 @@ object MemoryStore {}}}++ /**+ * One-time migration for pre-schema installs: hub files written before the+ * record schema gain frontmatter in place, so they stay editable through+ * the write gate. Bodies are preserved untouched; only already-valid files+ * and non-markdown files are skipped.+ */+ private fun migrateLegacyHubs() {+ val dir = GotchaStorage.memoryAreasDir()+ if (!dir.exists() || !dir.isDirectory) return+ val today = formatDateForMemory()+ dir.listFiles()+ ?.filter { it.isFile && it.name.substringAfterLast('.', "").lowercase() == "md" }+ .orEmpty()+ .forEach { hub ->+ runCatching {+ val text = hub.readText()+ if (text.lines().firstOrNull()?.trim() == "---") return@runCatching+ val base = hub.nameWithoutExtension+ val area = STARTER_AREAS.firstOrNull { it.equals(base, ignoreCase = true) }+ ?: base.replaceFirstChar { it.uppercase() }+ val header = listOf(+ "---",+ "title: $base",+ "area: $area",+ "type: area",+ "tags: []",+ "updated: $today",+ "---",+ ""+ ).joinToString("\n")+ hub.writeText(header + text)+ }+ }+ }}diff --git a/app/src/main/java/com/gotcha/tools/EditTool.kt b/app/src/main/java/com/gotcha/tools/EditTool.ktindex 670da73..ed0c1d4 100644--- a/app/src/main/java/com/gotcha/tools/EditTool.kt+++ b/app/src/main/java/com/gotcha/tools/EditTool.kt@@ -1,6 +1,7 @@package com.gotcha.toolsimport android.content.Context+import com.gotcha.data.MemoryStore/*** Surgical text replacement tool — replaces exact text in a file.@@ -74,6 +75,19 @@ class EditTool(private val context: Context) {} else {content.replaceFirst(oldString, newString)}+ // Memory schema gate (Second Brain Phase 1): edits must+ // leave detail records valid, so history and tags cannot+ // drift silently.+ MemoryStore.recordDirKind(file)?.let { dirKind ->+ val check = MemoryStore.validateRecord(file.name, newContent, dirKind)+ if (!check.valid) {+ return ToolResult.error(+ "Memory record rejected:\n" ++ check.errors.joinToString("\n") ++ "\nFix the frontmatter and retry (protocol: search_skills('memory'))."+ )+ }+ }file.writeText(newContent, Charsets.UTF_8)val verb = if (replaceAll) "Replaced $count occurrences" else "Replaced 1 occurrence"diff --git a/app/src/main/java/com/gotcha/tools/FileTool.kt b/app/src/main/java/com/gotcha/tools/FileTool.ktindex 9564a86..2cb06e3 100644--- a/app/src/main/java/com/gotcha/tools/FileTool.kt+++ b/app/src/main/java/com/gotcha/tools/FileTool.kt@@ -3,6 +3,7 @@ package com.gotcha.toolsimport android.content.Contextimport android.graphics.BitmapFactoryimport android.util.Base64+import com.gotcha.data.MemoryStoreimport java.io.Fileimport java.util.zip.ZipFile@@ -351,6 +352,40 @@ class FileTool(private val context: Context) {is FileResolver.ResolveResult.Ok -> {val perm = resolver.checkWritePermission(resolved.file)if (perm != null) return perm+ // Memory schema gate (Second Brain Phase 1): detail records+ // under memory people/areas/notes must carry valid frontmatter.+ // Rejected writes return the reasons so the agent speaks the fix.+ val dirKind = MemoryStore.recordDirKind(resolved.file)+ if (dirKind != null) {+ if (binary) {+ return ToolResult.error(+ "Memory records are Markdown text: refusing binary write to " ++ "'${resolved.file.name}'. Write text with frontmatter instead " ++ "(protocol: search_skills('memory'))."+ )+ }+ if (!append && resolved.file.exists() && MemoryStore.isDatedNote(resolved.file.name)) {+ return ToolResult.error(+ "Dated notes are append-only: '${resolved.file.name}' describes what was " ++ "true then and must not be replaced. Create a new note with the new " ++ "decision and link both ways with a Superseded by [[path]] line, or use " ++ "edit to add that line (protocol: search_skills('memory'))."+ )+ }+ val effective = if (append && resolved.file.exists()) {+ runCatching { resolved.file.readText(Charsets.UTF_8) }.getOrDefault("") + content+ } else {+ content+ }+ val check = MemoryStore.validateRecord(resolved.file.name, effective, dirKind)+ if (!check.valid) {+ return ToolResult.error(+ "Memory record rejected:\n" ++ check.errors.joinToString("\n") ++ "\nFix the frontmatter and retry (protocol: search_skills('memory'))."+ )+ }+ }writeResolved(resolved.file, path, content, append, binary)}}diff --git a/app/src/test/java/com/gotcha/data/MemoryStoreTest.kt b/app/src/test/java/com/gotcha/data/MemoryStoreTest.ktindex a9f7437..6956911 100644--- a/app/src/test/java/com/gotcha/data/MemoryStoreTest.kt+++ b/app/src/test/java/com/gotcha/data/MemoryStoreTest.kt@@ -293,4 +293,244 @@ class MemoryStoreTest {assertEquals(points[1], keptPoints[1])assertEquals(points[2], keptPoints[2])}++ // ---- Second Brain Phase 1: record schema, digest, history, timezone ----++ private fun goodRecord(): String = listOf(+ "---",+ "title: Trip Plan",+ "area: Personal",+ "type: note",+ "tags: [travel, japan-2026]",+ "updated: 2026-10-29",+ "source: user chat",+ "source_file: raw/memo.mp3",+ "---",+ "",+ "# Trip Plan",+ "",+ "See [[areas/personal.md]].",+ ""+ ).joinToString("\n")++ @Test+ fun `seeded area hubs carry valid frontmatter`() {+ MemoryStore.ensureDefaults(Settings())+ GotchaStorage.memoryAreasDir().listFiles()!!.forEach { hub ->+ val check = MemoryStore.validateRecord(hub.name, hub.readText())+ assertTrue("${hub.name}: ${check.errors}", check.valid)+ }+ }++ @Test+ fun `validateRecord accepts a complete record`() {+ MemoryStore.ensureDefaults(Settings())+ val check = MemoryStore.validateRecord("trip.md", goodRecord())+ assertTrue(check.errors.toString(), check.valid)+ }++ @Test+ fun `validateRecord rejects missing frontmatter`() {+ MemoryStore.ensureDefaults(Settings())+ val check = MemoryStore.validateRecord("trip.md", "# No frontmatter\n\nBody.\n")+ assertFalse(check.valid)+ assertTrue(check.errors.any { it.contains("frontmatter") })+ }++ @Test+ fun `validateRecord rejects bad fields`() {+ MemoryStore.ensureDefaults(Settings())+ val bad = listOf(+ "---",+ "title: ",+ "area: Atlantis",+ "type: nonsense",+ "tags: [Bad Tag, ok]",+ "updated: 29-10-2026",+ "mystery: 1",+ "---",+ "",+ "Body.",+ ""+ ).joinToString("\n")+ val check = MemoryStore.validateRecord("bad.md", bad)+ assertFalse(check.valid)+ val joined = check.errors.joinToString("\n")+ assertTrue(joined, joined.contains("'title'"))+ assertTrue(joined, joined.contains("Atlantis"))+ assertTrue(joined, joined.contains("nonsense"))+ assertTrue(joined, joined.contains("Bad Tag"))+ assertTrue(joined, joined.contains("updated"))+ assertTrue(joined, joined.contains("mystery"))+ }++ @Test+ fun `validateRecord rejects empty bodies`() {+ MemoryStore.ensureDefaults(Settings())+ val check = MemoryStore.validateRecord(+ "empty.md",+ "---\ntitle: T\narea: Work\ntype: note\nupdated: 2026-10-29\n---\n"+ )+ assertFalse(check.valid)+ assertTrue(check.errors.any { it.contains("empty body") })+ }++ @Test+ fun `parseTags handles inline lists and single slugs`() {+ assertEquals(listOf("travel", "japan-2026"), MemoryStore.parseTags("[travel, japan-2026]"))+ assertEquals(emptyList<String>(), MemoryStore.parseTags("[]"))+ assertEquals(listOf("solo"), MemoryStore.parseTags("solo"))+ }++ @Test+ fun `isKnownArea accepts starter and custom hubs`() {+ MemoryStore.ensureDefaults(Settings())+ assertTrue(MemoryStore.isKnownArea("Work"))+ assertTrue(MemoryStore.isKnownArea("work"))+ File(GotchaStorage.memoryAreasDir(), "sidequest.md").writeText("# Sidequest\n")+ assertTrue(MemoryStore.isKnownArea("sidequest"))+ assertFalse(MemoryStore.isKnownArea("Atlantis"))+ }++ @Test+ fun `isDetailRecord gates only detail markdown`() {+ MemoryStore.ensureDefaults(Settings())+ assertTrue(MemoryStore.isDetailRecord(File(GotchaStorage.memoryNotesDir(), "trip.md")))+ assertTrue(MemoryStore.isDetailRecord(File(GotchaStorage.memoryPeopleDir(), "asha.markdown")))+ assertFalse(MemoryStore.isDetailRecord(GotchaStorage.soulFile()))+ assertFalse(MemoryStore.isDetailRecord(GotchaStorage.memoryIndexFile()))+ assertFalse(MemoryStore.isDetailRecord(GotchaStorage.memoryUserFile()))+ assertFalse(MemoryStore.isDetailRecord(File(GotchaStorage.memoryRawDir(), "memo.mp3")))+ assertFalse(MemoryStore.isDetailRecord(File(GotchaStorage.memoryNotesDir(), "clip.mp3")))+ }++ @Test+ fun `listStaleRaw flags files older than 30 days`() {+ MemoryStore.ensureDefaults(Settings())+ val rawDir = GotchaStorage.memoryRawDir().apply { mkdirs() }+ val old = File(rawDir, "old-memo.mp3").apply {+ writeBytes(byteArrayOf(1, 2, 3))+ setLastModified(System.currentTimeMillis() - 40L * 24 * 60 * 60 * 1000)+ }+ val fresh = File(rawDir, "fresh.txt").apply { writeText("new") }+ val stale = MemoryStore.listStaleRaw()+ assertTrue(stale.map { it.name }.contains(old.name))+ assertFalse(stale.map { it.name }.contains(fresh.name))+ }++ @Test+ fun `isEphemeralPath spots staging paths`() {+ assertTrue(MemoryStore.isEphemeralPath("/tmp/voice.mp3"))+ assertTrue(MemoryStore.isEphemeralPath("/data/cache/memo.pdf"))+ assertTrue(MemoryStore.isEphemeralPath("/sdcard/Temp/clip.mp4"))+ assertTrue(MemoryStore.isEphemeralPath("/sdcard/Download/draft.tmp"))+ assertFalse(MemoryStore.isEphemeralPath("/sdcard/Documents/paper.pdf"))+ }++ @Test+ fun `isDatedNote detects dated names`() {+ assertTrue(MemoryStore.isDatedNote("2026-10-29-sync.md"))+ assertFalse(MemoryStore.isDatedNote("trip.md"))+ assertFalse(MemoryStore.isDatedNote("2026-13-99-bogus.md"))+ }++ @Test+ fun `memory dates use the device timezone`() {+ assertTrue(MemoryStore.deviceTimezoneId().isNotBlank())+ val expected = java.time.LocalDate.ofInstant(+ java.time.Instant.ofEpochMilli(0),+ java.time.ZoneId.systemDefault()+ ).toString()+ assertEquals(expected, MemoryStore.formatDateForMemory(0))+ assertTrue(MemoryStore.formatDateForMemory().matches(Regex("\\d{4}-\\d{2}-\\d{2}")))+ }++ // ---- Codex review follow-ups ----++ private fun record(type: String, area: String, tags: String = "[x]"): String = listOf(+ "---",+ "title: T",+ "area: $area",+ "type: $type",+ "tags: $tags",+ "updated: 2026-10-29",+ "---",+ "",+ "Body.",+ ""+ ).joinToString("\n")++ @Test+ fun `validateRecord treats quoted empty values as blank`() {+ MemoryStore.ensureDefaults(Settings())+ val check = MemoryStore.validateRecord(+ "q.md",+ "---\ntitle: \"\"\narea: Work\ntype: note\nupdated: 2026-10-29\n---\n\nBody.\n"+ )+ assertFalse(check.valid)+ assertTrue(check.errors.any { it.contains("'title'") })+ }++ @Test+ fun `validateRecord rejects commas inside quoted tags`() {+ MemoryStore.ensureDefaults(Settings())+ val check = MemoryStore.validateRecord("t.md", record("note", "Work", "[\"bad,tag\"]"))+ assertFalse(check.valid)+ assertTrue(check.errors.any { it.contains("bad,tag") })+ }++ @Test+ fun `validateRecord accepts block scalars`() {+ MemoryStore.ensureDefaults(Settings())+ val body = listOf(+ "---",+ "title: T",+ "area: Work",+ "type: note",+ "updated: 2026-10-29",+ "summary: |",+ " first line without a colon",+ " second: still part of the value",+ "---",+ "",+ "Body.",+ ""+ ).joinToString("\n")+ val check = MemoryStore.validateRecord("b.md", body)+ assertTrue(check.errors.toString(), check.valid)+ }++ @Test+ fun `validateRecord enforces type per directory`() {+ MemoryStore.ensureDefaults(Settings())+ val misplaced = MemoryStore.validateRecord("work.md", record("note", "Work"), "areas")+ assertFalse(misplaced.valid)+ assertTrue(misplaced.errors.any { it.contains("areas/") })+ assertTrue(MemoryStore.validateRecord("work.md", record("area", "Work"), "areas").valid)+ assertTrue(MemoryStore.validateRecord("asha.md", record("person", "People"), "people").valid)+ assertTrue(MemoryStore.validateRecord("sync.md", record("decision", "Work"), "notes").valid)+ // Without directory context the type check stays lenient.+ assertTrue(MemoryStore.validateRecord("work.md", record("note", "Work")).valid)+ }++ @Test+ fun `area bootstrap accepts the new hub name`() {+ MemoryStore.ensureDefaults(Settings())+ assertFalse(MemoryStore.isKnownArea("Research"))+ val check = MemoryStore.validateRecord("Research.md", record("area", "Research"), "areas")+ assertTrue(check.errors.toString(), check.valid)+ }++ @Test+ fun `ensureDefaults migrates legacy hubs`() {+ MemoryStore.ensureDefaults(Settings())+ val hub = File(GotchaStorage.memoryAreasDir(), "work.md")+ hub.writeText("# Work\n\nLegacy plain markdown.\n")+ MemoryStore.ensureDefaults(Settings())+ val text = hub.readText()+ assertTrue(text.lines().first() == "---")+ assertTrue(text.contains("Legacy plain markdown."))+ val check = MemoryStore.validateRecord(hub.name, text, "areas")+ assertTrue(check.errors.toString(), check.valid)+ }}diff --git a/app/src/test/java/com/gotcha/tools/FileToolsTest.kt b/app/src/test/java/com/gotcha/tools/FileToolsTest.ktindex 7fc76a7..8213045 100644--- a/app/src/test/java/com/gotcha/tools/FileToolsTest.kt+++ b/app/src/test/java/com/gotcha/tools/FileToolsTest.kt@@ -2,6 +2,9 @@ package com.gotcha.toolsimport android.content.Contextimport androidx.test.core.app.ApplicationProvider+import com.gotcha.data.GotchaStorage+import com.gotcha.data.MemoryStore+import com.gotcha.data.Settingsimport com.gotcha.testsupport.ShadowExternalStorageManagerimport org.junit.Afterimport org.junit.Assert.assertEquals@@ -121,6 +124,146 @@ class FileToolsTest {assertEquals("replaced", target.readText())}+ // ---- memory schema gate (Second Brain Phase 1) ----++ private fun withMemoryRoot(block: () -> Unit) {+ val savedRoot = GotchaStorage.rootPath+ GotchaStorage.rootPath = File(workDir, "Gotcha").absolutePath+ try {+ MemoryStore.ensureDefaults(Settings())+ block()+ } finally {+ GotchaStorage.rootPath = savedRoot+ }+ }++ private fun goodMemoryRecord(): String = listOf(+ "---",+ "title: Trip Plan",+ "area: Personal",+ "type: note",+ "tags: [travel]",+ "updated: 2026-10-29",+ "---",+ "",+ "# Trip Plan",+ "",+ "Body here.",+ ""+ ).joinToString("\n")++ @Test+ fun `write_file rejects memory records with bad frontmatter`() {+ withMemoryRoot {+ val target = File(GotchaStorage.memoryNotesDir(), "bad.md").absolutePath++ val result = fileTool.writeFile(target, "# No frontmatter\n\nBody.\n")++ assertFalse(result.message, result.success)+ assertTrue(result.message, result.message.contains("frontmatter"))+ assertFalse(File(target).exists())+ }+ }++ @Test+ fun `write_file accepts memory records with valid frontmatter`() {+ withMemoryRoot {+ val target = File(GotchaStorage.memoryNotesDir(), "good.md").absolutePath++ val result = fileTool.writeFile(target, goodMemoryRecord())++ assertTrue(result.message, result.success)+ assertTrue(File(target).exists())+ }+ }++ @Test+ fun `edit rejects changes that break memory frontmatter`() {+ withMemoryRoot {+ val target = File(GotchaStorage.memoryNotesDir(), "note.md").absolutePath+ assertTrue(fileTool.writeFile(target, goodMemoryRecord()).success)++ val bad = editTool.edit(target, "type: note", "type: nonsense", replaceAll = false)+ assertFalse(bad.message, bad.success)+ assertTrue(bad.message, bad.message.contains("nonsense"))+ assertTrue(File(target).readText().contains("type: note"))++ val good = editTool.edit(target, "Body here.", "Body updated.", replaceAll = false)+ assertTrue(good.message, good.success)+ }+ }++ @Test+ fun `write_file append without frontmatter is rejected`() {+ withMemoryRoot {+ val target = File(GotchaStorage.memoryNotesDir(), "appended.md").absolutePath++ val result = fileTool.writeFile(target, "# No frontmatter\n", append = true)++ assertFalse(result.message, result.success)+ assertTrue(result.message, result.message.contains("frontmatter"))+ assertFalse(File(target).exists())+ }+ }++ @Test+ fun `write_file appends body to a valid record`() {+ withMemoryRoot {+ val target = File(GotchaStorage.memoryNotesDir(), "append-ok.md").absolutePath+ assertTrue(fileTool.writeFile(target, goodMemoryRecord()).success)++ val result = fileTool.writeFile(target, "\nMore body.\n", append = true)++ assertTrue(result.message, result.success)+ assertTrue(File(target).readText().contains("More body."))+ }+ }++ @Test+ fun `write_file rejects binary writes to memory records`() {+ withMemoryRoot {+ val target = File(GotchaStorage.memoryNotesDir(), "bin.md").absolutePath++ val result = fileTool.writeFile(target, "aGk=", binary = true)++ assertFalse(result.message, result.success)+ assertTrue(result.message, result.message.contains("Markdown text"))+ assertFalse(File(target).exists())+ }+ }++ @Test+ fun `write_file rejects replacing dated notes but edit can link forward`() {+ withMemoryRoot {+ val dated = listOf(+ "---",+ "title: Sync",+ "area: Personal",+ "type: note",+ "updated: 2026-10-20",+ "---",+ "",+ "Old decision.",+ ""+ ).joinToString("\n")+ val target = File(GotchaStorage.memoryNotesDir(), "2026-10-20-sync.md").absolutePath+ assertTrue(fileTool.writeFile(target, dated).success)++ val overwrite = fileTool.writeFile(target, dated.replace("Old decision.", "New decision."))+ assertFalse(overwrite.message, overwrite.success)+ assertTrue(overwrite.message, overwrite.message.contains("append-only"))+ assertTrue(File(target).readText().contains("Old decision."))++ val link = editTool.edit(+ target,+ "Old decision.",+ "Superseded by [[notes/2026-10-29-sync.md]]\n\nOld decision.",+ replaceAll = false+ )+ assertTrue(link.message, link.success)+ }+ }+// ---- list_files ----@Test