Skip to content

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

Second Brain Phase 3: briefing preset, viewer search (#156)

Rishabh Bajpai4a6aebcf2a02
diff --git a/app/src/main/assets/skills/memory.json b/app/src/main/assets/skills/memory.json
index 992f535..f416a14 100644
--- a/app/src/main/assets/skills/memory.json
+++ b/app/src/main/assets/skills/memory.json
@@ -21,5 +21,5 @@
"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, 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."
+ "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. A ready-made Morning briefing preset (MONITOR, daily, read-only, writes the structured day plan as its chat response) ships paused in Settings / Scheduled tasks: the user enables it.\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/GotchaApp.kt b/app/src/main/java/com/gotcha/GotchaApp.kt
index 2a085ac..5c88e87 100644
--- a/app/src/main/java/com/gotcha/GotchaApp.kt
+++ b/app/src/main/java/com/gotcha/GotchaApp.kt
@@ -70,6 +70,15 @@ class GotchaApp : Application() {
val settings = com.gotcha.data.SettingsRepository(this).load()
com.gotcha.data.MemoryStore.ensureDefaults(settings)
}
+ // Morning briefing preset (Second Brain Phase 3): seeded paused so
+ // the user opts in. Best-effort, like the memory init above.
+ runCatching {
+ com.gotcha.scheduled.ScheduledTaskStore(this).seedBriefingPreset(
+ com.gotcha.data.GotchaStorage.memoryRoot().absolutePath,
+ System.currentTimeMillis(),
+ java.time.ZoneId.systemDefault()
+ )
+ }
}.start()
setupUncaughtExceptionHandler()
}
diff --git a/app/src/main/java/com/gotcha/data/MemoryStore.kt b/app/src/main/java/com/gotcha/data/MemoryStore.kt
index 6b85957..d213165 100644
--- a/app/src/main/java/com/gotcha/data/MemoryStore.kt
+++ b/app/src/main/java/com/gotcha/data/MemoryStore.kt
@@ -167,6 +167,12 @@ object MemoryStore {
) {
/** Every markdown node shown on the graph, keyed by file name. */
fun allMarkdown(): List<BrainFile> = listOfNotNull(soul, memoryIndex, userCard) + areas + people + notes
+
+ /** True when no file is shown: viewer search with no matches. */
+ fun isEmpty(): Boolean {
+ if (soul != null || memoryIndex != null || userCard != null) return false
+ return areas.isEmpty() && people.isEmpty() && notes.isEmpty() && raw.isEmpty()
+ }
}
/** Max chars shown per file in the viewer. */
@@ -487,6 +493,32 @@ object MemoryStore {
return file.content
}
+ /** Viewer search (Phase 3): snapshot copy holding only files matching [query] in name or content. */
+ fun filterSnapshot(snapshot: SecondBrainSnapshot, query: String): SecondBrainSnapshot {
+ val q = query.trim().lowercase()
+ if (q.isEmpty()) return snapshot
+ fun match(file: BrainFile): Boolean {
+ if (file.name.lowercase().contains(q)) return true
+ if (file.content.lowercase().contains(q)) return true
+ // Truncated previews stop at the viewer cap: search the full file
+ // before reporting no match. Bounded like every other vault read.
+ if (!file.truncated) return false
+ val abs = file.absolutePath
+ if (abs.isBlank()) return false
+ return readUpTo(File(abs), LINK_SCAN_CAP_CHARS)?.lowercase()?.contains(q) ?: false
+ }
+ fun matchOpt(file: BrainFile?): BrainFile? = if (file != null && match(file)) file else null
+ return snapshot.copy(
+ soul = matchOpt(snapshot.soul),
+ memoryIndex = matchOpt(snapshot.memoryIndex),
+ userCard = matchOpt(snapshot.userCard),
+ areas = snapshot.areas.filter(::match),
+ people = snapshot.people.filter(::match),
+ notes = snapshot.notes.filter(::match),
+ raw = snapshot.raw.filter(::match)
+ )
+ }
+
/**
* Duplicate guard: slug of a title or file name, so "Asha Sharma",
* "asha-sharma.md" and "Asha-Sharma" all compare equal. The agent checks
diff --git a/app/src/main/java/com/gotcha/scheduled/MorningBriefing.kt b/app/src/main/java/com/gotcha/scheduled/MorningBriefing.kt
new file mode 100644
index 0000000..b536fc0
--- /dev/null
+++ b/app/src/main/java/com/gotcha/scheduled/MorningBriefing.kt
@@ -0,0 +1,86 @@
+package com.gotcha.scheduled
+
+import com.gotcha.tools.AgentMode
+import java.time.LocalDateTime
+
+/**
+ * The Morning briefing template (Second Brain Phase 3): a read-only daily
+ * task that writes the structured day plan (timetable, dues, calendar check)
+ * as its chat response.
+ *
+ * It ships as a preset in Settings ▸ Scheduled tasks: present but paused, so
+ * the user opts in with the normal toggle. The same prefilled form is offered
+ * to re-add it after a delete. It runs in MONITOR with a prompt that forbids
+ * writes, so the briefing can never change anything even if the prompt were
+ * ignored.
+ */
+object MorningBriefing {
+
+ const val TEMPLATE_NAME = "Morning briefing"
+
+ /** Next 7:00 local time strictly after [now]. */
+ fun nextSevenAm(now: LocalDateTime): LocalDateTime {
+ val seven = now.toLocalDate().atTime(7, 0)
+ return if (seven.isAfter(now)) seven else seven.plusDays(1)
+ }
+
+ /** Self-contained read-only briefing prompt naming the vault's absolute paths. */
+ fun promptFor(memoryRoot: String): String = buildString {
+ appendLine("Morning briefing. Read-only: do not create, modify or delete any file,")
+ appendLine("task, calendar event, alarm or setting. Create nothing in this run;")
+ appendLine("the user approves any follow-up in chat.")
+ appendLine()
+ appendLine("Sources, in order:")
+ appendLine("1. SOUL.md and MEMORY.md are in your [memory_startup] message. Follow them.")
+ appendLine("2. Load what the day needs with read_file using ABSOLUTE paths:")
+ appendLine("$memoryRoot/MEMORY.md, $memoryRoot/user.md, plus their linked notes")
+ appendLine("for anything due or ongoing today.")
+ appendLine("3. Check dues with list_scheduled_tasks. Compare dues in the next 7 days")
+ appendLine("against existing reminder tasks and only surface what is missing;")
+ appendLine("never surface a reminder that already exists.")
+ appendLine("4. Calendar pass: query today's events on every available calendar with")
+ appendLine("list_calendar_events (live, device timezone). Anchor fixed commitments")
+ appendLine("first, checking for collisions.")
+ appendLine()
+ appendLine("Then output the day plan EXACTLY in this shape. Day blocks are real")
+ appendLine("markdown tables (header row + separator row, one row per item,")
+ appendLine("chronological, fixed commitments first). No bullet lists for scheduled items.")
+ appendLine()
+ appendLine("Good [morning/afternoon/evening, depending on the current time] - [one-line theme].")
+ appendLine()
+ appendLine("**Morning:**")
+ appendLine("| Time | Item | Est. | Done when |")
+ appendLine("|------|------|------|-----------|")
+ appendLine("| [time] | [item] | [~estimate] | [concrete end-state] |")
+ appendLine()
+ appendLine("**Afternoon:** (same table shape)")
+ appendLine("**Evening:** (same table shape)")
+ appendLine()
+ appendLine("**Not today:** [parked items, comma-separated, one line]")
+ appendLine()
+ appendLine("**Watch out:**")
+ appendLine("- [what to drop or shorten if the day overflows; omit this section if it fits]")
+ appendLine("- [dues in the next 7 days, one line]")
+ appendLine()
+ appendLine("**Calendar check:** [one line - collisions found, or clear on every calendar]")
+ appendLine()
+ appendLine("**Proposed reminders (do not create):**")
+ appendLine("[one line per reminder: what + when; omit section if none missing]")
+ appendLine()
+ appendLine("Hard rules: every table row carries an estimate (~15m style) and estimates")
+ appendLine("sum to a sane day; plain words, never field names or status labels; only facts")
+ appendLine("from memory, dues and live calendars, never invent details; max ~350 words.")
+ appendLine("Your final message IS the plan.")
+ }
+
+ /** Prefilled task the form offers; the user saving it is the approval. */
+ fun template(memoryRoot: String, now: LocalDateTime = LocalDateTime.now()): ScheduledTask =
+ ScheduledTask(
+ id = "",
+ name = TEMPLATE_NAME,
+ prompt = promptFor(memoryRoot),
+ startLocal = nextSevenAm(now).withSecond(0).withNano(0).toString(),
+ repeat = Repeat(kind = RepeatKind.DAILY),
+ agentMode = AgentMode.MONITOR.name
+ )
+}
diff --git a/app/src/main/java/com/gotcha/scheduled/ScheduledTaskStore.kt b/app/src/main/java/com/gotcha/scheduled/ScheduledTaskStore.kt
index 61cc52b..a0d127b 100644
--- a/app/src/main/java/com/gotcha/scheduled/ScheduledTaskStore.kt
+++ b/app/src/main/java/com/gotcha/scheduled/ScheduledTaskStore.kt
@@ -7,6 +7,10 @@ import com.gotcha.data.SafeEncryptedSharedPreferences
import kotlinx.serialization.builtins.ListSerializer
import kotlinx.serialization.json.Json
import java.io.File
+import java.time.Instant
+import java.time.LocalDateTime
+import java.time.ZoneId
+import java.util.UUID
/**
* The scheduled tasks (issue #132). The tasks are kept in encrypted prefs, like
@@ -57,6 +61,44 @@ class ScheduledTaskStore internal constructor(
write(if (tasks.any { it.id == task.id }) tasks.map { if (it.id == task.id) task else it } else tasks + task)
}
+ /**
+ * Seeds the Morning briefing preset once (Second Brain Phase 3): present
+ * in the catalog but paused, so the user opts in with the normal toggle.
+ * Never duplicates: an existing briefing (seeded, renamed, re-added, or
+ * user-made) is adopted by id tracking and only the marker is healed.
+ * A deleted preset is never re-added unasked. The flag is written after
+ * the task, so a failed seed retries next time. Returns the preset when
+ * newly created, null otherwise.
+ */
+ fun seedBriefingPreset(memoryRoot: String, now: Long, zone: ZoneId): ScheduledTask? = synchronized(LOCK) {
+ val seededId = prefs.getString(KEY_BRIEFING_TASK_ID, null)
+ read().firstOrNull { it.id == seededId || it.name == MorningBriefing.TEMPLATE_NAME }?.let { existing ->
+ markBriefingSeeded(existing.id)
+ return null
+ }
+ if (prefs.getBoolean(KEY_BRIEFING_SEEDED, false)) return null
+ val preset = MorningBriefing.template(
+ memoryRoot,
+ LocalDateTime.ofInstant(Instant.ofEpochMilli(now), zone)
+ ).copy(id = UUID.randomUUID().toString(), enabled = false, createdAt = now)
+ put(preset)
+ markBriefingSeeded(preset.id)
+ preset
+ }
+
+ /** True when a briefing preset exists right now (even renamed): hides the re-add button. */
+ fun hasBriefingPreset(): Boolean = synchronized(LOCK) {
+ val seededId = prefs.getString(KEY_BRIEFING_TASK_ID, null)
+ read().any { it.id == seededId || it.name == MorningBriefing.TEMPLATE_NAME }
+ }
+
+ private fun markBriefingSeeded(taskId: String?) {
+ prefs.edit()
+ .putBoolean(KEY_BRIEFING_SEEDED, true)
+ .apply { if (taskId != null) putString(KEY_BRIEFING_TASK_ID, taskId) }
+ .apply()
+ }
+
fun delete(id: String) {
update(id) { null }
}
@@ -109,6 +151,8 @@ class ScheduledTaskStore internal constructor(
private companion object {
const val PREFS_FILE = "gotcha_scheduled_tasks"
const val KEY_TASKS = "tasks"
+ const val KEY_BRIEFING_SEEDED = "briefing_preset_seeded"
+ const val KEY_BRIEFING_TASK_ID = "briefing_preset_task_id"
const val ATTACHMENTS_DIR = "scheduled_tasks"
val LOCK = Any()
}
diff --git a/app/src/main/java/com/gotcha/ui/ScheduledTasksScreen.kt b/app/src/main/java/com/gotcha/ui/ScheduledTasksScreen.kt
index f3fb4c4..afcd510 100644
--- a/app/src/main/java/com/gotcha/ui/ScheduledTasksScreen.kt
+++ b/app/src/main/java/com/gotcha/ui/ScheduledTasksScreen.kt
@@ -58,7 +58,9 @@ import com.gotcha.agent.AttachmentFiles
import com.gotcha.agent.ChatTitle
import com.gotcha.agent.ComposerAttachment
import com.gotcha.data.ChatHistoryRepository
+import com.gotcha.data.GotchaStorage
import com.gotcha.i18n.stringLookup
+import com.gotcha.scheduled.MorningBriefing
import com.gotcha.scheduled.Repeat
import com.gotcha.scheduled.RepeatKind
import com.gotcha.scheduled.ScheduledStart
@@ -90,6 +92,7 @@ import java.util.UUID
/** [editing] value for the add form, as opposed to a task id. */
private const val NEW_TASK = "+new"
+private const val BRIEFING_TASK = "+briefing"
/**
* Settings ▸ Scheduled tasks (issue #132): prompts Gotcha sends itself at set
@@ -108,7 +111,17 @@ fun ScheduledTasksScreen(onBack: () -> Unit, onOpenChat: (String) -> Unit) {
var tick by remember { mutableStateOf(0) }
var editing by remember { mutableStateOf<String?>(null) }
var deleting by remember { mutableStateOf<ScheduledTask?>(null) }
- val tasks = remember(tick) { store.all() }
+ // Seed where shown, not only at app start: the list below then never
+ // renders stale, and the re-add button cannot race a background seed.
+ val tasks = remember(tick) {
+ store.seedBriefingPreset(
+ GotchaStorage.memoryRoot().absolutePath,
+ System.currentTimeMillis(),
+ ZoneId.systemDefault()
+ )
+ store.all()
+ }
+ val hasBriefing = remember(tasks) { store.hasBriefingPreset() }
val canRunUnattended = remember(tick) { ScheduledTaskScheduler.canRunUnattended(context) }
// A run ending records its result just before the keep-alive service stops,
@@ -141,7 +154,7 @@ fun ScheduledTasksScreen(onBack: () -> Unit, onOpenChat: (String) -> Unit) {
SettingsScaffold(title = stringResource(SettingsPage.SCHEDULED_TASKS.title), onBack = onBack, overlay = overlay) {
Text(stringResource(R.string.scheduled_intro), style = MaterialTheme.typography.bodyMedium)
if (!canRunUnattended) ExactAlarmHint(context)
- if (tasks.isEmpty() && editing != NEW_TASK) {
+ if (tasks.isEmpty() && editing != NEW_TASK && editing != BRIEFING_TASK) {
Text(
stringResource(R.string.scheduled_empty),
style = MaterialTheme.typography.bodySmall,
@@ -186,10 +199,17 @@ fun ScheduledTasksScreen(onBack: () -> Unit, onOpenChat: (String) -> Unit) {
}
}
HorizontalDivider()
- if (editing == NEW_TASK) {
+ if (editing == NEW_TASK || editing == BRIEFING_TASK) {
TaskEditor(
store = store,
initial = null,
+ template = if (editing == BRIEFING_TASK) {
+ remember {
+ MorningBriefing.template(GotchaStorage.memoryRoot().absolutePath)
+ }
+ } else {
+ null
+ },
onSaved = {
editing = null
tick++
@@ -201,6 +221,13 @@ fun ScheduledTasksScreen(onBack: () -> Unit, onOpenChat: (String) -> Unit) {
onClick = { editing = NEW_TASK },
modifier = Modifier.fillMaxWidth().testTag("scheduled_add_task")
) { Text(stringResource(R.string.scheduled_add_task)) }
+ // Re-add path for a deleted preset; hidden while one exists.
+ if (!hasBriefing) {
+ OutlinedButton(
+ onClick = { editing = BRIEFING_TASK },
+ modifier = Modifier.fillMaxWidth().testTag("scheduled_add_briefing")
+ ) { Text(stringResource(R.string.scheduled_add_briefing)) }
+ }
}
}
@@ -350,7 +377,7 @@ private fun HistoryRow(run: TaskRun, onOpenChat: (String) -> Unit) {
}
}
-/** The add/edit form. [initial] null adds a task. */
+/** The add/edit form. [initial] null adds a task; [template] prefills a new task (e.g. the briefing). */
@OptIn(ExperimentalLayoutApi::class)
@Composable
@Suppress("LongMethod", "CyclomaticComplexMethod")
@@ -358,19 +385,24 @@ private fun TaskEditor(
store: ScheduledTaskStore,
initial: ScheduledTask?,
onSaved: () -> Unit,
- onCancel: () -> Unit
+ onCancel: () -> Unit,
+ template: ScheduledTask? = null
) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
- val start = remember { initial?.start ?: defaultStart() }
- var name by remember { mutableStateOf(initial?.name.orEmpty()) }
- var prompt by remember { mutableStateOf(initial?.prompt.orEmpty()) }
+ val start = remember { initial?.start ?: template?.start ?: defaultStart() }
+ var name by remember { mutableStateOf(initial?.name ?: template?.name.orEmpty()) }
+ var prompt by remember { mutableStateOf(initial?.prompt ?: template?.prompt.orEmpty()) }
var date by remember { mutableStateOf(start.toLocalDate()) }
var time by remember { mutableStateOf(start.toLocalTime()) }
- var kind by remember { mutableStateOf(initial?.repeat?.kind ?: RepeatKind.NONE) }
- var interval by remember { mutableStateOf((initial?.repeat?.interval ?: 1).toString()) }
- var weekdays by remember { mutableStateOf(initial?.repeat?.weekdays?.toSet() ?: emptySet()) }
- var mode by remember { mutableStateOf(initial?.mode ?: AgentMode.MONITOR) }
+ var kind by remember { mutableStateOf(initial?.repeat?.kind ?: template?.repeat?.kind ?: RepeatKind.NONE) }
+ var interval by remember {
+ mutableStateOf((initial?.repeat?.interval ?: template?.repeat?.interval ?: 1).toString())
+ }
+ var weekdays by remember {
+ mutableStateOf(initial?.repeat?.weekdays?.toSet() ?: template?.repeat?.weekdays?.toSet() ?: emptySet())
+ }
+ var mode by remember { mutableStateOf(initial?.mode ?: template?.mode ?: AgentMode.MONITOR) }
var personaId by remember { mutableStateOf(initial?.personaId) }
var sameChat by remember { mutableStateOf(initial?.sameChat ?: false) }
var chatSessionId by remember { mutableStateOf(initial?.chatSessionId) }
diff --git a/app/src/main/java/com/gotcha/ui/SecondBrainScreen.kt b/app/src/main/java/com/gotcha/ui/SecondBrainScreen.kt
index a228ad4..f1d0d22 100644
--- a/app/src/main/java/com/gotcha/ui/SecondBrainScreen.kt
+++ b/app/src/main/java/com/gotcha/ui/SecondBrainScreen.kt
@@ -20,6 +20,7 @@ import androidx.compose.material3.Button
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
+import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
@@ -151,21 +152,41 @@ fun SecondBrainScreen(onBack: () -> Unit) {
if (showGraph) {
SecondBrainGraphView(snapshot = current)
} else {
- current.soul?.let {
+ var search by remember(current) { mutableStateOf("") }
+ OutlinedTextField(
+ value = search,
+ onValueChange = { search = it },
+ label = { Text(stringResource(R.string.second_brain_search)) },
+ singleLine = true,
+ modifier = Modifier
+ .fillMaxWidth()
+ .testTag("settings_second_brain_search")
+ )
+ val shown = remember(current, search) { MemoryStore.filterSnapshot(current, search) }
+ val shownEmpty = remember(shown) { shown.isEmpty() }
+ if (search.isNotBlank() && shownEmpty) {
+ Text(
+ text = stringResource(R.string.second_brain_no_matches, search.trim()),
+ style = MaterialTheme.typography.bodyMedium,
+ modifier = Modifier.testTag("settings_second_brain_no_matches")
+ )
+ return@SettingsScaffold
+ }
+ shown.soul?.let {
BrainSection(
heading = stringResource(R.string.second_brain_identity),
file = it,
tag = "identity"
)
}
- current.memoryIndex?.let {
+ shown.memoryIndex?.let {
BrainSection(
heading = stringResource(R.string.second_brain_map),
file = it,
tag = "map"
)
}
- current.userCard?.let {
+ shown.userCard?.let {
BrainSection(
heading = stringResource(R.string.second_brain_user_card),
file = it,
@@ -174,25 +195,27 @@ fun SecondBrainScreen(onBack: () -> Unit) {
}
BrainFileList(
heading = stringResource(R.string.second_brain_areas),
- files = current.areas,
+ files = shown.areas,
tag = "areas"
)
BrainFileList(
heading = stringResource(R.string.second_brain_people),
- files = current.people,
+ files = shown.people,
tag = "people"
)
BrainFileList(
heading = stringResource(R.string.second_brain_notes),
- files = current.notes,
+ files = shown.notes,
tag = "notes"
)
BrainFileList(
heading = stringResource(R.string.second_brain_raw),
- files = current.raw,
+ files = shown.raw,
tag = "raw"
)
- health?.let { BrainHealthSection(health = it) }
+ // Health is vault-level, not query-level: hide it while searching
+ // so its unrelated filenames never confuse a filtered view.
+ if (search.isBlank()) health?.let { BrainHealthSection(health = it) }
}
}
}
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 8c35599..58dd302 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -92,6 +92,8 @@
<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_search">Search memory</string>
+ <string name="second_brain_no_matches">No matches for “%1$s”.</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>
@@ -1746,6 +1748,7 @@
<string name="scheduled_intro">Gotcha sends itself a prompt at the time you set and works on it like any chat. The result lands in a chat, with a notification when you\'re away.</string>
<string name="scheduled_empty">No scheduled tasks yet. Add one here, or ask Gotcha in a chat, e.g. “every weekday at 8, summarise my unread mail”.</string>
<string name="scheduled_add_task">Add a task</string>
+ <string name="scheduled_add_briefing">Morning briefing</string>
<string name="scheduled_exact_alarm_hint">Gotcha may not set exact alarms, so a task can\'t start on its own: it will ask you to tap a notification instead.</string>
<string name="scheduled_exact_alarm_allow">Allow alarms and reminders</string>
<string name="scheduled_set_up_by_gotcha">Set up by Gotcha in a chat</string>
diff --git a/app/src/test/java/com/gotcha/data/MemoryStoreTest.kt b/app/src/test/java/com/gotcha/data/MemoryStoreTest.kt
index 6e79aea..1af439f 100644
--- a/app/src/test/java/com/gotcha/data/MemoryStoreTest.kt
+++ b/app/src/test/java/com/gotcha/data/MemoryStoreTest.kt
@@ -776,4 +776,49 @@ class MemoryStoreTest {
)
assertTrue(MemoryStore.findPossibleDuplicates("Nobody Here", snap).isEmpty())
}
+
+ // ---- Phase 3: viewer search ----
+
+ @Test
+ fun `filterSnapshot with a blank query returns everything`() {
+ MemoryStore.ensureDefaults(Settings())
+ val snap = MemoryStore.loadSnapshot()
+ val filtered = MemoryStore.filterSnapshot(snap, " ")
+ assertEquals(snap.areas.size, filtered.areas.size)
+ assertEquals(snap.notes.size, filtered.notes.size)
+ assertNotNull(filtered.soul)
+ }
+
+ @Test
+ fun `filterSnapshot matches names and contents`() {
+ MemoryStore.ensureDefaults(Settings())
+ val notes = GotchaStorage.memoryNotesDir().apply { mkdirs() }
+ File(notes, "trip.md").writeText(record("note", "Personal").replace("Body.", "Kyoto itinerary."))
+ File(notes, "other.md").writeText(record("note", "Personal").replace("Body.", "Unrelated."))
+ val rawDir = GotchaStorage.memoryRawDir().apply { mkdirs() }
+ File(rawDir, "receipt.txt").writeText("Kyoto taxi")
+ val snap = MemoryStore.loadSnapshot()
+ val byName = MemoryStore.filterSnapshot(snap, "trip")
+ assertEquals(listOf("trip.md"), byName.notes.map { it.name })
+ val byContent = MemoryStore.filterSnapshot(snap, "kyoto")
+ assertEquals(listOf("trip.md"), byContent.notes.map { it.name })
+ assertEquals(listOf("receipt.txt"), byContent.raw.map { it.name })
+ val none = MemoryStore.filterSnapshot(snap, "zzzz-no-match")
+ assertTrue(none.notes.isEmpty())
+ assertNull(none.soul)
+ }
+
+ @Test
+ fun `filterSnapshot searches past the preview cap`() {
+ MemoryStore.ensureDefaults(Settings())
+ val notes = GotchaStorage.memoryNotesDir().apply { mkdirs() }
+ val filler = "x".repeat(MemoryStore.VIEWER_FILE_CAP_CHARS)
+ File(notes, "long.md").writeText(
+ record("note", "Personal").replace("Body.", "$filler needle-term")
+ )
+ val snap = MemoryStore.loadSnapshot()
+ assertTrue(snap.notes.single { it.name == "long.md" }.truncated)
+ val found = MemoryStore.filterSnapshot(snap, "needle-term")
+ assertEquals(listOf("long.md"), found.notes.map { it.name })
+ }
}
diff --git a/app/src/test/java/com/gotcha/scheduled/MorningBriefingTest.kt b/app/src/test/java/com/gotcha/scheduled/MorningBriefingTest.kt
new file mode 100644
index 0000000..2f3b8de
--- /dev/null
+++ b/app/src/test/java/com/gotcha/scheduled/MorningBriefingTest.kt
@@ -0,0 +1,60 @@
+package com.gotcha.scheduled
+
+import com.gotcha.tools.AgentMode
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import java.time.LocalDateTime
+
+/** [MorningBriefing]: the read-only daily briefing template (Second Brain Phase 3). */
+class MorningBriefingTest {
+
+ @Test
+ fun `next seven am stays today before seven`() {
+ assertEquals(
+ LocalDateTime.parse("2026-10-29T07:00"),
+ MorningBriefing.nextSevenAm(LocalDateTime.parse("2026-10-29T06:59"))
+ )
+ }
+
+ @Test
+ fun `next seven am rolls to tomorrow after seven`() {
+ assertEquals(
+ LocalDateTime.parse("2026-10-30T07:00"),
+ MorningBriefing.nextSevenAm(LocalDateTime.parse("2026-10-29T07:00"))
+ )
+ assertEquals(
+ LocalDateTime.parse("2026-10-30T07:00"),
+ MorningBriefing.nextSevenAm(LocalDateTime.parse("2026-10-29T22:15"))
+ )
+ }
+
+ @Test
+ fun `the prompt is self-contained and read-only`() {
+ val prompt = MorningBriefing.promptFor("/vault/Gotcha/memory")
+ assertTrue(prompt.contains("/vault/Gotcha/memory/MEMORY.md"))
+ assertTrue(prompt.contains("/vault/Gotcha/memory/user.md"))
+ assertTrue(prompt.contains("ABSOLUTE"))
+ assertTrue(prompt.contains("Read-only"))
+ assertTrue(prompt.contains("list_scheduled_tasks"))
+ assertTrue(prompt.contains("list_calendar_events"))
+ assertTrue(prompt.contains("| Time | Item | Est. | Done when |"))
+ assertTrue(prompt.contains("**Not today:**"))
+ assertTrue(prompt.contains("**Calendar check:**"))
+ assertTrue(prompt.contains("Your final message IS the plan."))
+ assertTrue(!prompt.contains("speak"))
+ }
+
+ @Test
+ fun `the template runs monitor daily at seven`() {
+ val task = MorningBriefing.template(
+ "/vault/Gotcha/memory",
+ LocalDateTime.parse("2026-10-29T22:15")
+ )
+ assertEquals(MorningBriefing.TEMPLATE_NAME, task.name)
+ assertEquals(AgentMode.MONITOR, task.mode)
+ assertEquals(RepeatKind.DAILY, task.repeat.kind)
+ assertEquals("2026-10-30T07:00", task.startLocal)
+ assertTrue(task.enabled)
+ }
+}
diff --git a/app/src/test/java/com/gotcha/scheduled/ScheduledTaskStoreTest.kt b/app/src/test/java/com/gotcha/scheduled/ScheduledTaskStoreTest.kt
index 723d079..d0110e0 100644
--- a/app/src/test/java/com/gotcha/scheduled/ScheduledTaskStoreTest.kt
+++ b/app/src/test/java/com/gotcha/scheduled/ScheduledTaskStoreTest.kt
@@ -87,4 +87,59 @@ class ScheduledTaskStoreTest {
assertNull(store.get("1")!!.chatSessionId)
assertEquals("chat-b", store.get("2")!!.chatSessionId)
}
+
+ @Test
+ fun `the briefing preset seeds once, paused`() {
+ val zone = java.time.ZoneId.of("UTC")
+ val now = java.time.LocalDateTime.parse("2026-10-29T22:15").atZone(zone).toInstant().toEpochMilli()
+
+ val seeded = store.seedBriefingPreset("/mem", now, zone)
+
+ assertTrue(seeded != null)
+ assertEquals(MorningBriefing.TEMPLATE_NAME, seeded!!.name)
+ assertEquals(false, seeded.enabled)
+ assertEquals(com.gotcha.tools.AgentMode.MONITOR, seeded.mode)
+ assertEquals("2026-10-30T07:00", seeded.startLocal)
+ assertNull(store.seedBriefingPreset("/mem", now, zone))
+ assertEquals(1, store.all().count { it.name == MorningBriefing.TEMPLATE_NAME })
+ }
+
+ @Test
+ fun `the briefing preset skips a user-added briefing`() {
+ val zone = java.time.ZoneId.of("UTC")
+ val now = java.time.LocalDateTime.parse("2026-10-29T22:15").atZone(zone).toInstant().toEpochMilli()
+ store.put(task("u").copy(name = MorningBriefing.TEMPLATE_NAME))
+
+ assertNull(store.seedBriefingPreset("/mem", now, zone))
+ assertEquals(1, store.all().size)
+ assertTrue(store.hasBriefingPreset())
+ }
+
+ @Test
+ fun `a user-added briefing is adopted and tracked across renames`() {
+ val zone = java.time.ZoneId.of("UTC")
+ val now = java.time.LocalDateTime.parse("2026-10-29T22:15").atZone(zone).toInstant().toEpochMilli()
+ store.put(task("u").copy(name = MorningBriefing.TEMPLATE_NAME))
+
+ assertNull(store.seedBriefingPreset("/mem", now, zone))
+ store.update("u") { it.copy(name = "Mine") }
+ assertTrue(store.hasBriefingPreset())
+ assertNull(store.seedBriefingPreset("/mem", now, zone))
+ assertEquals(1, store.all().size)
+ }
+
+ @Test
+ fun `renaming the seeded preset neither duplicates it nor shows the re-add path`() {
+ val zone = java.time.ZoneId.of("UTC")
+ val now = java.time.LocalDateTime.parse("2026-10-29T22:15").atZone(zone).toInstant().toEpochMilli()
+ val seeded = store.seedBriefingPreset("/mem", now, zone)!!
+ store.update(seeded.id) { it.copy(name = "My mornings") }
+
+ assertNull(store.seedBriefingPreset("/mem", now, zone))
+ assertEquals(1, store.all().size)
+ assertTrue(store.hasBriefingPreset())
+
+ store.delete(seeded.id)
+ assertTrue(!store.hasBriefingPreset())
+ }
}