basic-memory icon indicating copy to clipboard operation
basic-memory copied to clipboard

[BUG] Links at the beginning of a line are wrongly interpreted as observations

Open ottsch opened this issue 1 year ago • 3 comments

Bug Description

When a line starts with a [[Wikilink]], or a [Weblink](...) basic memory interprets it as an observation.

Steps To Reproduce

Steps to reproduce the behavior:

[ESLint](https://eslint.org/) is the most popular JavaScript linter, providing static analysis to identify problematic patterns and enforce coding standards.
[[ESLint]] is the most popular JavaScript linter, providing static analysis to identify problematic patterns and enforce coding standards.
[fact] ESLint is the most popular JavaScript linter, providing static analysis to identify problematic patterns and enforce coding standards.

Expected Behavior

Only the fact line should be an observation.

Actual Behavior

Creates these observations categories:

  • ESLint
  • [ESLint
  • fact

Possible Solution

Fixing the matching regex

ottsch avatar Aug 04 '25 09:08 ottsch

--- a/src/basic_memory/markdown/plugins.py
+++ b/src/basic_memory/markdown/plugins.py
@@ ... @@
-def is_observation(token: Token) -> bool:
-    """Check if token looks like our observation format."""
-    if token.type != "inline": # pragma: no cover
-        return False
-    content = token.content.strip()
-    if not content: # pragma: no cover
-        return False
-    # if it's a markdown_task, return false
-    if content.startswith("[ ]") or content.startswith("[x]") or content.startswith("[-]"):
-        return False
-    has_category = content.startswith("[") and "]" in content
-    has_tags = "#" in content
-    return has_category or has_tags
+def is_observation(token: Token) -> bool:
+    """Check if token looks like our observation format."""
+    import re
+    if token.type != "inline":  # pragma: no cover
+        return False
+    content = token.content.strip()
+    if not content:  # pragma: no cover
+        return False
+    # if it's a markdown_task, return false
+    if content.startswith("[ ]") or content.startswith("[x]") or content.startswith("[-]"):
+        return False
+    match = re.match(r"^\[([^\[\]()]+)\]\s+(.+)", content)
+    has_tags = "#" in content
+    return bool(match) or has_tags

-def parse_observation(token: Token) -> Dict[str, Any]:
-    """Extract observation parts from token."""
-    # Strip bullet point if present
-    content = token.content.strip()
-    # Parse [category]
-    category = None
-    if content.startswith("["):
-        end = content.find("]")
-        if end != -1:
-            category = content[1:end].strip() or None # Convert empty to None
-            content = content[end + 1 :].strip()
-    # Parse (context)
-    context = None
-    if content.endswith(")"):
-        start = content.rfind("(")
-        if start != -1:
-            context = content[start + 1 : -1].strip()
-            content = content[:start].strip()
-    # Extract tags and keep original content
-    tags = []
-    parts = content.split()
-    for part in parts:
-        if part.startswith("#"):
-            # Handle multiple #tags stuck together
-            if "#" in part[1:]:
-                # Split on # but keep non-empty tags
-                subtags = [t for t in part.split("#") if t]
-                tags.extend(subtags)
-            else:
-                tags.append(part[1:])
-    return {
-        "category": category,
-        "content": content,
-        "tags": tags if tags else None,
-        "context": context,
-    }
+def parse_observation(token: Token) -> Dict[str, Any]:
+    """Extract observation parts from token."""
+    import re
+    content = token.content.strip()
+    match = re.match(r"^\[([^\[\]()]+)\]\s+(.+)", content)
+    category = None
+    if match:
+        category = match.group(1).strip()
+        content = match.group(2).strip()
+    # Parse (context)
+    context = None
+    if content.endswith(")"):
+        start = content.rfind("(")
+        if start != -1:
+            context = content[start + 1 : -1].strip()
+            content = content[:start].strip()
+    # Extract tags and keep original content
+    tags = []
+    parts = content.split()
+    for part in parts:
+        if part.startswith("#"):
+            if "#" in part[1:]:
+                subtags = [t for t in part.split("#") if t]
+                tags.extend(subtags)
+            else:
+                tags.append(part[1:])
+    return {
+        "category": category,
+        "content": content,
+        "tags": tags if tags else None,
+        "context": context,
+    }

ottsch avatar Aug 04 '25 10:08 ottsch

@claude can you take a look at this?

jope-bm avatar Aug 22 '25 20:08 jope-bm

Claude finished @jope-bm's task —— View job • claude/issue-247-20250822-2037 • Create PR ➔


Analyzing and fixing observation parsing bug ✅

I've successfully fixed the bug where links at the beginning of lines were incorrectly interpreted as observations.

Todo List:

  • [x] Read and analyze current observation parsing code
  • [x] Understand the bug and test the suggested fix
  • [x] Implement the regex-based solution
  • [x] Run tests to verify the fix
  • [x] Run linting and type checking
  • [x] Commit and push changes
  • [x] Create PR link

Summary of Changes:

Fixed the root cause in src/basic_memory/markdown/plugins.py:

  1. Updated is_observation() (line 22): Replaced simple bracket detection with regex pattern ^\[([^\[\]()]+)\]\s+(.+) that requires:

    • [category] format with no nested brackets or parentheses
    • Followed by whitespace and content
  2. Updated parse_observation(): Uses the same regex for consistent parsing of category and content

Before (buggy):

has_category = content.startswith("[") and "]" in content  # Too permissive!

After (fixed):

match = re.match(r"^\[([^\[\]()]+)\]\s+(.+)", content)  # Proper validation

Test Cases Now Work Correctly:

  • [ESLint](https://eslint.org/) → ❌ Not an observation (correct)
  • [[ESLint]] → ❌ Not an observation (correct)
  • [fact] ESLint is... → ✅ Observation with category "fact" (correct)

claude[bot] avatar Aug 22 '25 20:08 claude[bot]