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
1 change: 1 addition & 0 deletions src/basic_memory/api/v2/routers/schema_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ def _entity_to_note_data(entity: Entity) -> NoteData:
identifier=entity.permalink or entity.file_path,
observations=_entity_observations(entity),
relations=_entity_relations(entity),
frontmatter=_entity_frontmatter(entity),
)


Expand Down
10 changes: 9 additions & 1 deletion src/basic_memory/man/man3/bm-schema(3).md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,14 @@ do:
the share of notes a field must appear in.
- `diff` — compare a `note_type`'s notes with its schema to find drift.

A schema field is satisfied by a frontmatter key or an observation category of
the same name. Frontmatter is checked first: `attendees: 4` in frontmatter
satisfies `attendees: integer`, and a `- [attendees]` observation is used only
when the key is absent. Enum checks apply to either. A field whose type is
another note type is satisfied by relations. `infer` and `diff` count
frontmatter keys as fields, except `title`, `type`, `permalink`, `tags` and
`schema`.

A type with no schema, or no notes, is a `NOT_FOUND` error that says how to
create one.

Expand All @@ -59,7 +67,7 @@ bm_schema(command="validate", note_type="plan", project="demo")
# → # Schema Validation: plan
# Notes: 1 | Valid: 1 | Warnings: 1 | Errors: 0
# - **launch-plan** — valid
# - warning: Missing required field: owner (expected [owner] observation)
# - warning: Missing required field: owner (expected owner: in frontmatter or a [owner] observation)

