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 2: memory-task links, duplicate guard, health (#156)
Rishabh Bajpai3c02816dab03
diff --git a/app/src/main/assets/skills/memory.json b/app/src/main/assets/skills/memory.jsonindex c24f02a..992f535 100644--- a/app/src/main/assets/skills/memory.json+++ b/app/src/main/assets/skills/memory.json@@ -16,7 +16,10 @@"user card","digest","frontmatter",- "second brain"+ "second brain",+ "scheduled task",+ "duplicate",+ "health"],- "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."+ "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, next_action (the one concrete follow-up), task_ref (a scheduled task id). 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\nTask links: when a note commits to dated work, create the scheduled task with schedule_agent_task passing memory_note (the note's absolute path), and write the approved task id back into the note's task_ref frontmatter plus the concrete follow-up into next_action. Link both ways or not at all: a task whose note is deleted gets its link cleared with edit_scheduled_task, and a note whose task is deleted loses its task_ref. The viewer flags notes pointing at unknown task ids.\n\nDuplicate guard: before creating a person, area or note, grep memory for the name and compare slugs (\"Asha Sharma\" is asha-sharma). If a card or note already covers it, update that file instead of creating a second one. One fact in one place.\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. The viewer shows a health row (unlinked files, dangling links, records failing the schema, notes pointing at deleted tasks): work through it when the user asks for a cleanup.\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 1162348..6b85957 100644--- a/app/src/main/java/com/gotcha/data/MemoryStore.kt+++ b/app/src/main/java/com/gotcha/data/MemoryStore.kt@@ -175,9 +175,16 @@ object MemoryStore {/** Matches Obsidian-style links: [[path]] or [[path|label]]. */val wikiLinkRegex = Regex("""\[\[([^\]|]+)(?:\|[^\]]*)?]]""")- /** Extracts link targets from markdown, in order, deduplicated. */+ /** Fenced code blocks (backtick or tilde, closed or running to end of file): links inside examples are not real links. */+ private val fenceRegex = Regex("(?s)(```|~~~).*?(\\1|\\Z)")++ /** Extracts link targets from markdown prose, in order, deduplicated. */fun parseWikiLinks(markdown: String): List<String> =- wikiLinkRegex.findAll(markdown).map { it.groupValues[1].trim() }.filter { it.isNotEmpty() }.distinct().toList()+ wikiLinkRegex.findAll(fenceRegex.replace(markdown, ""))+ .map { it.groupValues[1].trim() }+ .filter { it.isNotEmpty() }+ .distinct()+ .toList()/** One node on the Second Brain graph. */data class BrainNode(val id: String, val label: String, val kind: String)@@ -201,30 +208,66 @@ object MemoryStore {* [LINK_SCAN_CAP_CHARS].*/fun buildGraph(snapshot: SecondBrainSnapshot): BrainGraph {- val nodes = mutableListOf<BrainNode>()- val byFull = mutableMapOf<String, String>()- fun norm(path: String): String = path.lowercase().removeSuffix(".md").removeSuffix(".markdown")- fun relId(file: BrainFile, fallback: String): String {- val abs = file.absolutePath- if (abs.isNotBlank()) {- val root = runCatching { GotchaStorage.memoryRoot().absolutePath }.getOrNull()- if (root != null && abs.startsWith(root)) {- return abs.removePrefix(root).trimStart('/')- }+ val index = buildNodeIndex(snapshot)+ return BrainGraph(index.nodes, graphEdges(index, null).toList())+ }++ /**+ * Graph edges from [index]. When [texts] is supplied the preloaded bounded+ * file contents are used; otherwise each file is read on demand. Sharing+ * one read per file keeps the health check cheap on large vaults.+ */+ private fun graphEdges(index: NodeIndex, texts: Map<String, String>?): Set<BrainEdge> {+ val edges = mutableSetOf<BrainEdge>()+ index.sources.forEach { source ->+ if (!source.file.isMarkdown) return@forEach+ val text = texts?.get(source.id) ?: fullTextForLinks(source.file)+ parseWikiLinks(text).forEach { target ->+ val toId = resolveGraphLink(target, source.id, index)+ if (toId != null && toId != source.id) edges.add(BrainEdge(source.id, toId))}- return fallback}- data class Source(val id: String, val file: BrainFile)- val sources = mutableListOf<Source>()+ return edges+ }++ /** One link source: a graph node id plus its file. */+ private data class GraphSource(val id: String, val file: BrainFile)++ /** Graph nodes, link sources and the normalized path index, shared by the graph and health checks. */+ private data class NodeIndex(+ val nodes: List<BrainNode>,+ val sources: List<GraphSource>,+ val byFull: Map<String, String>+ )++ private fun normGraphPath(path: String): String =+ path.lowercase().removeSuffix(".md").removeSuffix(".markdown")++ /** Memory-relative id (areas/work.md) from the absolute path, or [fallback]. */+ fun relativeMemoryId(file: BrainFile, fallback: String): String {+ val abs = file.absolutePath+ if (abs.isNotBlank()) {+ val root = runCatching { GotchaStorage.memoryRoot().absolutePath }.getOrNull()+ if (root != null && abs.startsWith(root)) {+ return abs.removePrefix(root).trimStart('/')+ }+ }+ return fallback+ }++ private fun buildNodeIndex(snapshot: SecondBrainSnapshot): NodeIndex {+ val nodes = mutableListOf<BrainNode>()+ val byFull = mutableMapOf<String, String>()+ val sources = mutableListOf<GraphSource>()fun addNode(id: String, label: String, kind: String) {nodes.add(BrainNode(id, label, kind))- byFull.putIfAbsent(norm(id), id)+ byFull.putIfAbsent(normGraphPath(id), id)}fun addSource(file: BrainFile?, fallbackId: String, label: String, kind: String) {if (file == null) return- val id = relId(file, fallbackId)+ val id = relativeMemoryId(file, fallbackId)addNode(id, label, kind)- sources.add(Source(id, file))+ sources.add(GraphSource(id, file))}addSource(snapshot.soul, "SOUL.md", "SOUL", "soul")addSource(snapshot.memoryIndex, "MEMORY.md", "MEMORY", "map")@@ -233,38 +276,252 @@ 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, 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")+ return NodeIndex(nodes, sources, byFull)+ }++ /**+ * Resolves one [[link]] target to a node id, or null when dangling,+ * self-pointing or ambiguous. Source-relative first, vault-relative+ * second, unique bare names last.+ */+ private fun resolveGraphLink(target: String, sourceId: String, index: NodeIndex): String? {+ val raw = target.trim()+ if (raw.isEmpty()) return null+ graphCandidates(raw, sourceId).forEach { candidate ->+ index.byFull[normGraphPath(candidate)]?.let { return it }+ }+ // (c) Bare-name fallback only when it names exactly one node.+ val base = normGraphPath(raw).substringAfterLast('/')+ return index.nodes+ .filter { normGraphPath(it.id).substringAfterLast('/') == base }+ .map { it.id }+ .singleOrNull()+ }++ /** Ordered lookup paths for a link target: source-relative, then vault-relative. */+ private fun graphCandidates(raw: String, sourceId: String): List<String> {+ val sourceDir = sourceId.substringBeforeLast('/', "")+ return buildList {+ if (sourceDir.isNotEmpty()) {+ add("$sourceDir/$raw")+ add("$sourceDir/$raw.md")+ add("$sourceDir/$raw.markdown")}- candidates.forEach { candidate ->- byFull[norm(candidate)]?.let { return it }+ add(raw)+ add("$raw.md")+ add("$raw.markdown")+ }+ }++ /**+ * True when [target] matches several nodes by bare name without matching+ * any relative or vault path: ambiguous, not missing. The graph draws no+ * edge for these either, so health does not report them as dangling.+ */+ private fun hasAmbiguousMatches(target: String, sourceId: String, index: NodeIndex): Boolean {+ val raw = target.trim()+ if (raw.isEmpty()) return false+ if (graphCandidates(raw, sourceId).any { index.byFull.containsKey(normGraphPath(it)) }) return false+ val base = normGraphPath(raw).substringAfterLast('/')+ return index.nodes.count { normGraphPath(it.id).substringAfterLast('/') == base } > 1+ }++ /** One [[link]] that points nowhere (or at its own file). */+ data class DanglingLink(val fromId: String, val target: String)++ /** One detail record that fails the schema, with its reasons. */+ data class RecordProblem(val fileId: String, val errors: List<String>)++ /** One note whose `task_ref` names a task id no scheduled task carries. */+ data class TaskNoteRef(val fileId: String, val taskId: String)++ /** One scheduled task for the health check: id, display name and linked note path. */+ data class TaskLink(val id: String, val name: String, val notePath: String?)++ /** One note whose `task_ref` names a task that points at a different note (or nowhere). */+ data class TaskMismatch(val fileId: String, val taskId: String, val linkedPath: String?)++ /** One scheduled task whose linked note no longer exists in the vault. */+ data class StaleTaskLink(val taskName: String, val path: String)++ /** Orphan dashboard: everything that keeps the Second Brain from hanging together. */+ data class BrainHealth(+ val unlinked: List<String>,+ val dangling: List<DanglingLink>,+ val invalid: List<RecordProblem>,+ val unknownTasks: List<TaskNoteRef>,+ val mismatchedTasks: List<TaskMismatch> = emptyList(),+ val staleTaskLinks: List<StaleTaskLink> = emptyList(),+ val unscanned: List<String> = emptyList()+ ) {+ val isClean: Boolean+ get() = unlinked.isEmpty() && dangling.isEmpty() && invalid.isEmpty() &&+ unknownTasks.isEmpty() && mismatchedTasks.isEmpty() &&+ staleTaskLinks.isEmpty() && unscanned.isEmpty()+ val issueCount: Int+ get() = unlinked.size + dangling.size + invalid.size + unknownTasks.size ++ mismatchedTasks.size + staleTaskLinks.size + unscanned.size+ }++ /** Root files are navigation hubs, not content: never reported as unlinked. */+ private val healthRootIds = setOf("SOUL.md", "MEMORY.md", "user.md")++ /**+ * Checks the whole vault for orphans: nodes with no links in or out,+ * [[links]] that resolve nowhere, detail records failing the schema, notes+ * whose `task_ref` names an unknown or mismatched task, tasks pointing at+ * deleted notes, and files too large for the link scan. Each file is read+ * once, bounded by [LINK_SCAN_CAP_CHARS].+ */+ fun checkHealth(+ snapshot: SecondBrainSnapshot,+ taskLinks: List<TaskLink> = emptyList()+ ): BrainHealth {+ val index = buildNodeIndex(snapshot)+ val texts = index.sources+ .filter { it.file.isMarkdown }+ .associate { it.id to fullText(it.file) }+ val linked = graphEdges(index, texts).flatMap { listOf(it.fromId, it.toId) }.toSet()+ val unlinked = index.nodes+ .map { it.id }+ .filter { it !in linked && it !in healthRootIds }+ .sorted()+ val dangling = danglingFor(index, texts)+ val byTaskId = taskLinks.associateBy { it.id }+ val vaultNotePaths = detailFiles(snapshot).mapNotNull { (file, _) ->+ runCatching { File(file.absolutePath).canonicalPath }.getOrNull()+ }.toSet()+ val invalid = mutableListOf<RecordProblem>()+ val unknownTasks = mutableListOf<TaskNoteRef>()+ val mismatched = mutableListOf<TaskMismatch>()+ val unscanned = mutableListOf<String>()+ detailFiles(snapshot).forEach { (file, dirKind) ->+ val id = relativeMemoryId(file, "$dirKind/${file.name}")+ val full = texts[id] ?: fullText(file)+ if ((texts[id]?.length ?: 0) > LINK_SCAN_CAP_CHARS) unscanned.add(id)+ val check = validateRecord(file.name, full, dirKind)+ if (!check.valid) invalid.add(RecordProblem(id, check.errors))+ frontmatterOf(full)?.get("task_ref")?.takeIf { it.isNotBlank() }?.let { ref ->+ val task = byTaskId[ref]+ when {+ task == null -> unknownTasks.add(TaskNoteRef(id, ref))+ task.notePath == null || !samePath(task.notePath, file.absolutePath) ->+ mismatched.add(TaskMismatch(id, ref, task.notePath))+ }}- // (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, source.id)- if (toId != null && toId != source.id) edges.add(BrainEdge(source.id, toId))+ val stale = taskLinks.mapNotNull { task ->+ val path = task.notePath ?: return@mapNotNull null+ if (vaultNotePaths.none { samePath(it, path) }) StaleTaskLink(task.name, path) else null+ }+ return BrainHealth(+ unlinked.sorted(),+ dangling,+ invalid,+ unknownTasks,+ mismatched,+ stale,+ unscanned.sorted()+ )+ }++ /** Every detail record with its top-level dir for schema checks. */+ private fun detailFiles(snapshot: SecondBrainSnapshot): List<Pair<BrainFile, String>> =+ snapshot.areas.map { it to "areas" } ++ snapshot.people.map { it to "people" } ++ snapshot.notes.map { it to "notes" }++ /** Links that resolve nowhere, in stable order. Self-links count: they draw nothing. */+ fun findDanglingLinks(snapshot: SecondBrainSnapshot): List<DanglingLink> {+ val index = buildNodeIndex(snapshot)+ val texts = index.sources.associate { it.id to fullText(it.file) }+ return danglingFor(index, texts)+ }++ /**+ * Dangling links from preloaded [texts]. Ambiguous bare names are skipped:+ * they match several files rather than none.+ */+ private fun danglingFor(index: NodeIndex, texts: Map<String, String>): List<DanglingLink> {+ return index.sources+ .filter { it.file.isMarkdown }+ .flatMap { source ->+ val text = texts[source.id] ?: fullText(source.file)+ parseWikiLinks(text).mapNotNull { target ->+ val toId = resolveGraphLink(target, source.id, index)+ when {+ toId == null && !hasAmbiguousMatches(target, source.id, index) ->+ DanglingLink(source.id, target)+ toId != null && toId == source.id -> DanglingLink(source.id, target)+ else -> null+ }+ }}+ .distinct()+ .sortedWith(compareBy({ it.fromId }, { it.target }))+ }++ /** True when two paths name the same file, best-effort. */+ private fun samePath(a: String, b: String): Boolean {+ if (a == b) return true+ return runCatching { File(a).canonicalPath == File(b).canonicalPath }.getOrDefault(false)+ }++ /** Frontmatter values of [content], or null when it carries none. Errors are ignored. */+ private fun frontmatterOf(content: String): Map<String, String>? {+ val lines = content.lines()+ if (lines.isEmpty() || lines[0].trim() != "---") return null+ val end = lines.drop(1).indexOfFirst { it.trim() == "---" }+ if (end < 0) return null+ val values = mutableMapOf<String, String>()+ parseFrontmatterLines("", lines.drop(1).take(end), values, mutableListOf())+ return values+ }++ /** Full text for checks that must see past the viewer preview cap. */+ private fun fullText(file: BrainFile): String {+ val abs = file.absolutePath+ if (abs.isNotBlank()) {+ readUpTo(File(abs), LINK_SCAN_CAP_CHARS)?.let { return it }+ }+ return file.content+ }++ /**+ * Duplicate guard: slug of a title or file name, so "Asha Sharma",+ * "asha-sharma.md" and "Asha-Sharma" all compare equal. The agent checks+ * this (and greps) before creating a person, area or note.+ */+ fun slugify(text: String): String =+ text.lowercase()+ .map { if (it.isLetterOrDigit()) it else '-' }+ .joinToString("")+ .replace(Regex("-+"), "-")+ .trim('-')++ /** Strips a real record extension (.md, .markdown); dots inside titles are kept. */+ private fun stripRecordExtension(name: String): String {+ val lower = name.lowercase()+ return when {+ lower.endsWith(".markdown") -> name.dropLast(".markdown".length)+ lower.endsWith(".md") -> name.dropLast(".md".length)+ else -> name}- return BrainGraph(nodes, edges.toList())+ }++ /**+ * Ids of existing records that likely duplicate [title]: same slug as the+ * file base name or the frontmatter title. Empty when there is no clash.+ */+ fun findPossibleDuplicates(title: String, snapshot: SecondBrainSnapshot): List<String> {+ val slug = slugify(stripRecordExtension(title.substringAfterLast('/')))+ if (slug.isEmpty()) return emptyList()+ return detailFiles(snapshot).mapNotNull { (file, dirKind) ->+ val id = relativeMemoryId(file, "$dirKind/${file.name}")+ val baseSlug = slugify(stripRecordExtension(id.substringAfterLast('/')))+ val titleSlug = frontmatterOf(file.content)?.get("title")?.let { slugify(it) }+ if (slug == baseSlug || slug == titleSlug) id else null+ }.distinct().sorted()}/** Max chars scanned per file for [[link]] parsing (preview cap stays smaller). */@@ -428,7 +685,7 @@ object MemoryStore {return try {if (!dir.exists() || !dir.isDirectory) return emptyList()dir.listFiles()- ?.filter { it.isFile && it.name.substringAfterLast('.', "").lowercase() == "md" }+ ?.filter { it.isFile && it.name.substringAfterLast('.', "").lowercase() in setOf("md", "markdown") }?.sortedBy { it.name.lowercase() }?.mapNotNull { loadBrainFile(it) }.orEmpty()@@ -480,7 +737,8 @@ object MemoryStore {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"+ "source", "source_file", "stage", "project", "summary",+ "next_action", "task_ref")/** Record types. Hub files in areas/ use `area`. */@@ -627,8 +885,10 @@ object MemoryStore {}}}- if (values.containsKey("source") && values["source"].isNullOrBlank()) {- errors.add("$fileName: 'source' is present but blank.")+ listOf("source", "source_file", "next_action", "task_ref").forEach { key ->+ if (values.containsKey(key) && values[key].isNullOrBlank()) {+ errors.add("$fileName: '$key' is present but blank.")+ }}}diff --git a/app/src/main/java/com/gotcha/scheduled/ScheduledTask.kt b/app/src/main/java/com/gotcha/scheduled/ScheduledTask.ktindex cb6b3b4..e87423a 100644--- a/app/src/main/java/com/gotcha/scheduled/ScheduledTask.kt+++ b/app/src/main/java/com/gotcha/scheduled/ScheduledTask.kt@@ -93,6 +93,12 @@ data class ScheduledTask(val createdByAgent: Boolean = false,/** Names of the files stored with the task; the files themselves are in [ScheduledTaskStore]. */val attachmentNames: List<String> = emptyList(),+ /**+ * Absolute path of the memory note this task works off (a people/, areas/+ * or notes/ record), or null when unlinked. The note names the task back+ * in its `task_ref` frontmatter: the Second Brain link both ways.+ */+ val memoryNotePath: String? = null,val createdAt: Long = 0L,val nextRunAt: Long? = null,val retryAt: Long? = null,diff --git a/app/src/main/java/com/gotcha/tools/ScheduledTaskTool.kt b/app/src/main/java/com/gotcha/tools/ScheduledTaskTool.ktindex ba20678..67e5d62 100644--- a/app/src/main/java/com/gotcha/tools/ScheduledTaskTool.kt+++ b/app/src/main/java/com/gotcha/tools/ScheduledTaskTool.kt@@ -5,6 +5,8 @@ import com.gotcha.agent.AttachmentFilesimport com.gotcha.agent.ChatTitleimport com.gotcha.agent.ComposerAttachmentimport com.gotcha.data.ChatHistoryRepository+import com.gotcha.data.GotchaStorage+import com.gotcha.data.MemoryStoreimport com.gotcha.i18n.stringLookupimport com.gotcha.scheduled.Repeatimport com.gotcha.scheduled.RepeatKind@@ -15,6 +17,7 @@ import com.gotcha.scheduled.ScheduledTaskStoreimport kotlinx.serialization.Serializableimport kotlinx.serialization.json.Jsonimport kotlinx.serialization.json.JsonArray+import kotlinx.serialization.json.JsonNullimport kotlinx.serialization.json.JsonObjectimport kotlinx.serialization.json.JsonPrimitiveimport kotlinx.serialization.json.booleanOrNull@@ -47,7 +50,11 @@ data class ScheduleRequest(val sameChat: Boolean? = null,val mode: String? = null,val files: List<String>? = null,- val enabled: Boolean? = null+ val enabled: Boolean? = null,+ /** Absolute path of the memory note linked both ways, or null to leave the link as it is. */+ val memoryNote: String? = null,+ /** True when `memory_note` was passed blank: unlink the task from its note. */+ val clearMemoryNote: Boolean = false) {val isCreate: Boolean get() = taskId == null}@@ -98,6 +105,13 @@ class ScheduledTaskTool(}val mode = parseMode(args).getOrElse { return ToolResult.error(it.message.orEmpty()) }val files = checkFiles(args).getOrElse { return ToolResult.error(it.message.orEmpty()) }+ val memoryNote = checkMemoryNoteArg(+ args,+ fileResolver+ ).getOrElse { return ToolResult.error(it.message.orEmpty()) }+ val clearMemoryNote = args["memory_note"]?.let { element ->+ element is JsonPrimitive && element !is JsonNull && element.content.trim().isEmpty()+ } ?: falsereturn confirm(ScheduleRequest(name = name,@@ -106,7 +120,9 @@ class ScheduledTaskTool(repeat = repeat,sameChat = args.boolean("same_chat") ?: false,mode = mode?.name,- files = files+ files = files,+ memoryNote = memoryNote,+ clearMemoryNote = clearMemoryNote))}@@ -126,6 +142,10 @@ class ScheduledTaskTool(}val mode = parseMode(args).getOrElse { return ToolResult.error(it.message.orEmpty()) }val files = checkFiles(args).getOrElse { return ToolResult.error(it.message.orEmpty()) }+ val memoryNote = checkMemoryNoteArg(+ args,+ fileResolver+ ).getOrElse { return ToolResult.error(it.message.orEmpty()) }val request = ScheduleRequest(taskId = existing.id,name = args.string("name")?.trim()?.take(MAX_NAME)?.ifEmpty { null },@@ -135,7 +155,11 @@ class ScheduledTaskTool(sameChat = args.boolean("same_chat"),mode = mode?.name,files = files,- enabled = args.boolean("enabled")+ enabled = args.boolean("enabled"),+ memoryNote = memoryNote,+ clearMemoryNote = args["memory_note"]?.let { element ->+ element is JsonPrimitive && element !is JsonNull && element.content.trim().isEmpty()+ } ?: false)if (request == ScheduleRequest(taskId = existing.id)) {return ToolResult.error("Nothing to change: pass at least one field to edit.")@@ -156,6 +180,7 @@ class ScheduledTaskTool(append("; ${task.mode.name.lowercase()} mode")append(if (task.sameChat) "; same chat" else "; new chat each time")if (task.attachmentNames.isNotEmpty()) append("; files: ${task.attachmentNames.joinToString()}")+ task.memoryNotePath?.let { append("; memory note: ${shortenMemoryPath(it)}") }append(if (task.createdByAgent) "; set up by you" else "; set up by the user")task.lastRun?.let { append("; last run: ${it.status.name.lowercase()} at ${formatInstant(it.at)}") }append("\n prompt: ${task.prompt.take(LIST_PROMPT_CHARS)}")@@ -207,6 +232,7 @@ class ScheduledTaskTool(})if (files.isNotEmpty()) append("Files: ${files.joinToString()}\n")+ appendMemoryNoteLine(request, existing)request.enabled?.let { append(if (it) "Turns the task on\n" else "Pauses the task\n") }append("Prompt: ${request.prompt ?: existing?.prompt}")}@@ -240,7 +266,12 @@ class ScheduledTaskTool(base.chatSessionId},enabled = request.enabled ?: base.enabled,- attachmentNames = attachments?.map { it.name } ?: base.attachmentNames+ attachmentNames = attachments?.map { it.name } ?: base.attachmentNames,+ memoryNotePath = if (request.clearMemoryNote) {+ null+ } else {+ request.memoryNote ?: base.memoryNotePath+ })}val saved = if (existing == null) {@@ -315,6 +346,15 @@ class ScheduledTaskTool()}+ /** Approval line for the task's memory link: set, kept, or removed. */+ private fun StringBuilder.appendMemoryNoteLine(request: ScheduleRequest, existing: ScheduledTask?) {+ if (request.clearMemoryNote && existing?.memoryNotePath != null) {+ append("Memory note: (removed)\n")+ return+ }+ (request.memoryNote ?: existing?.memoryNotePath)?.let { append("Memory note: $it\n") }+ }+/** The `files` argument, each checked to be a readable file and made canonical. */private fun checkFiles(args: JsonObject): Result<List<String>?> {val paths = (args["files"] as? JsonArray)?.mapNotNull { (it as? JsonPrimitive)?.content?.trim() }@@ -379,7 +419,11 @@ class ScheduledTaskTool(LocalDateTime.ofInstant(Instant.ofEpochMilli(at), zone()).format(DISPLAY_FORMAT)private fun JsonObject.string(key: String): String? =- (this[key] as? JsonPrimitive)?.takeIf { it.isString || it.content.isNotEmpty() }?.content+ when (val element = this[key]) {+ is JsonNull -> null+ is JsonPrimitive -> element.takeIf { it.isString || it.content.isNotEmpty() }?.content+ else -> null+ }private fun JsonObject.boolean(key: String): Boolean? =(this[key] as? JsonPrimitive)?.let { it.booleanOrNull ?: it.content.trim().toBooleanStrictOrNull() }@@ -447,3 +491,43 @@ class ScheduledTaskTool(}}}++/** The `memory_note` argument: an existing memory record (people/, areas/, notes/), canonicalised. */+private fun checkMemoryNoteArg(args: JsonObject, fileResolver: FileResolver): Result<String?> {+ val element = args["memory_note"] ?: return Result.success(null)+ if (element is JsonNull) return Result.success(null)+ val raw = (element as? JsonPrimitive)?.content?.trim().orEmpty()+ if (raw.isEmpty()) return Result.success(null)+ val file = when (val resolved = fileResolver.resolveForRead(raw)) {+ is FileResolver.ResolveResult.Ok -> resolved.file+ is FileResolver.ResolveResult.PermissionNeeded ->+ return Result.failure(IllegalArgumentException(resolved.result.message))+ is FileResolver.ResolveResult.Error ->+ return Result.failure(IllegalArgumentException(resolved.message))+ }+ if (!file.isFile || !file.canRead()) {+ return Result.failure(IllegalArgumentException("No readable file at '$raw'."))+ }+ if (MemoryStore.recordDirKind(file) == null) {+ return Result.failure(+ IllegalArgumentException(+ "'$raw' is not a memory note, person card or area hub: " ++ "link a file under Gotcha/memory people/, areas/ or notes/."+ )+ )+ }+ return Result.success(file.canonicalPath)+}++/** Memory-root-relative display path (`notes/plan.md`), so same-named files stay apart in listings. */+private fun shortenMemoryPath(path: String): String {+ return runCatching {+ val root = GotchaStorage.memoryRoot().canonicalPath+ val canonical = File(path).canonicalPath+ if (canonical.startsWith(root + File.separator)) {+ canonical.removePrefix(root + File.separator)+ } else {+ File(path).name+ }+ }.getOrDefault(File(path).name)+}diff --git a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt b/app/src/main/java/com/gotcha/tools/ToolDefinitions.ktindex 92ceb9c..b7b5f9e 100644--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt@@ -3069,6 +3069,15 @@ object ToolDefinitions {putJsonObject("items") { put("type", "string") }put("description", "Paths of files sent with the prompt each time (read once, when saved). At most 10.")}+ putJsonObject("memory_note") {+ put("type", "string")+ put(+ "description",+ "Absolute path of the memory note, person card or area hub this task works off " ++ "(under Gotcha/memory people/, areas/ or notes/). Links both ways: the note names " ++ "the task id back in its task_ref frontmatter. Pass an empty string to unlink. Optional."+ )+ }}val scheduleAgentTask = tool(diff --git a/app/src/main/java/com/gotcha/ui/SecondBrainScreen.kt b/app/src/main/java/com/gotcha/ui/SecondBrainScreen.ktindex 8f114be..a228ad4 100644--- a/app/src/main/java/com/gotcha/ui/SecondBrainScreen.kt+++ b/app/src/main/java/com/gotcha/ui/SecondBrainScreen.kt@@ -51,6 +51,7 @@ import androidx.compose.ui.unit.spimport androidx.core.content.FileProviderimport com.gotcha.Rimport com.gotcha.data.MemoryStore+import com.gotcha.scheduled.ScheduledTaskStoreimport com.gotcha.tools.FileResolverimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.withContext@@ -71,11 +72,23 @@ import kotlin.math.sin@Composablefun SecondBrainScreen(onBack: () -> Unit) {val overlay = rememberSettingsOverlayState()+ val context = LocalContext.currentvar snapshot by remember { mutableStateOf<MemoryStore.SecondBrainSnapshot?>(null) }+ var health by remember { mutableStateOf<MemoryStore.BrainHealth?>(null) }var showGraph by remember { mutableStateOf(false) }LaunchedEffect(Unit) {- snapshot = withContext(Dispatchers.IO) { MemoryStore.loadSnapshot() }+ val loaded = withContext(Dispatchers.IO) { MemoryStore.loadSnapshot() }+ snapshot = loaded+ // Health re-reads files and resolves every link: off the main thread.+ health = withContext(Dispatchers.Default) {+ val taskLinks = runCatching {+ ScheduledTaskStore(context).all().map {+ MemoryStore.TaskLink(it.id, it.name, it.memoryNotePath)+ }+ }.getOrDefault(emptyList())+ MemoryStore.checkHealth(loaded, taskLinks)+ }}SettingsScaffold(@@ -179,6 +192,7 @@ fun SecondBrainScreen(onBack: () -> Unit) {files = current.raw,tag = "raw")+ health?.let { BrainHealthSection(health = it) }}}}@@ -981,6 +995,132 @@ private fun BrainFileList(heading: String, files: List<MemoryStore.BrainFile>, tHorizontalDivider(thickness = 1.dp)}+@Composable+private fun BrainHealthSection(health: MemoryStore.BrainHealth) {+ var expanded by remember { mutableStateOf(false) }+ Column(+ modifier = Modifier+ .fillMaxWidth()+ .testTag("settings_second_brain_health")+ ) {+ Text(+ text = (if (expanded) "▼ " else "▶ ") + stringResource(+ if (health.isClean) {+ R.string.second_brain_health_clean+ } else {+ R.string.second_brain_health_title+ },+ health.issueCount+ ),+ style = MaterialTheme.typography.titleMedium,+ fontWeight = FontWeight.Bold,+ modifier = Modifier+ .fillMaxWidth()+ .clickable(+ role = Role.Button,+ onClickLabel = if (expanded) "Collapse" else "Expand"+ ) { expanded = !expanded }+ .padding(vertical = 4.dp)+ )+ if (expanded) {+ if (health.isClean) {+ Text(+ text = stringResource(R.string.second_brain_health_clean_detail),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant+ )+ } else {+ HealthGroup(+ heading = stringResource(+ R.string.second_brain_health_unlinked,+ health.unlinked.size+ ),+ lines = health.unlinked+ )+ HealthGroup(+ heading = stringResource(+ R.string.second_brain_health_dangling,+ health.dangling.size+ ),+ lines = health.dangling.map { "${it.fromId} → [[${it.target}]]" }+ )+ HealthGroup(+ heading = stringResource(+ R.string.second_brain_health_invalid,+ health.invalid.size+ ),+ lines = health.invalid.map { problem ->+ "${problem.fileId}: ${problem.errors.firstOrNull().orEmpty()}"+ }+ )+ HealthGroup(+ heading = stringResource(+ R.string.second_brain_health_unknown_tasks,+ health.unknownTasks.size+ ),+ lines = health.unknownTasks.map { "${it.fileId} → ${it.taskId}" }+ )+ HealthGroup(+ heading = stringResource(+ R.string.second_brain_health_mismatched,+ health.mismatchedTasks.size+ ),+ lines = health.mismatchedTasks.map {+ "${it.fileId} → task points at ${it.linkedPath ?: "(nowhere)"}"+ }+ )+ HealthGroup(+ heading = stringResource(+ R.string.second_brain_health_stale,+ health.staleTaskLinks.size+ ),+ lines = health.staleTaskLinks.map { "\"${it.taskName}\" → ${it.path}" }+ )+ HealthGroup(+ heading = stringResource(+ R.string.second_brain_health_unscanned,+ health.unscanned.size+ ),+ lines = health.unscanned+ )+ }+ }+ }+ HorizontalDivider(thickness = 1.dp)+}++@Composable+private fun HealthGroup(heading: String, lines: List<String>) {+ if (lines.isEmpty()) return+ Text(+ text = heading,+ style = MaterialTheme.typography.bodyMedium,+ fontWeight = FontWeight.Medium,+ modifier = Modifier.padding(top = 4.dp)+ )+ // Cap composed rows so a huge vault cannot jank the settings column.+ val shown = lines.take(HEALTH_GROUP_LIMIT)+ shown.forEach { line ->+ Text(+ text = "• $line",+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ modifier = Modifier.padding(start = 8.dp, top = 1.dp)+ )+ }+ if (lines.size > shown.size) {+ Text(+ text = stringResource(R.string.second_brain_health_more, lines.size - shown.size),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ modifier = Modifier.padding(start = 8.dp, top = 1.dp)+ )+ }+}++/** Max issue rows composed per health group. */+private const val HEALTH_GROUP_LIMIT = 50+/*** Per-file preview: Markdown renders as formatted text, text files as plain* text, and media/binary files (audio, images, video, documents) show filediff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xmlindex fc659fa..8c35599 100644--- a/app/src/main/res/values/strings.xml+++ b/app/src/main/res/values/strings.xml@@ -81,6 +81,17 @@<string name="second_brain_notes">Notes</string><string name="second_brain_raw">Raw files</string><string name="second_brain_empty">Nothing here yet.</string>+ <string name="second_brain_health_title">Health (%1$d issues)</string>+ <string name="second_brain_health_clean">Health: all connected (%1$d issues)</string>+ <string name="second_brain_health_clean_detail">No unlinked files, dangling links, invalid records or notes pointing at missing tasks.</string>+ <string name="second_brain_health_unlinked">Unlinked files (%1$d)</string>+ <string name="second_brain_health_dangling">Dangling links (%1$d)</string>+ <string name="second_brain_health_invalid">Invalid records (%1$d)</string>+ <string name="second_brain_health_unknown_tasks">Notes pointing at missing tasks (%1$d)</string>+ <string name="second_brain_health_mismatched">Notes whose task points elsewhere (%1$d)</string>+ <string name="second_brain_health_stale">Tasks pointing at missing notes (%1$d)</string>+ <string name="second_brain_health_unscanned">Files too large to scan fully (%1$d)</string>+ <string name="second_brain_health_more">…and %1$d more</string><string name="second_brain_truncated">Long file — showing the start only.</string><string name="second_brain_open">Open</string><string name="second_brain_open_failed">No app on this phone can open that file type.</string>diff --git a/app/src/test/java/com/gotcha/data/MemoryStoreTest.kt b/app/src/test/java/com/gotcha/data/MemoryStoreTest.ktindex 6956911..6e79aea 100644--- a/app/src/test/java/com/gotcha/data/MemoryStoreTest.kt+++ b/app/src/test/java/com/gotcha/data/MemoryStoreTest.kt@@ -13,6 +13,7 @@ import org.junit.Testimport java.io.Fileimport java.nio.file.Files+@Suppress("LargeClass")class MemoryStoreTest {private lateinit var tmpRoot: File@@ -533,4 +534,246 @@ class MemoryStoreTest {val check = MemoryStore.validateRecord(hub.name, text, "areas")assertTrue(check.errors.toString(), check.valid)}++ // ---- Phase 2: task links, duplicates, health ----++ @Test+ fun `validateRecord accepts task link fields`() {+ MemoryStore.ensureDefaults(Settings())+ val rec = listOf(+ "---",+ "title: Trip",+ "area: Personal",+ "type: note",+ "tags: [travel]",+ "updated: 2026-10-29",+ "next_action: Book flights",+ "task_ref: 123e4567-e89b-12d3-a456-426614174000",+ "---",+ "",+ "Body.",+ ""+ ).joinToString("\n")+ val check = MemoryStore.validateRecord("trip.md", rec, "notes")+ assertTrue(check.errors.toString(), check.valid)+ }++ @Test+ fun `validateRecord rejects blank task link fields`() {+ MemoryStore.ensureDefaults(Settings())+ val rec = record("note", "Personal").replace("tags: [x]", "tags: [x]\ntask_ref: ")+ val check = MemoryStore.validateRecord("trip.md", rec, "notes")+ assertFalse(check.valid)+ assertTrue(check.errors.any { it.contains("task_ref") })+ }++ @Test+ fun `checkHealth reports orphans`() {+ MemoryStore.ensureDefaults(Settings())+ val notes = GotchaStorage.memoryNotesDir().apply { mkdirs() }+ fun note(name: String, body: String, extra: String = "") {+ File(notes, name).writeText(+ listOf(+ "---",+ "title: $name",+ "area: Personal",+ "type: note",+ "updated: 2026-10-29",+ extra,+ "---",+ "",+ body,+ ""+ ).filter { it.isNotEmpty() }.joinToString("\n")+ )+ }+ note("a.md", "See [[notes/b.md]].")+ note("b.md", "See [[notes/a.md]].")+ note("c.md", "Lonely.")+ note("d.md", "See [[nowhere-at-all]].")+ File(notes, "e.md").writeText("No frontmatter.\n")+ note("f.md", "Waiting on a task.", "task_ref: dead-beef")+ val snap = MemoryStore.loadSnapshot()++ val health = MemoryStore.checkHealth(snap)+ assertTrue(health.unlinked.contains("notes/c.md"))+ assertTrue(health.unlinked.contains("notes/d.md"))+ assertTrue(health.unlinked.contains("notes/e.md"))+ assertTrue(health.unlinked.contains("notes/f.md"))+ assertFalse(health.unlinked.contains("notes/a.md"))+ assertFalse(health.unlinked.contains("notes/b.md"))+ assertFalse(health.unlinked.contains("SOUL.md"))+ assertFalse(health.unlinked.contains("MEMORY.md"))+ assertFalse(health.unlinked.contains("user.md"))+ assertEquals(+ listOf(MemoryStore.DanglingLink("notes/d.md", "nowhere-at-all")),+ health.dangling+ )+ assertEquals(listOf("notes/e.md"), health.invalid.map { it.fileId })+ assertEquals(+ listOf(MemoryStore.TaskNoteRef("notes/f.md", "dead-beef")),+ health.unknownTasks+ )+ assertFalse(health.isClean)++ val linked = MemoryStore.checkHealth(+ snap,+ listOf(MemoryStore.TaskLink("dead-beef", "Task", File(notes, "f.md").absolutePath))+ )+ assertTrue(linked.unknownTasks.isEmpty())+ assertTrue(linked.mismatchedTasks.isEmpty())+ assertTrue(linked.staleTaskLinks.isEmpty())+ }++ @Test+ fun `checkHealth flags mismatched and stale task links`() {+ MemoryStore.ensureDefaults(Settings())+ val notes = GotchaStorage.memoryNotesDir().apply { mkdirs() }+ File(notes, "g.md").writeText(+ listOf(+ "---",+ "title: G",+ "area: Personal",+ "type: note",+ "updated: 2026-10-29",+ "task_ref: real-id",+ "---",+ "",+ "Body.",+ ""+ ).joinToString("\n")+ )+ File(notes, "h.md").writeText(+ listOf(+ "---",+ "title: H",+ "area: Personal",+ "type: note",+ "updated: 2026-10-29",+ "task_ref: lonely-id",+ "---",+ "",+ "Body.",+ ""+ ).joinToString("\n")+ )+ val snap = MemoryStore.loadSnapshot()+ val health = MemoryStore.checkHealth(+ snap,+ listOf(+ MemoryStore.TaskLink("real-id", "Task", "/other/note.md"),+ MemoryStore.TaskLink("lonely-id", "Lonely", null)+ )+ )+ assertTrue(health.unknownTasks.isEmpty())+ assertTrue(+ health.mismatchedTasks.contains(+ MemoryStore.TaskMismatch("notes/g.md", "real-id", "/other/note.md")+ )+ )+ assertTrue(+ health.mismatchedTasks.contains(+ MemoryStore.TaskMismatch("notes/h.md", "lonely-id", null)+ )+ )+ assertEquals(+ listOf(MemoryStore.StaleTaskLink("Task", "/other/note.md")),+ health.staleTaskLinks+ )+ assertFalse(health.isClean)+ }++ @Test+ fun `checkHealth flags files past the link scan cap`() {+ MemoryStore.ensureDefaults(Settings())+ val notes = GotchaStorage.memoryNotesDir().apply { mkdirs() }+ val filler = "x".repeat(MemoryStore.LINK_SCAN_CAP_CHARS)+ File(notes, "big.md").writeText(+ record("note", "Personal").replace("Body.", "See [[areas/work.md]].\n\n$filler")+ )+ val snap = MemoryStore.loadSnapshot()+ val health = MemoryStore.checkHealth(snap)+ assertTrue(health.unscanned.contains("notes/big.md"))+ // The link at the start still resolves, so no false unlinked/dangling.+ assertFalse(health.unlinked.contains("notes/big.md"))+ assertTrue(health.dangling.none { it.fromId == "notes/big.md" })+ }++ @Test+ fun `ambiguous bare names are not dangling`() {+ MemoryStore.ensureDefaults(Settings())+ val notes = GotchaStorage.memoryNotesDir().apply { mkdirs() }+ val people = GotchaStorage.memoryPeopleDir().apply { mkdirs() }+ File(notes, "plan.md").writeText(record("note", "Personal"))+ File(people, "plan.md").writeText(record("person", "People"))+ File(GotchaStorage.memoryAreasDir(), "hub.md").writeText(+ record("area", "Work").replace("Body.", "See [[plan]].")+ )+ val snap = MemoryStore.loadSnapshot()+ assertTrue(MemoryStore.findDanglingLinks(snap).none { it.target == "plan" })+ }++ @Test+ fun `wiki links ignore fenced code blocks`() {+ assertEquals(+ listOf("notes/real.md"),+ MemoryStore.parseWikiLinks("```\nSee [[notes/fake.md]].\n```\nSee [[notes/real.md]].")+ )+ assertEquals(+ listOf("notes/real.md"),+ MemoryStore.parseWikiLinks("~~~\nSee [[notes/fake.md]].\n~~~\nSee [[notes/real.md]].")+ )+ assertEquals(+ listOf("notes/real.md"),+ MemoryStore.parseWikiLinks("See [[notes/real.md]].\n```\nUnclosed [[notes/fake.md]].")+ )+ }++ @Test+ fun `detail listing includes markdown files`() {+ MemoryStore.ensureDefaults(Settings())+ File(GotchaStorage.memoryAreasDir(), "extra.markdown").writeText(+ record("area", "Work").replace("title: T", "title: Extra")+ )+ val snap = MemoryStore.loadSnapshot()+ assertTrue(snap.areas.map { it.name }.contains("extra.markdown"))+ }++ @Test+ fun `findPossibleDuplicates keeps dots in titles`() {+ MemoryStore.ensureDefaults(Settings())+ val notes = GotchaStorage.memoryNotesDir().apply { mkdirs() }+ File(notes, "release-2-0.md").writeText(record("note", "Work"))+ File(notes, "release-2.md").writeText(record("note", "Work"))+ val snap = MemoryStore.loadSnapshot()+ assertEquals(+ listOf("notes/release-2-0.md"),+ MemoryStore.findPossibleDuplicates("Release 2.0", snap)+ )+ }++ @Test+ fun `slugify normalizes names`() {+ assertEquals("asha-sharma", MemoryStore.slugify("Asha Sharma"))+ assertEquals("k99", MemoryStore.slugify("K99"))+ assertEquals("3d-kinematics", MemoryStore.slugify("3D Kinematics!"))+ assertEquals("", MemoryStore.slugify("---"))+ }++ @Test+ fun `findPossibleDuplicates catches renames`() {+ MemoryStore.ensureDefaults(Settings())+ val people = GotchaStorage.memoryPeopleDir().apply { mkdirs() }+ File(people, "asha-sharma.md").writeText(+ record("person", "People").replace("title: T", "title: Asha Sharma")+ )+ val snap = MemoryStore.loadSnapshot()+ assertTrue(+ MemoryStore.findPossibleDuplicates("Asha Sharma", snap).contains("people/asha-sharma.md")+ )+ assertTrue(+ MemoryStore.findPossibleDuplicates("asha-sharma", snap).contains("people/asha-sharma.md")+ )+ assertTrue(MemoryStore.findPossibleDuplicates("Nobody Here", snap).isEmpty())+ }}diff --git a/app/src/test/java/com/gotcha/scheduled/ScheduledTaskScheduleTest.kt b/app/src/test/java/com/gotcha/scheduled/ScheduledTaskScheduleTest.ktindex e92dce0..1cb1a34 100644--- a/app/src/test/java/com/gotcha/scheduled/ScheduledTaskScheduleTest.kt+++ b/app/src/test/java/com/gotcha/scheduled/ScheduledTaskScheduleTest.kt@@ -1,7 +1,9 @@package com.gotcha.scheduled+import kotlinx.serialization.json.Jsonimport org.junit.Assert.assertEqualsimport org.junit.Assert.assertNull+import org.junit.Assert.assertTrueimport org.junit.Testimport java.time.LocalDateTimeimport java.time.ZoneId@@ -29,6 +31,27 @@ class ScheduledTaskScheduleTest {assertNull(next(once, "2026-10-20T08:00"))}+ @Test+ fun `a memory note link survives a serialization round trip`() {+ val task = ScheduledTask(+ id = "t",+ name = "n",+ prompt = "p",+ startLocal = "2026-10-19T08:00",+ memoryNotePath = "/mem/notes/plan.md"+ )+ val json = Json.encodeToString(ScheduledTask.serializer(), task)+ assertTrue(json.contains("memoryNotePath"))+ assertEquals(task, Json.decodeFromString(ScheduledTask.serializer(), json))+ }++ @Test+ fun `old stored tasks without the link field still decode`() {+ val old = """{"id":"t","name":"n","prompt":"p","startLocal":"2026-10-19T08:00"}"""+ val task = Json { ignoreUnknownKeys = true }.decodeFromString(ScheduledTask.serializer(), old)+ assertNull(task.memoryNotePath)+ }+@Testfun `a daily task comes round at the same local time`() {val daily = task("2026-10-19T08:00", Repeat(RepeatKind.DAILY))diff --git a/app/src/test/java/com/gotcha/tools/ScheduledTaskToolTest.kt b/app/src/test/java/com/gotcha/tools/ScheduledTaskToolTest.ktindex df5c284..910e459 100644--- a/app/src/test/java/com/gotcha/tools/ScheduledTaskToolTest.kt+++ b/app/src/test/java/com/gotcha/tools/ScheduledTaskToolTest.kt@@ -3,6 +3,9 @@ package com.gotcha.toolsimport android.content.Contextimport androidx.test.core.app.ApplicationProviderimport com.gotcha.agent.ComposerAttachment+import com.gotcha.data.GotchaStorage+import com.gotcha.data.MemoryStore+import com.gotcha.data.Settingsimport com.gotcha.scheduled.RepeatKindimport com.gotcha.scheduled.ScheduledTaskimport com.gotcha.scheduled.ScheduledTaskStore@@ -155,6 +158,219 @@ class ScheduledTaskToolTest {assertEquals(AgentMode.OPERATOR, store.all().single().mode)}+ // ---- memory note links (Second Brain Phase 2) ----++ private fun withMemoryNote(name: String = "plan.md", block: (note: File) -> Unit) {+ val savedRoot = GotchaStorage.rootPath+ GotchaStorage.rootPath = File(context.filesDir, "sched-mem-test/Gotcha").absolutePath+ try {+ MemoryStore.ensureDefaults(Settings())+ val note = File(GotchaStorage.memoryNotesDir(), name)+ note.writeText(+ listOf(+ "---",+ "title: Plan",+ "area: Personal",+ "type: note",+ "updated: 2026-10-29",+ "---",+ "",+ "Body.",+ ""+ ).joinToString("\n")+ )+ block(note)+ } finally {+ GotchaStorage.rootPath = savedRoot+ File(context.filesDir, "sched-mem-test").deleteRecursively()+ }+ }++ @Test+ fun `a create with a memory note saves the link`() {+ withMemoryNote { note ->+ val result = tool.prepareCreate(+ args(+ """{"name":"Plan","prompt":"Work the plan","start":"2026-10-19T08:00",""" ++ """"memory_note":"${note.absolutePath}"}"""+ )+ )++ val req = request(result)+ assertEquals(note.canonicalPath, req.memoryNote)+ val applied = tool.apply(req, sessionId = "chat", chatMode = AgentMode.OPERATOR)+ assertTrue(applied.message, applied.success)+ assertEquals(note.canonicalPath, store.all().single().memoryNotePath)+ }+ }++ @Test+ fun `a create rejects a memory note outside memory`() {+ val outside = File(context.filesDir, "outside.md").apply { writeText("# Outside\n") }+ try {+ val result = tool.prepareCreate(+ args(+ """{"name":"Plan","prompt":"Work the plan","start":"2026-10-19T08:00",""" ++ """"memory_note":"${outside.absolutePath}"}"""+ )+ )+ assertFalse(result.message, result.success)+ assertTrue(result.message, result.message.contains("not a memory"))+ } finally {+ outside.delete()+ }+ }++ @Test+ fun `an edit can link a note and the listing names it`() {+ withMemoryNote { note ->+ val created = request(+ tool.prepareCreate(args("""{"name":"Plan","prompt":"Work it","start":"2026-10-19T08:00"}"""))+ )+ tool.apply(created, sessionId = "chat", chatMode = AgentMode.OPERATOR)+ val task = store.all().single()+ assertNull(task.memoryNotePath)++ val edited = request(+ tool.prepareEdit(+ args("""{"task_id":"${task.id}","memory_note":"${note.absolutePath}"}""")+ )+ )+ assertEquals(note.canonicalPath, edited.memoryNote)+ tool.apply(edited, sessionId = "chat", chatMode = AgentMode.OPERATOR)+ assertEquals(note.canonicalPath, store.all().single().memoryNotePath)+ assertTrue(tool.list().message, tool.list().message.contains("memory note"))+ }+ }++ @Test+ fun `an edit with a blank memory note clears the link`() {+ withMemoryNote { note ->+ val created = request(+ tool.prepareCreate(+ args(+ """{"name":"Plan","prompt":"Work it","start":"2026-10-19T08:00",""" ++ """"memory_note":"${note.absolutePath}"}"""+ )+ )+ )+ tool.apply(created, sessionId = "chat", chatMode = AgentMode.OPERATOR)+ val task = store.all().single()+ assertEquals(note.canonicalPath, task.memoryNotePath)++ val cleared = request(+ tool.prepareEdit(args("""{"task_id":"${task.id}","memory_note":""}"""))+ )+ assertTrue(cleared.clearMemoryNote)+ tool.apply(cleared, sessionId = "chat", chatMode = AgentMode.OPERATOR)+ assertNull(store.all().single().memoryNotePath)+ }+ }++ @Test+ fun `the approval names a removed memory note`() = runTest {+ store.put(+ ScheduledTask(+ id = "t1",+ name = "Plan",+ prompt = "p",+ startLocal = "2026-10-19T08:00",+ memoryNotePath = "/mem/notes/plan.md"+ )+ )+ val words = tool.describe(+ ScheduleRequest(taskId = "t1", clearMemoryNote = true),+ sessionId = "chat",+ chatMode = AgentMode.OPERATOR+ )+ assertTrue(words, words.contains("(removed)"))+ }++ @Test+ fun `an edit with an explicit null memory note keeps the link`() {+ withMemoryNote { note ->+ val created = request(+ tool.prepareCreate(+ args(+ """{"name":"Plan","prompt":"Work it","start":"2026-10-19T08:00",""" ++ """"memory_note":"${note.absolutePath}"}"""+ )+ )+ )+ tool.apply(created, sessionId = "chat", chatMode = AgentMode.OPERATOR)+ val task = store.all().single()++ val kept = request(+ tool.prepareEdit(+ args("""{"task_id":"${task.id}","name":"Renamed","memory_note":null}""")+ )+ )+ assertNull(kept.memoryNote)+ assertFalse(kept.clearMemoryNote)+ tool.apply(kept, sessionId = "chat", chatMode = AgentMode.OPERATOR)+ val saved = store.all().single()+ assertEquals("Renamed", saved.name)+ assertEquals(note.canonicalPath, saved.memoryNotePath)+ }+ }++ @Test+ fun `a create with a blank memory note shows no link line`() = runTest {+ var created: ScheduleRequest? = null+ withMemoryNote {+ created = request(+ tool.prepareCreate(+ args("""{"name":"Plan","prompt":"Work it","start":"2026-10-19T08:00","memory_note":""}""")+ )+ )+ assertTrue(created!!.clearMemoryNote)+ }+ val words = tool.describe(created!!, sessionId = "chat", chatMode = AgentMode.OPERATOR)+ assertFalse(words, words.contains("Memory note"))+ }++ @Test+ fun `an edit can point a task at a different note`() {+ withMemoryNote { first ->+ val people = GotchaStorage.memoryPeopleDir().apply { mkdirs() }+ val second = File(people, "plan.md")+ second.writeText(+ listOf(+ "---",+ "title: Person Plan",+ "area: People",+ "type: person",+ "updated: 2026-10-29",+ "---",+ "",+ "Body.",+ ""+ ).joinToString("\n")+ )+ val created = request(+ tool.prepareCreate(+ args(+ """{"name":"Plan","prompt":"Work it","start":"2026-10-19T08:00",""" ++ """"memory_note":"${first.absolutePath}"}"""+ )+ )+ )+ tool.apply(created, sessionId = "chat", chatMode = AgentMode.OPERATOR)+ val task = store.all().single()++ val moved = request(+ tool.prepareEdit(+ args("""{"task_id":"${task.id}","memory_note":"${second.absolutePath}"}""")+ )+ )+ tool.apply(moved, sessionId = "chat", chatMode = AgentMode.OPERATOR)+ // Same-named files stay apart in the listing.+ val listing = tool.list().message+ assertTrue(listing, listing.contains("people/plan.md"))+ assertFalse(listing, listing.contains("notes/plan.md"))+ }+ }+@Testfun `files are checked when asked and read when approved`() {val notes = File(context.filesDir, "notes.txt").apply { writeText("Buy milk") }