Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,18 @@
relations it declares. Rows already lost to the old behavior stay lost; re-index
the affected notes to bring them back as unresolved.

### Fixes

- **#1451**: A markdown file whose leading `---` block is not a YAML mapping (a letterhead between
horizontal rules) is now indexed as plain markdown instead of being dropped. The parser
already treated such a block as body; the indexer separately saw fences, tried to write
a permalink into them, hit the "refusing to update malformed frontmatter" guard, and
excluded the file while readiness reported idle. The guard stands: the file is never
rewritten, and `remove_frontmatter` no longer strips such a block from search content.
Frontmatter is now classified once, by the parser, as present, absent, or
malformed, and only the first two are ever written to.


## v0.23.2 (2026-08-25)

Patch release fixing case-duplicate folder creation.
Expand Down
27 changes: 20 additions & 7 deletions src/basic_memory/file_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -480,25 +480,38 @@ def remove_frontmatter(content: str, *, strip: bool = True) -> str:
reflow the note body (issue #1090 review).

Returns:
Content with frontmatter removed, or original content if no frontmatter
Content with frontmatter removed, or the original content when there is
no frontmatter: no fences, or a fenced block that is not a YAML mapping.

Raises:
ParseError: If content starts with frontmatter marker but is malformed
ParseError: If content opens with a fence that is never closed
"""
# Strip BOM before processing
content = strip_bom(content)

split = _split_frontmatter(content)
# Trigger: content does not open with a line-anchored fence
# Why: inline `---` is ordinary content, not frontmatter (issue #972)
# Trigger: content does not open with a line-anchored fence, or the fenced
# block is not a YAML mapping (a letterhead between horizontal rules, a
# bare scalar, a list).
# Why: inline `---` is ordinary content, not frontmatter (issue #972), and a
# fenced block that no frontmatter parser would accept is body text; the
# indexer treats it that way and search must not strip it (#1451).
# Outcome: return the content untouched (stripped to preserve prior behavior)
if split is None:
if split is None or not _is_frontmatter_mapping(split[0]):
return content.strip() if strip else content

_, body = split
return body.strip() if strip else body


def _is_frontmatter_mapping(yaml_block: str) -> bool:
"""Whether a fenced block is what every frontmatter reader here accepts: a YAML
mapping, or empty. The same rule `parse_frontmatter` enforces by raising."""
try:
loaded = yaml.safe_load(yaml_block)
except yaml.YAMLError:
return False
return loaded is None or isinstance(loaded, dict)


def dump_frontmatter(post: frontmatter.Post) -> str:
"""
Serialize frontmatter.Post to markdown with Obsidian-compatible YAML format.
Expand Down
34 changes: 19 additions & 15 deletions src/basic_memory/indexing/batch_indexer.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,9 @@
from basic_memory.file_utils import (
ParseError,
compute_checksum,
has_frontmatter,
remove_frontmatter,
)
from basic_memory.markdown.schemas import EntityMarkdown
from basic_memory.markdown.schemas import FrontmatterState, EntityMarkdown
from basic_memory.indexing.models import (
IndexEntitySearchWriter,
IndexedEntity,
Expand Down Expand Up @@ -116,7 +115,7 @@ class _PreparedMarkdownFile:
content: str
final_checksum: str
markdown: EntityMarkdown
file_contains_frontmatter: bool
frontmatter_state: FrontmatterState


@dataclass(slots=True)
Expand Down Expand Up @@ -372,7 +371,6 @@ async def _prepare_markdown_file(self, file: IndexInputFile) -> _PreparedMarkdow
raise ValueError(f"Missing content for markdown file: {file.path}")

content = file.content.decode("utf-8")
file_contains_frontmatter = has_frontmatter(content)
final_checksum = await self._resolve_checksum(file)
entity_markdown = await self.entity_service.entity_parser.parse_markdown_content(
file_path=Path(file.path),
Expand All @@ -386,7 +384,9 @@ async def _prepare_markdown_file(self, file: IndexInputFile) -> _PreparedMarkdow
content=content,
final_checksum=final_checksum,
markdown=entity_markdown,
file_contains_frontmatter=file_contains_frontmatter,
# The parser's classification, not a fence check: a fenced block that is
# not YAML must be indexed without ever being rewritten (#1451).
frontmatter_state=entity_markdown.frontmatter_state,
Comment thread
phernandez marked this conversation as resolved.
Resolved
)

async def _normalize_markdown_batch(
Expand Down Expand Up @@ -436,7 +436,9 @@ async def _normalize_markdown_file(
# Trigger: markdown file has no frontmatter and sync enforcement is enabled.
# Why: downstream indexing relies on normalized metadata and stable permalinks.
# Outcome: write derived metadata back through the storage-agnostic writer.
if not prepared.file_contains_frontmatter and self.app_config.ensure_frontmatter_on_sync:
# A "malformed" file matches neither branch: its fenced block is not YAML,
# so no rewrite can know which bytes were metadata; it is indexed as-is.
if prepared.frontmatter_state == "absent" and self.app_config.ensure_frontmatter_on_sync:
frontmatter_updates = {
"title": prepared.markdown.frontmatter.title,
"type": prepared.markdown.frontmatter.type,
Expand All @@ -453,7 +455,7 @@ async def _normalize_markdown_file(
# Why: batch sync keeps permalinks stable without forcing a full rewrite when unchanged.
# Outcome: only the permalink field is updated when it actually differs.
elif (
prepared.file_contains_frontmatter
prepared.frontmatter_state == "present"
and not self.app_config.disable_permalinks
and final_permalink != prepared.markdown.frontmatter.permalink
):
Expand All @@ -472,7 +474,7 @@ async def _normalize_markdown_file(
content=final_content,
final_checksum=final_checksum,
markdown=prepared.markdown,
file_contains_frontmatter=prepared.file_contains_frontmatter,
frontmatter_state=prepared.frontmatter_state,
)

async def _resolve_batch_permalink(
Expand All @@ -481,8 +483,8 @@ async def _resolve_batch_permalink(
reserved_permalinks: set[str],
) -> str | None:
should_resolve_permalink = (
not prepared.file_contains_frontmatter and self.app_config.ensure_frontmatter_on_sync
) or (prepared.file_contains_frontmatter and not self.app_config.disable_permalinks)
prepared.frontmatter_state == "absent" and self.app_config.ensure_frontmatter_on_sync
) or (prepared.frontmatter_state == "present" and not self.app_config.disable_permalinks)
if not should_resolve_permalink:
permalink = prepared.markdown.frontmatter.permalink
if permalink:
Expand Down Expand Up @@ -1054,12 +1056,14 @@ async def _reconcile_persisted_permalink(
# to leave frontmatterless files alone.
# Why: upsert may still assign a DB permalink even when disk content should stay untouched.
# Outcome: skip reconciliation writes that would silently inject frontmatter.
rewrite_allowed = (
self.app_config.ensure_frontmatter_on_sync
if prepared.frontmatter_state == "absent"
else prepared.frontmatter_state == "present"
)
if (
self.app_config.disable_permalinks
or (
not prepared.file_contains_frontmatter
and not self.app_config.ensure_frontmatter_on_sync
)
or not rewrite_allowed
or entity.permalink is None
or entity.permalink == prepared.markdown.frontmatter.permalink
):
Expand All @@ -1083,7 +1087,7 @@ async def _reconcile_persisted_permalink(
content=write_result.content,
final_checksum=write_result.checksum,
markdown=prepared.markdown,
file_contains_frontmatter=prepared.file_contains_frontmatter,
frontmatter_state=prepared.frontmatter_state,
)

async def _build_prepared_entity(
Expand Down
33 changes: 25 additions & 8 deletions src/basic_memory/markdown/entity_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,14 @@

import dateparser
import frontmatter
import yaml
from loguru import logger
from markdown_it import MarkdownIt

from basic_memory.markdown.plugins import observation_plugin, relation_plugin
from basic_memory.markdown.schemas import (
EntityFrontmatter,
EntityMarkdown,
FrontmatterState,
Observation,
Relation,
)
Expand Down Expand Up @@ -273,7 +273,12 @@ async def parse_markdown_content(
"""
# Strip BOM before parsing (can be present in files from Windows or certain sources)
# See issue #452
from basic_memory.file_utils import strip_bom
from basic_memory.file_utils import (
ParseError,
has_frontmatter,
parse_frontmatter,
strip_bom,
)

content = strip_bom(content)

Expand All @@ -286,15 +291,26 @@ async def parse_markdown_content(
# loads() does Post(content, handler, **metadata), which crashes when
# the YAML contains reserved keys like 'content' or 'handler'.
# See basic-memory-cloud#375.
try:
# Classify before splitting. python-frontmatter strips a fenced block that
# is valid YAML but not a mapping (a bare scalar, a list) as if it were
# metadata, silently discarding its text; parse_frontmatter applies the
# rule every writer here enforces, so a block it rejects is body (#1451).
frontmatter_state: FrontmatterState = "absent"
if has_frontmatter(content):
try:
parse_frontmatter(content)
frontmatter_state = "present"
except ParseError as e:
logger.warning(
f"Failed to parse YAML frontmatter in {file_path}: {e}. "
f"Treating file as plain markdown without frontmatter."
)
frontmatter_state = "malformed"
if frontmatter_state == "present":
fm_metadata, fm_content = frontmatter.parse(content)
post = frontmatter.Post(fm_content)
post.metadata.update(fm_metadata)
except yaml.YAMLError as e:
logger.warning(
f"Failed to parse YAML frontmatter in {file_path}: {e}. "
f"Treating file as plain markdown without frontmatter."
)
else:
# Use Post(content) not Post(content, metadata={})
# The latter creates {"metadata": {}} in the metadata dict (issue #528)
post = frontmatter.Post(content)
Expand Down Expand Up @@ -379,6 +395,7 @@ async def parse_markdown_content(

return EntityMarkdown(
frontmatter=entity_frontmatter,
frontmatter_state=frontmatter_state,
content=post.content,
observations=entity_content.observations,
relations=entity_content.relations,
Expand Down
13 changes: 12 additions & 1 deletion src/basic_memory/markdown/schemas.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Schema models for entity markdown files."""

from datetime import datetime
from typing import override, TYPE_CHECKING, Any, List, Optional
from typing import Literal, override, TYPE_CHECKING, Any, List, Optional

from pydantic import BaseModel, Field, model_validator

Expand Down Expand Up @@ -99,10 +99,21 @@ def permalink(self) -> Optional[str]:
return permalink if isinstance(permalink, str) else None


# What the parser found at the top of the file. "present" is a fenced block
# that parsed as YAML and can be rewritten field by field; "absent" means no
# fences, so frontmatter may be injected; "malformed" is a fenced block that is
# not YAML (a letterhead between horizontal rules, a broken document). The
# indexer must never rewrite a malformed block, because it cannot know which
# bytes the author meant as metadata, and must still index the file (#1451).
type FrontmatterState = Literal["present", "absent", "malformed"]


class EntityMarkdown(BaseModel):
"""Complete entity combining frontmatter, content, and metadata."""

frontmatter: EntityFrontmatter
# The parser always sets this; the default only serves hand-built values.
frontmatter_state: FrontmatterState = "present"
content: Optional[str] = None
observations: List[Observation] = []
relations: List[Relation] = []
Expand Down
Loading
Loading