bm_schema(command="diff", note_type="plan", project="demo")
# → # Schema Drift: plan
Expand Down
4 changes: 2 additions & 2 deletions src/basic_memory/picoschema/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
RelationData,
NoteData,
infer_schema,
analyze_observations,
analyze_fields,
analyze_relations,
)
from basic_memory.picoschema.diff import (
Expand Down Expand Up @@ -58,7 +58,7 @@
"RelationData",
"NoteData",
"infer_schema",
"analyze_observations",
"analyze_fields",
"analyze_relations",
# Diff
"SchemaDrift",
Expand Down
41 changes: 29 additions & 12 deletions src/basic_memory/picoschema/diff.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
"""Schema diff for Basic Memory.

Compares a schema definition against actual note usage to detect drift.
Drift happens naturally as notes evolve -- new observation categories appear,
Drift happens naturally as notes evolve -- new frontmatter keys and observation
categories appear,
old ones fall out of use, single-value fields become multi-value.

The diff engine reuses inference analysis internally, comparing inferred
Expand All @@ -14,12 +15,13 @@
from dataclasses import dataclass, field

from basic_memory.picoschema.inference import (
NOTE_FRONTMATTER_KEYS,
FieldFrequency,
NoteData,
analyze_observations,
analyze_fields,
analyze_relations,
)
from basic_memory.picoschema.parser import SchemaDefinition
from basic_memory.picoschema.parser import SchemaDefinition, SchemaField


@dataclass
Expand Down Expand Up @@ -54,30 +56,45 @@ def diff_schema(
if total == 0:
return SchemaDrift()

# Keys declared under settings.frontmatter are declared too; they are not new.
schema_field_names = {f.name for f in schema.fields + schema.frontmatter_fields}

# --- Analyze actual usage ---
obs_frequencies = analyze_observations(notes, total, max_sample_values=3)
# Trigger: the schema declares a key every note carries, such as `tags`.
# Why: validation accepts its frontmatter value, so drift must count it too,
# or the field reads as dropped while every note uses it.
# Outcome: only undeclared built-in keys stay out of the analysis.
field_frequencies = analyze_fields(
notes,
total,
max_sample_values=3,
skipped_keys=NOTE_FRONTMATTER_KEYS - schema_field_names,
)
rel_frequencies = analyze_relations(notes, total, max_sample_values=3)

# Build lookup from schema fields
schema_field_names = {f.name for f in schema.fields}

# Build lookup from actual frequencies
obs_freq_by_name = {f.name: f for f in obs_frequencies}
field_freq_by_name = {f.name: f for f in field_frequencies}
rel_freq_by_name = {f.name: f for f in rel_frequencies}
all_freq_by_name = {**obs_freq_by_name, **rel_freq_by_name}

def usage(schema_field: SchemaField) -> FieldFrequency | None:
# An entity-reference field is satisfied only by relations, as in validation;
# a frontmatter key or observation of the same name must not hide its absence.
if schema_field.is_entity_ref:
return rel_freq_by_name.get(schema_field.name)
return field_freq_by_name.get(schema_field.name)

result = SchemaDrift()

# --- Detect new fields ---
# Fields that appear frequently in notes but aren't declared in the schema
for freq in obs_frequencies + rel_frequencies:
for freq in field_frequencies + rel_frequencies:
if freq.name not in schema_field_names and freq.percentage >= new_field_threshold:
result.new_fields.append(freq)
Comment thread
phernandez marked this conversation as resolved.
Resolved

# --- Detect dropped fields ---
# Fields declared in the schema but rarely appearing in actual notes
for schema_field in schema.fields:
freq = all_freq_by_name.get(schema_field.name)
freq = usage(schema_field)
if freq is None:
# Field doesn't appear at all in any note
result.dropped_fields.append(
Expand All @@ -95,7 +112,7 @@ def diff_schema(
# --- Detect cardinality changes ---
# Fields where the schema says single but usage shows array, or vice versa
for schema_field in schema.fields:
freq = all_freq_by_name.get(schema_field.name)
freq = usage(schema_field)
if freq is None:
continue

Expand Down
75 changes: 55 additions & 20 deletions src/basic_memory/picoschema/inference.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
"""Schema inference engine for Basic Memory.

Analyzes notes of a given type and suggests a schema based on observation
and relation frequency. Instead of requiring users to define schemas upfront,
Analyzes notes of a given type and suggests a schema based on how often each
field appears. A field is a frontmatter key, an observation category, or a
relation type. Instead of requiring users to define schemas upfront,
schemas emerge from actual usage patterns:

Write notes freely -> Patterns emerge -> Crystallize into schema
Expand All @@ -25,7 +26,7 @@ class FieldFrequency:
"""Frequency analysis for a single field across notes of a type."""

name: str
source: str # "observation" | "relation"
source: str # "frontmatter" | "observation" | "relation"
count: int # notes containing this field
total: int # total notes analyzed
percentage: float
Expand Down Expand Up @@ -80,6 +81,26 @@ class NoteData:
identifier: str
observations: list[ObservationData]
relations: list[RelationData]
frontmatter: dict[str, Any] = field(default_factory=dict)


# Every note carries these keys, or Basic Memory manages them. They describe the
# note itself, not the fields of its type, so inference and drift skip them.
NOTE_FRONTMATTER_KEYS = frozenset({"title", "type", "permalink", "tags", "schema"})


def frontmatter_values(frontmatter: dict[str, Any]) -> dict[str, list[str]]:
"""Return each frontmatter key's values as strings; a list gives one value per item.

Keys with a null value or an empty list have no values and are left out.
"""
values: dict[str, list[str]] = {}
for key, value in frontmatter.items():
items = value if isinstance(value, list) else [value]
strings = [str(item) for item in items if item is not None]
if strings:
values[key] = strings
return values


# --- Inference Logic ---
Expand All @@ -94,7 +115,8 @@ def infer_schema(
) -> InferenceResult:
"""Analyze notes and suggest a Picoschema definition.

Examines observation categories and relation types across all provided notes.
Examines frontmatter keys, observation categories and relation types across all
provided notes.
Fields that appear in a high percentage of notes become required; those that
appear less frequently become optional.

Expand All @@ -120,14 +142,12 @@ def infer_schema(
excluded=[],
)

# --- Analyze observation frequencies ---
obs_frequencies = analyze_observations(notes, total, max_sample_values)

# --- Analyze relation frequencies ---
# --- Analyze field and relation frequencies ---
field_frequencies = analyze_fields(notes, total, max_sample_values)
rel_frequencies = analyze_relations(notes, total, max_sample_values)

# --- Classify fields by threshold ---
all_frequencies = obs_frequencies + rel_frequencies
all_frequencies = field_frequencies + rel_frequencies
suggested_required: list[str] = []
suggested_optional: list[str] = []
excluded: list[str] = []
Expand Down Expand Up @@ -156,32 +176,46 @@ def infer_schema(
)


# --- Observation Analysis ---
# --- Field Analysis ---


def analyze_observations(
def analyze_fields(
notes: list[NoteData],
total: int,
max_sample_values: int,
skipped_keys: frozenset[str] = NOTE_FRONTMATTER_KEYS,
) -> list[FieldFrequency]:
"""Count observation category frequencies across notes.

A category is counted once per note (presence), not per occurrence.
Array detection: if a category appears multiple times in a single note
in more than half the notes where it appears, it's flagged as an array.
"""Count field frequencies across notes, from frontmatter keys and observation categories.

A field is counted once per note (presence), not per occurrence. Frontmatter
is checked first, as in validation: when a note has the key in frontmatter, its
observations of the same name are not counted again. A field's source is where
most of its notes keep it, frontmatter on a tie.
Array detection: if a field has several values in a single note in more than
half the notes where it appears, it's flagged as an array.
Frontmatter keys in `skipped_keys` are not counted; by default these are the
keys every note carries (title, type, tags, ...), which are not schema fields.
"""
# Count how many notes contain each category (presence per note)
# Count how many notes contain each field (presence per note)
category_note_count: Counter[str] = Counter()
# Count how many notes have multiple occurrences (for array detection)
# Count how many notes have multiple values (for array detection)
category_multi_count: Counter[str] = Counter()
# Count how many notes keep the field in frontmatter (for its source)
frontmatter_note_count: Counter[str] = Counter()
# Collect sample values
category_samples: dict[str, list[str]] = {}

for note in notes:
# Group observations by category within this note
# Group observations by category within this note, then let frontmatter
# keys replace a category of the same name.
note_categories: dict[str, list[str]] = {}
for obs in note.observations:
note_categories.setdefault(obs.category, []).append(obs.content)
for key, values in frontmatter_values(note.frontmatter).items():
if key in skipped_keys:
continue
note_categories[key] = values
frontmatter_note_count[key] += 1

for category, values in note_categories.items():
category_note_count[category] += 1
Expand All @@ -201,11 +235,12 @@ def analyze_observations(
# multiple occurrences, treat it as an array field
multi_count = category_multi_count.get(category, 0)
is_array = multi_count > (count / 2)
from_frontmatter = frontmatter_note_count.get(category, 0) * 2 >= count

frequencies.append(
FieldFrequency(
name=category,
source="observation",
source="frontmatter" if from_frontmatter else "observation",
count=count,
total=total,
percentage=count / total,
Expand Down
Loading
Loading