Skip to content

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

Address PR #158 review: shared table geometry, backlinks, search threading

Rishabh Bajpaie8c8b1615bdf
diff --git a/app/src/main/java/com/gotcha/data/MemoryStore.kt b/app/src/main/java/com/gotcha/data/MemoryStore.kt
index d213165..5a96d47 100644
--- a/app/src/main/java/com/gotcha/data/MemoryStore.kt
+++ b/app/src/main/java/com/gotcha/data/MemoryStore.kt
@@ -350,6 +350,9 @@ object MemoryStore {
/** One scheduled task whose linked note no longer exists in the vault. */
data class StaleTaskLink(val taskName: String, val path: String)
+ /** One scheduled task pointing at a real note that does not name it back in `task_ref`. */
+ data class MissingBacklink(val fileId: String, val taskName: String)
+
/** Orphan dashboard: everything that keeps the Second Brain from hanging together. */
data class BrainHealth(
val unlinked: List<String>,
@@ -358,15 +361,16 @@ object MemoryStore {
val unknownTasks: List<TaskNoteRef>,
val mismatchedTasks: List<TaskMismatch> = emptyList(),
val staleTaskLinks: List<StaleTaskLink> = emptyList(),
- val unscanned: List<String> = emptyList()
+ val unscanned: List<String> = emptyList(),
+ val missingBacklinks: List<MissingBacklink> = emptyList()
) {
val isClean: Boolean
get() = unlinked.isEmpty() && dangling.isEmpty() && invalid.isEmpty() &&
unknownTasks.isEmpty() && mismatchedTasks.isEmpty() &&
- staleTaskLinks.isEmpty() && unscanned.isEmpty()
+ staleTaskLinks.isEmpty() && unscanned.isEmpty() && missingBacklinks.isEmpty()
val issueCount: Int
get() = unlinked.size + dangling.size + invalid.size + unknownTasks.size +
- mismatchedTasks.size + staleTaskLinks.size + unscanned.size
+ mismatchedTasks.size + staleTaskLinks.size + unscanned.size + missingBacklinks.size
}
/** Root files are navigation hubs, not content: never reported as unlinked. */
@@ -401,24 +405,39 @@ object MemoryStore {
val unknownTasks = mutableListOf<TaskNoteRef>()
val mismatched = mutableListOf<TaskMismatch>()
val unscanned = mutableListOf<String>()
+ // Canonical note path to (id, task_ref) for the reverse backlink pass.
+ val noteRefs = mutableMapOf<String, Pair<String, 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]
+ val ref = frontmatterOf(full)?.get("task_ref")?.takeIf { it.isNotBlank() }
+ runCatching { File(file.absolutePath).canonicalPath }.getOrNull()?.let { canonical ->
+ noteRefs[canonical] = id to ref
+ }
+ ref?.let {
+ val task = byTaskId[it]
when {
- task == null -> unknownTasks.add(TaskNoteRef(id, ref))
+ task == null -> unknownTasks.add(TaskNoteRef(id, it))
task.notePath == null || !samePath(task.notePath, file.absolutePath) ->
- mismatched.add(TaskMismatch(id, ref, task.notePath))
+ mismatched.add(TaskMismatch(id, it, task.notePath))
}
}
}
- val stale = taskLinks.mapNotNull { task ->
- val path = task.notePath ?: return@mapNotNull null
- if (vaultNotePaths.none { samePath(it, path) }) StaleTaskLink(task.name, path) else null
+ val stale = mutableListOf<StaleTaskLink>()
+ val missingBacklinks = mutableListOf<MissingBacklink>()
+ taskLinks.forEach { task ->
+ val path = task.notePath ?: return@forEach
+ val canonical = runCatching { File(path).canonicalPath }.getOrNull()
+ val entry = canonical?.let { noteRefs[it] }
+ when {
+ entry == null && vaultNotePaths.none { samePath(it, path) } ->
+ stale.add(StaleTaskLink(task.name, path))
+ entry != null && entry.second != task.id ->
+ missingBacklinks.add(MissingBacklink(entry.first, task.name))
+ }
}
return BrainHealth(
unlinked.sorted(),
@@ -427,7 +446,8 @@ object MemoryStore {
unknownTasks,
mismatched,
stale,
- unscanned.sorted()
+ unscanned.sorted(),
+ missingBacklinks.sortedBy { it.fileId }
)
}
diff --git a/app/src/main/java/com/gotcha/ui/MarkdownTable.kt b/app/src/main/java/com/gotcha/ui/MarkdownTable.kt
index 060ec84..7da652d 100644
--- a/app/src/main/java/com/gotcha/ui/MarkdownTable.kt
+++ b/app/src/main/java/com/gotcha/ui/MarkdownTable.kt
@@ -3,21 +3,29 @@
package com.gotcha.ui
import androidx.compose.foundation.horizontalScroll
-import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
-import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
-import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState
-import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.ProvideTextStyle
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
+import androidx.compose.runtime.remember
+import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.drawBehind
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.layout.Layout
+import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.dp
+import com.halilibo.richtext.markdown.Markdown
+import com.halilibo.richtext.ui.material3.Material3RichText
/** Column alignment parsed from a GFM delimiter row (`:---`, `:--:`, `---:`). */
enum class TableAlign { LEFT, CENTER, RIGHT }
@@ -26,7 +34,7 @@ enum class TableAlign { LEFT, CENTER, RIGHT }
* A GFM table: pipe header, delimiter row, pipe body rows. The bundled
* Markdown renderer sizes every column equally, which squeezes wide tables
* into unreadable slivers on a phone, so tables are drawn here instead in a
- * sideways-scrollable grid with capped column widths.
+ * sideways-scrollable grid whose columns size to their content.
*/
fun splitTables(prose: String): List<MarkdownSegment> {
val segments = mutableListOf<MarkdownSegment>()
@@ -67,16 +75,28 @@ fun splitTables(prose: String): List<MarkdownSegment> {
return segments
}
-/** Table-eligible line: up to 3 leading spaces (GFM allows 3). deeper indents are code, `>` quotes stay with the bundled renderer. */
+/** Table-eligible line: visual indent under 4 (GFM allows 3 spaces). deeper indents are code, `>` quotes stay with the bundled renderer. */
private fun tableLine(line: String?): String? {
if (line == null) return null
val stripped = line.trimStart()
if (stripped.startsWith('>')) return null
- val indent = line.length - stripped.length
- if (line.startsWith('\t') || indent >= 4) return null
+ if (visualIndent(line) >= 4) return null
return stripped
}
+/** Visual indent in columns: spaces count 1, tabs advance to the next multiple of 4. */
+private fun visualIndent(line: String): Int {
+ var column = 0
+ for (ch in line) {
+ when (ch) {
+ ' ' -> column++
+ '\t' -> column = (column / 4 + 1) * 4
+ else -> break
+ }
+ }
+ return column
+}
+
/** True when [line] is a GFM delimiter row: pipes of dashes with optional edge colons. */
private fun isDelimiterRow(line: String): Boolean {
val cells = splitRow(line)
@@ -84,38 +104,45 @@ private fun isDelimiterRow(line: String): Boolean {
return cells.all { it.matches(Regex(":?-{1,}:?")) }
}
-/** Splits one table row on unescaped pipes; trims cells and drops the outer pair. */
+/**
+ * Splits one table row on unescaped pipes. Escapes pass through untouched for
+ * the cell renderer (a Markdown parser): `\|` renders as `|`, `\\` as `\`.
+ * Leading/trailing pipes count as an outer border only when both are really
+ * there; otherwise edge empties are real cells (` | second` in a two-column
+ * table means an empty first cell).
+ */
private fun splitRow(line: String): List<String> {
+ val s = line.trim()
val cells = mutableListOf<String>()
val cur = StringBuilder()
- var escaped = false
- line.forEach { ch ->
- when {
- escaped -> {
- cur.append(ch)
- escaped = false
- }
- ch == '\\' -> escaped = true
- ch == '|' -> {
- cells += cur.toString()
- cur.clear()
- }
- else -> cur.append(ch)
+ s.forEachIndexed { index, ch ->
+ if (ch == '|' && !isEscaped(s, index)) {
+ cells += cur.toString().trim()
+ cur.clear()
+ } else {
+ cur.append(ch)
}
}
- cells += cur.toString()
- val trimmed = cells.map { it.trim() }
- val inner = { list: List<String> ->
- var result = list
- if (result.isNotEmpty() && result.first().isEmpty()) result = result.drop(1)
- if (result.isNotEmpty() && result.last().isEmpty()) result = result.dropLast(1)
- result
+ cells += cur.toString().trim()
+ if (cells.size >= 2 && s.startsWith('|') && s.endsWith('|') && !isEscaped(s, s.length - 1)) {
+ return cells.drop(1).dropLast(1)
}
- return inner(trimmed)
+ return cells
+}
+
+/** True when the char at [index] is escaped by an odd run of backslashes. */
+private fun isEscaped(s: String, index: Int): Boolean {
+ var backslashes = 0
+ var k = index - 1
+ while (k >= 0 && s[k] == '\\') {
+ backslashes++
+ k--
+ }
+ return backslashes % 2 == 1
}
private fun alignOf(cell: String): TableAlign = when {
- cell.startsWith(':') && cell.endsWith(':') -> TableAlign.CENTER
+ cell.startsWith(':') && cell.endsWith(':') && cell.length > 1 -> TableAlign.CENTER
cell.endsWith(':') -> TableAlign.RIGHT
else -> TableAlign.LEFT
}
@@ -131,10 +158,90 @@ private fun TableAlign.toTextAlign(): TextAlign = when (this) {
TableAlign.RIGHT -> TextAlign.End
}
+/** Grid lines recorded during measure and drawn afterwards. Plain holder, never state. */
+private class TableGeometry {
+ val verticals = mutableListOf<Float>()
+ val horizontals = mutableListOf<Float>()
+ var width = 0f
+ var height = 0f
+}
+
+/**
+ * A grid with shared column widths and shared row heights: every cell of a
+ * row sits on the same baseline band, so wrapped text can never pair values
+ * with the wrong row. Columns size to their content between [minColumnWidth]
+ * and [maxColumnWidth]; the caller scrolls sideways. Cells are measured
+ * twice (intrinsics, then fixed width) and placed once.
+ */
+@Composable
+private fun TableGrid(
+ columnCount: Int,
+ minColumnWidth: Int,
+ maxColumnWidth: Int,
+ lineColor: Color,
+ modifier: Modifier = Modifier,
+ content: @Composable () -> Unit
+) {
+ val geometry = remember { TableGeometry() }
+ Layout(
+ content = content,
+ modifier = modifier.drawBehind {
+ geometry.verticals.forEach { x ->
+ drawLine(lineColor, Offset(x, 0f), Offset(x, geometry.height))
+ }
+ geometry.horizontals.forEach { y ->
+ drawLine(lineColor, Offset(0f, y), Offset(geometry.width, y))
+ }
+ }
+ ) { measurables, _ ->
+ val rows = measurables.chunked(columnCount).filter { it.size == columnCount }
+ if (rows.isEmpty()) {
+ geometry.verticals.clear()
+ geometry.horizontals.clear()
+ return@Layout layout(0, 0) {}
+ }
+ // No intrinsics: library text uses BoxWithConstraints, which throws on
+ // intrinsic measurement. Instead measure once capped (content width),
+ // then again at the shared width (wrapping height).
+ val columnWidths = IntArray(columnCount) { column ->
+ rows.maxOf { row ->
+ row[column].measure(Constraints(maxWidth = maxColumnWidth)).width
+ }.coerceIn(minColumnWidth, maxColumnWidth)
+ }
+ val placed = rows.map { row ->
+ row.mapIndexed { column, measurable ->
+ measurable.measure(Constraints.fixedWidth(columnWidths[column]))
+ }
+ }
+ val rowHeights = placed.map { row -> row.maxOf { it.height } }
+ val columnLefts = IntArray(columnCount + 1)
+ for (column in 1..columnCount) {
+ columnLefts[column] = columnLefts[column - 1] + columnWidths[column - 1]
+ }
+ val rowTops = IntArray(rows.size + 1)
+ for (row in 1..rows.size) {
+ rowTops[row] = rowTops[row - 1] + rowHeights[row - 1]
+ }
+ geometry.verticals.clear()
+ geometry.horizontals.clear()
+ columnLefts.forEach { geometry.verticals += it.toFloat() }
+ rowTops.forEach { geometry.horizontals += it.toFloat() }
+ geometry.width = columnLefts[columnCount].toFloat()
+ geometry.height = rowTops[rows.size].toFloat()
+ layout(columnLefts[columnCount], rowTops[rows.size]) {
+ placed.forEachIndexed { row, cells ->
+ cells.forEachIndexed { column, placeable ->
+ placeable.place(columnLefts[column], rowTops[row])
+ }
+ }
+ }
+ }
+}
+
/**
* A sideways-scrollable table: columns size to their content between a fixed
- * min and max, so narrow columns stay compact and wide ones wrap instead of
- * squeezing their neighbours.
+ * min and max, rows share one height band, cells render inline Markdown so
+ * emphasis, code and links keep working.
*/
@Composable
fun MarkdownTable(
@@ -143,38 +250,51 @@ fun MarkdownTable(
rows: List<List<String>>,
modifier: Modifier = Modifier
) {
+ if (headers.isEmpty()) return
+ val bodyStyle = MaterialTheme.typography.bodySmall
+ val headerStyle = bodyStyle.copy(fontWeight = FontWeight.Bold)
+ val lineColor = MaterialTheme.colorScheme.outlineVariant
+ val density = LocalDensity.current
+ val minColumnWidth = remember(density) { with(density) { 84.dp.roundToPx() } }
+ val maxColumnWidth = remember(density) { with(density) { 240.dp.roundToPx() } }
Surface(
- modifier = modifier.fillMaxWidth(),
+ modifier = modifier,
shape = MaterialTheme.shapes.small,
tonalElevation = 1.dp
) {
Row(modifier = Modifier.horizontalScroll(rememberScrollState())) {
- headers.forEachIndexed { index, header ->
- val align = aligns.getOrElse(index) { TableAlign.LEFT }.toTextAlign()
- val cells = rows.map { it.getOrElse(index) { "" } }
- Column(
- modifier = Modifier
- .widthIn(min = 84.dp, max = 240.dp)
- .padding(horizontal = 10.dp, vertical = 6.dp)
- ) {
- // No fillMaxWidth: in the scrolling row each column sizes
- // to its content (within the caps) instead of every
- // column stretching to the 240dp maximum.
- Text(
- text = header,
- style = MaterialTheme.typography.bodySmall,
- fontWeight = FontWeight.Bold,
- textAlign = align
- )
- HorizontalDivider(modifier = Modifier.padding(vertical = 4.dp))
- cells.forEachIndexed { rowIndex, cell ->
- Text(
- text = cell,
- style = MaterialTheme.typography.bodySmall,
- textAlign = align
- )
- if (rowIndex < cells.size - 1) {
- HorizontalDivider(modifier = Modifier.padding(vertical = 4.dp))
+ TableGrid(
+ columnCount = headers.size,
+ minColumnWidth = minColumnWidth,
+ maxColumnWidth = maxColumnWidth,
+ lineColor = lineColor
+ ) {
+ headers.forEachIndexed { index, header ->
+ ProvideTextStyle(
+ headerStyle.copy(textAlign = aligns.getOrElse(index) { TableAlign.LEFT }.toTextAlign())
+ ) {
+ // No fillMaxWidth: the grid measures content width, so
+ // filling here would stretch every column to the cap.
+ // Alignment comes from the cell Box instead.
+ Box(
+ modifier = Modifier.padding(horizontal = 10.dp, vertical = 6.dp),
+ contentAlignment = aligns.getOrElse(index) { TableAlign.LEFT }.toAlignment()
+ ) {
+ Text(header)
+ }
+ }
+ }
+ rows.forEach { row ->
+ headers.indices.forEach { index ->
+ ProvideTextStyle(
+ bodyStyle.copy(textAlign = aligns.getOrElse(index) { TableAlign.LEFT }.toTextAlign())
+ ) {
+ Box(
+ modifier = Modifier.padding(horizontal = 10.dp, vertical = 6.dp),
+ contentAlignment = aligns.getOrElse(index) { TableAlign.LEFT }.toAlignment()
+ ) {
+ TableCellContent(row.getOrElse(index) { "" })
+ }
}
}
}
@@ -182,3 +302,17 @@ fun MarkdownTable(
}
}
}
+
+/** One table cell's inline Markdown, shrink-wrapped so the grid measures content width. */
+@Composable
+private fun TableCellContent(markdown: String) {
+ Material3RichText {
+ Markdown(markdown)
+ }
+}
+
+private fun TableAlign.toAlignment(): Alignment = when (this) {
+ TableAlign.LEFT -> Alignment.TopStart
+ TableAlign.CENTER -> Alignment.TopCenter
+ TableAlign.RIGHT -> Alignment.TopEnd
+}
diff --git a/app/src/main/java/com/gotcha/ui/SecondBrainScreen.kt b/app/src/main/java/com/gotcha/ui/SecondBrainScreen.kt
index f1d0d22..8e2fcb3 100644
--- a/app/src/main/java/com/gotcha/ui/SecondBrainScreen.kt
+++ b/app/src/main/java/com/gotcha/ui/SecondBrainScreen.kt
@@ -55,6 +55,7 @@ import com.gotcha.data.MemoryStore
import com.gotcha.scheduled.ScheduledTaskStore
import com.gotcha.tools.FileResolver
import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import java.io.File
import kotlin.math.cos
@@ -153,6 +154,21 @@ fun SecondBrainScreen(onBack: () -> Unit) {
SecondBrainGraphView(snapshot = current)
} else {
var search by remember(current) { mutableStateOf("") }
+ var shown by remember(current) { mutableStateOf(current) }
+ // Filtering reads full files past the preview cap: off the main
+ // thread, debounced so scans start after typing pauses. A scan
+ // already running is left to finish (its result is discarded);
+ // scans are bounded reads, so overlap stays brief.
+ LaunchedEffect(current, search) {
+ if (search.isBlank()) {
+ shown = current
+ } else {
+ delay(300)
+ shown = withContext(Dispatchers.Default) {
+ MemoryStore.filterSnapshot(current, search)
+ }
+ }
+ }
OutlinedTextField(
value = search,
onValueChange = { search = it },
@@ -162,9 +178,7 @@ fun SecondBrainScreen(onBack: () -> Unit) {
.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) {
+ if (search.isNotBlank() && remember(shown) { shown.isEmpty() }) {
Text(
text = stringResource(R.string.second_brain_no_matches, search.trim()),
style = MaterialTheme.typography.bodyMedium,
@@ -954,7 +968,11 @@ private fun BrainSection(heading: String, file: MemoryStore.BrainFile, tag: Stri
.fillMaxWidth()
.clickable(
role = Role.Button,
- onClickLabel = if (expanded) "Collapse" else "Expand"
+ onClickLabel = if (expanded) {
+ stringResource(R.string.message_collapse)
+ } else {
+ stringResource(R.string.message_expand)
+ }
) { expanded = !expanded }
.padding(vertical = 4.dp)
)
@@ -981,7 +999,11 @@ private fun BrainFileList(heading: String, files: List<MemoryStore.BrainFile>, t
.fillMaxWidth()
.clickable(
role = Role.Button,
- onClickLabel = if (expanded) "Collapse" else "Expand"
+ onClickLabel = if (expanded) {
+ stringResource(R.string.message_collapse)
+ } else {
+ stringResource(R.string.message_expand)
+ }
) { expanded = !expanded }
.padding(vertical = 4.dp)
)
@@ -1003,7 +1025,11 @@ private fun BrainFileList(heading: String, files: List<MemoryStore.BrainFile>, t
.fillMaxWidth()
.clickable(
role = Role.Button,
- onClickLabel = if (fileExpanded) "Collapse" else "Expand"
+ onClickLabel = if (fileExpanded) {
+ stringResource(R.string.message_collapse)
+ } else {
+ stringResource(R.string.message_expand)
+ }
) { fileExpanded = !fileExpanded }
.padding(vertical = 2.dp)
.testTag("settings_second_brain_${tag}_$index")
@@ -1041,7 +1067,11 @@ private fun BrainHealthSection(health: MemoryStore.BrainHealth) {
.fillMaxWidth()
.clickable(
role = Role.Button,
- onClickLabel = if (expanded) "Collapse" else "Expand"
+ onClickLabel = if (expanded) {
+ stringResource(R.string.message_collapse)
+ } else {
+ stringResource(R.string.message_expand)
+ }
) { expanded = !expanded }
.padding(vertical = 4.dp)
)
@@ -1065,7 +1095,13 @@ private fun BrainHealthSection(health: MemoryStore.BrainHealth) {
R.string.second_brain_health_dangling,
health.dangling.size
),
- lines = health.dangling.map { "${it.fromId} → [[${it.target}]]" }
+ lines = health.dangling.map {
+ stringResource(
+ R.string.second_brain_health_dangling_line,
+ it.fromId,
+ it.target
+ )
+ }
)
HealthGroup(
heading = stringResource(
@@ -1073,7 +1109,11 @@ private fun BrainHealthSection(health: MemoryStore.BrainHealth) {
health.invalid.size
),
lines = health.invalid.map { problem ->
- "${problem.fileId}: ${problem.errors.firstOrNull().orEmpty()}"
+ stringResource(
+ R.string.second_brain_health_invalid_line,
+ problem.fileId,
+ problem.errors.firstOrNull().orEmpty()
+ )
}
)
HealthGroup(
@@ -1081,7 +1121,13 @@ private fun BrainHealthSection(health: MemoryStore.BrainHealth) {
R.string.second_brain_health_unknown_tasks,
health.unknownTasks.size
),
- lines = health.unknownTasks.map { "${it.fileId} → ${it.taskId}" }
+ lines = health.unknownTasks.map {
+ stringResource(
+ R.string.second_brain_health_unknown_line,
+ it.fileId,
+ it.taskId
+ )
+ }
)
HealthGroup(
heading = stringResource(
@@ -1089,7 +1135,12 @@ private fun BrainHealthSection(health: MemoryStore.BrainHealth) {
health.mismatchedTasks.size
),
lines = health.mismatchedTasks.map {
- "${it.fileId} → task points at ${it.linkedPath ?: "(nowhere)"}"
+ stringResource(
+ R.string.second_brain_health_mismatch_line,
+ it.fileId,
+ it.linkedPath
+ ?: stringResource(R.string.second_brain_health_nowhere)
+ )
}
)
HealthGroup(
@@ -1097,7 +1148,26 @@ private fun BrainHealthSection(health: MemoryStore.BrainHealth) {
R.string.second_brain_health_stale,
health.staleTaskLinks.size
),
- lines = health.staleTaskLinks.map { "\"${it.taskName}\" → ${it.path}" }
+ lines = health.staleTaskLinks.map {
+ stringResource(
+ R.string.second_brain_health_stale_line,
+ it.taskName,
+ it.path
+ )
+ }
+ )
+ HealthGroup(
+ heading = stringResource(
+ R.string.second_brain_health_missing_backlink,
+ health.missingBacklinks.size
+ ),
+ lines = health.missingBacklinks.map {
+ stringResource(
+ R.string.second_brain_health_missing_backlink_line,
+ it.taskName,
+ it.fileId
+ )
+ }
)
HealthGroup(
heading = stringResource(
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 58dd302..2a191e9 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -83,11 +83,19 @@
<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_clean_detail">No unlinked files, dangling links, invalid records, task-link problems or files too large to scan.</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_invalid_line">%1$s: %2$s</string>
<string name="second_brain_health_unknown_tasks">Notes pointing at missing tasks (%1$d)</string>
+ <string name="second_brain_health_unknown_line">%1$s → %2$s</string>
+ <string name="second_brain_health_dangling_line">%1$s → [[%2$s]]</string>
+ <string name="second_brain_health_mismatch_line">%1$s → task points at %2$s</string>
+ <string name="second_brain_health_nowhere">(nowhere)</string>
+ <string name="second_brain_health_stale_line">“%1$s” → %2$s</string>
+ <string name="second_brain_health_missing_backlink">Tasks missing a link back from their note (%1$d)</string>
+ <string name="second_brain_health_missing_backlink_line">“%1$s” points at %2$s but the note does not name it back</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>
diff --git a/app/src/test/java/com/gotcha/data/MemoryStoreTest.kt b/app/src/test/java/com/gotcha/data/MemoryStoreTest.kt
index 1af439f..44e7c76 100644
--- a/app/src/test/java/com/gotcha/data/MemoryStoreTest.kt
+++ b/app/src/test/java/com/gotcha/data/MemoryStoreTest.kt
@@ -657,12 +657,17 @@ class MemoryStoreTest {
""
).joinToString("\n")
)
+ File(notes, "i.md").writeText(record("note", "Personal").replace("title: T", "title: I"))
val snap = MemoryStore.loadSnapshot()
+ val gPath = File(notes, "g.md").absolutePath
+ val iPath = File(notes, "i.md").absolutePath
val health = MemoryStore.checkHealth(
snap,
listOf(
MemoryStore.TaskLink("real-id", "Task", "/other/note.md"),
- MemoryStore.TaskLink("lonely-id", "Lonely", null)
+ MemoryStore.TaskLink("lonely-id", "Lonely", null),
+ MemoryStore.TaskLink("boss-id", "Boss", gPath),
+ MemoryStore.TaskLink("aim-id", "Aim", iPath)
)
)
assertTrue(health.unknownTasks.isEmpty())
@@ -676,6 +681,16 @@ class MemoryStoreTest {
MemoryStore.TaskMismatch("notes/h.md", "lonely-id", null)
)
)
+ assertTrue(
+ health.missingBacklinks.contains(
+ MemoryStore.MissingBacklink("notes/g.md", "Boss")
+ )
+ )
+ assertTrue(
+ health.missingBacklinks.contains(
+ MemoryStore.MissingBacklink("notes/i.md", "Aim")
+ )
+ )
assertEquals(
listOf(MemoryStore.StaleTaskLink("Task", "/other/note.md")),
health.staleTaskLinks
diff --git a/app/src/test/java/com/gotcha/ui/MarkdownTableTest.kt b/app/src/test/java/com/gotcha/ui/MarkdownTableTest.kt
index a62ffd9..c333668 100644
--- a/app/src/test/java/com/gotcha/ui/MarkdownTableTest.kt
+++ b/app/src/test/java/com/gotcha/ui/MarkdownTableTest.kt
@@ -35,10 +35,17 @@ class MarkdownTableTest {
}
@Test
- fun `escaped pipes stay inside cells`() {
+ fun `escaped pipes stay inside cells for the renderer to unescape`() {
val segments = splitTables("| A |\n|---|\n| x \\| y |")
val parsed = segments.single() as MarkdownSegment.Table
- assertEquals(listOf(listOf("x | y")), parsed.rows)
+ assertEquals(listOf(listOf("x \\| y")), parsed.rows)
+ }
+
+ @Test
+ fun `double backslashes before other punctuation pass through`() {
+ val segments = splitTables("P | Q\n--- | ---\nA\\\\* | B")
+ val parsed = segments.single() as MarkdownSegment.Table
+ assertEquals(listOf(listOf("A\\\\*", "B")), parsed.rows)
}
@Test
@@ -72,6 +79,36 @@ class MarkdownTableTest {
assertTrue(segments.single() is MarkdownSegment.Prose)
}
+ @Test
+ fun `empty edge cells stay in their column`() {
+ val segments = splitTables("A | B\n--- | ---\n | second")
+ val parsed = segments.single() as MarkdownSegment.Table
+ assertEquals(listOf(listOf("", "second")), parsed.rows)
+ }
+
+ @Test
+ fun `backslashes survive except before pipes`() {
+ val segments = splitTables("P | Q\n--- | ---\nC:\\Users\\Asha | ok")
+ val parsed = segments.single() as MarkdownSegment.Table
+ assertEquals(listOf(listOf("C:\\Users\\Asha", "ok")), parsed.rows)
+ }
+
+ @Test
+ fun `an escaped backslash before a pipe still splits`() {
+ val segments = splitTables("P | Q\n--- | ---\nC:\\\\ | next")
+ val parsed = segments.single() as MarkdownSegment.Table
+ // Raw text passes through; the cell renderer turns `\\` into `\`.
+ assertEquals(listOf(listOf("C:\\\\", "next")), parsed.rows)
+ }
+
+ @Test
+ fun `tab-indented pipe rows stay prose`() {
+ val segments = splitTables("P | Q\n--- | ---\n \t| x | y |")
+ assertEquals(2, segments.size)
+ assertTrue(segments[0] is MarkdownSegment.Table)
+ assertTrue(segments[1] is MarkdownSegment.Prose)
+ }
+
@Test
fun `indented code and quotes stay with the bundled renderer`() {
val code = " | A |\n |---|\n | x |"