diff --git a/src/basic_memory/api/v2/routers/schema_router.py b/src/basic_memory/api/v2/routers/schema_router.py index 70084bada..12af39570 100644 --- a/src/basic_memory/api/v2/routers/schema_router.py +++ b/src/basic_memory/api/v2/routers/schema_router.py @@ -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), ) diff --git a/src/basic_memory/man/man3/bm-schema(3).md b/src/basic_memory/man/man3/bm-schema(3).md index 71d2688ee..a083a5b9d 100644 --- a/src/basic_memory/man/man3/bm-schema(3).md +++ b/src/basic_memory/man/man3/bm-schema(3).md @@ -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. @@ -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 diff --git a/src/basic_memory/picoschema/__init__.py b/src/basic_memory/picoschema/__init__.py index c26354940..6b973cd4a 100644 --- a/src/basic_memory/picoschema/__init__.py +++ b/src/basic_memory/picoschema/__init__.py @@ -28,7 +28,7 @@ RelationData, NoteData, infer_schema, - analyze_observations, + analyze_fields, analyze_relations, ) from basic_memory.picoschema.diff import ( @@ -58,7 +58,7 @@ "RelationData", "NoteData", "infer_schema", - "analyze_observations", + "analyze_fields", "analyze_relations", # Diff "SchemaDrift", diff --git a/src/basic_memory/picoschema/diff.py b/src/basic_memory/picoschema/diff.py index 6bbc50adf..e08cede01 100644 --- a/src/basic_memory/picoschema/diff.py +++ b/src/basic_memory/picoschema/diff.py @@ -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 @@ -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 @@ -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) # --- 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( @@ -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 diff --git a/src/basic_memory/picoschema/inference.py b/src/basic_memory/picoschema/inference.py index 9193dcfaa..7d2bf8195 100644 --- a/src/basic_memory/picoschema/inference.py +++ b/src/basic_memory/picoschema/inference.py @@ -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 @@ -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 @@ -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 --- @@ -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. @@ -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] = [] @@ -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 @@ -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, diff --git a/src/basic_memory/picoschema/validator.py b/src/basic_memory/picoschema/validator.py index abf980c81..bf222ceb9 100644 --- a/src/basic_memory/picoschema/validator.py +++ b/src/basic_memory/picoschema/validator.py @@ -1,15 +1,18 @@ """Schema validator for Basic Memory. -Validates a note's observations and relations against a resolved schema definition. -The mapping rules ground schema fields in the existing Basic Memory note format: +Validates a note's frontmatter, observations and relations against a resolved schema +definition. The mapping rules ground schema fields in the existing Basic Memory note format: Schema Declaration -> Grounded In ----------------------------------------------- - field: string -> observation [field] value - field?(array): string -> multiple [field] observations + field: string -> frontmatter key field, else observation [field] value + field?(array): string -> a frontmatter list, else multiple [field] observations field?: EntityType -> relation 'field [[Target]]' field?(array): EntityType -> multiple 'field' relations - field?(enum): [values] -> observation [field] value where value is in set + field?(enum): [values] -> frontmatter or observation value where value is in set + +Frontmatter is checked first: when a note has the key, its observations of the same +name are not consulted. Validation is soft by default (warn mode). Unmatched observations and relations are informational, not errors -- schemas are a subset, not a straitjacket. @@ -18,7 +21,7 @@ from dataclasses import dataclass, field as dataclass_field from typing import Any, assert_never -from basic_memory.picoschema.inference import ObservationData, RelationData +from basic_memory.picoschema.inference import ObservationData, RelationData, frontmatter_values from basic_memory.picoschema.parser import SchemaDefinition, SchemaField, ValidationMode @@ -66,7 +69,8 @@ def validate_note( schema: The resolved SchemaDefinition to validate against. observations: List of ObservationData from the note's observations. relations: List of RelationData from the note's relations. - frontmatter: The note's frontmatter dict for settings.frontmatter validation. + frontmatter: The note's frontmatter dict. Its keys satisfy schema fields before + observations do, and settings.frontmatter rules validate it. Returns: A ValidationResult with per-field results, unmatched items, and warnings/errors. @@ -80,6 +84,7 @@ def validate_note( # Build lookup structures from the note's actual content obs_by_category = _group_observations(observations) rel_by_type = _group_relations(relations) + values_by_key = frontmatter_values(frontmatter) if frontmatter is not None else {} # Track which observation categories and relation types are matched by schema fields matched_categories: set[str] = set() @@ -87,7 +92,7 @@ def validate_note( # --- Validate each schema field --- for schema_field in schema.fields: - field_result = _validate_field(schema_field, obs_by_category, rel_by_type) + field_result = _validate_field(schema_field, values_by_key, obs_by_category, rel_by_type) result.field_results.append(field_result) # Track which categories/relation types this field consumed @@ -145,32 +150,37 @@ def validate_note( def _validate_field( schema_field: SchemaField, + values_by_key: dict[str, list[str]], obs_by_category: dict[str, list[str]], rel_by_type: dict[str, list[str]], ) -> FieldResult: """Validate a single schema field against the note's data. - Entity ref fields map to relations; all other fields map to observations. + Entity ref fields map to relations; all other fields map to a frontmatter key + or, when the note has no such key, to observations. """ # --- Entity reference fields map to relations --- if schema_field.is_entity_ref: return _validate_entity_ref_field(schema_field, rel_by_type) + # Trigger: the note has the field as a frontmatter key. + # Why: scalar facts (counts, dates, owners) live in frontmatter, where + # bm_write(metadata=...) and set_metadata put them (#1973). + # Outcome: the key's values are checked; same-named observations are not. + values = values_by_key.get(schema_field.name) or obs_by_category.get(schema_field.name, []) + # --- Enum fields require value membership check --- if schema_field.is_enum: - return _validate_enum_field(schema_field, obs_by_category) + return _validate_enum_field(schema_field, values) - # --- Scalar and array fields map to observations --- - return _validate_observation_field(schema_field, obs_by_category) + return _validate_value_field(schema_field, values) -def _validate_observation_field( +def _validate_value_field( schema_field: SchemaField, - obs_by_category: dict[str, list[str]], + values: list[str], ) -> FieldResult: - """Validate a field that maps to observation categories.""" - values = obs_by_category.get(schema_field.name, []) - + """Validate a scalar or array field from its frontmatter or observation values.""" if not values: return FieldResult( field=schema_field, @@ -209,11 +219,9 @@ def _validate_entity_ref_field( def _validate_enum_field( schema_field: SchemaField, - obs_by_category: dict[str, list[str]], + values: list[str], ) -> FieldResult: """Validate an enum field -- value must be in the allowed set.""" - values = obs_by_category.get(schema_field.name, []) - if not values: return FieldResult( field=schema_field, @@ -341,4 +349,7 @@ def _missing_field_message(schema_field: SchemaField) -> str: f"(no '{schema_field.name} [[...]]' relation found)" ) - return f"Missing {kind} field: {schema_field.name} (expected [{schema_field.name}] observation)" + return ( + f"Missing {kind} field: {schema_field.name} " + f"(expected {schema_field.name}: in frontmatter or a [{schema_field.name}] observation)" + ) diff --git a/src/basic_memory/schemas/schema.py b/src/basic_memory/schemas/schema.py index ffa865d90..0187c2c9e 100644 --- a/src/basic_memory/schemas/schema.py +++ b/src/basic_memory/schemas/schema.py @@ -77,7 +77,7 @@ class FieldFrequencyResponse(BaseModel): """Frequency analysis for a single field across notes.""" name: str - source: str = Field(description="One of: observation, relation") + source: str = Field(description="One of: frontmatter, observation, relation") count: int = Field(description="Number of notes containing this field") total: int = Field(description="Total notes analyzed") percentage: float diff --git a/tests/api/v2/test_schema_router.py b/tests/api/v2/test_schema_router.py index 32bc532b4..ccc577f99 100644 --- a/tests/api/v2/test_schema_router.py +++ b/tests/api/v2/test_schema_router.py @@ -1575,3 +1575,60 @@ async def test_an_inline_schema_has_no_reference_to_report( assert len(outcomes) == 1 assert outcomes[0].schema_entity == "person" assert outcomes[0].schema_reference is None + + +@pytest.mark.asyncio +async def test_frontmatter_satisfies_schema_fields_in_validate_infer_and_diff( + client: AsyncClient, + test_project: Project, + v2_project_url: str, + entity_service, + search_service, +): + """The #1973 report: `attendees: 4` in frontmatter satisfies `attendees: integer`.""" + schema_entity, _ = await entity_service.create_or_update_entity( + EntitySchema( + title="Meeting Schema", + directory="schemas", + note_type="schema", + entity_metadata={ + "entity": "meeting", + "version": 1, + "schema": {"attendees": "integer, how many attended"}, + }, + content="Schema for meetings.", + ) + ) + await search_service.index_entity(schema_entity) + meeting, _ = await entity_service.create_or_update_entity( + EntitySchema( + title="Standup Monday", + directory="meetings", + note_type="meeting", + entity_metadata={"attendees": 4}, + content=dedent("""\ + ## Observations + - [action] ship the release + """), + ) + ) + await search_service.index_entity(meeting) + + validated = await client.post( + f"{v2_project_url}/schema/validate", params={"note_type": "meeting"} + ) + assert validated.status_code == 200 + [result] = validated.json()["results"] + assert result["warnings"] == [] + assert [(fr["field_name"], fr["status"]) for fr in result["field_results"]] == [ + ("attendees", "present") + ] + + inferred = await client.post(f"{v2_project_url}/schema/infer", params={"note_type": "meeting"}) + assert inferred.status_code == 200 + sources = {freq["name"]: freq["source"] for freq in inferred.json()["field_frequencies"]} + assert sources == {"attendees": "frontmatter", "action": "observation"} + + drift = await client.get(f"{v2_project_url}/schema/diff/meeting") + assert drift.status_code == 200 + assert drift.json()["dropped_fields"] == [] diff --git a/tests/picoschema/test_frontmatter_fields.py b/tests/picoschema/test_frontmatter_fields.py new file mode 100644 index 000000000..aceda0934 --- /dev/null +++ b/tests/picoschema/test_frontmatter_fields.py @@ -0,0 +1,196 @@ +"""Schema fields are satisfied by a frontmatter key or an observation category (#1973). + +Frontmatter is checked first. Inference and drift count frontmatter keys as fields. +""" + +from typing import Any + +from basic_memory.picoschema.diff import diff_schema +from basic_memory.picoschema.inference import ( + NoteData, + ObservationData, + frontmatter_values, + infer_schema, +) +from basic_memory.picoschema.parser import SchemaDefinition, SchemaField +from basic_memory.picoschema.validator import validate_note + +Obs = ObservationData + + +def _schema(*fields: SchemaField) -> SchemaDefinition: + return SchemaDefinition( + entity="meeting", version=1, fields=list(fields), validation_mode="warn" + ) + + +def _note( + identifier: str, + frontmatter: dict[str, Any] | None = None, + observations: list[ObservationData] | None = None, +) -> NoteData: + return NoteData( + identifier=identifier, + observations=observations or [], + relations=[], + frontmatter={"title": identifier, "type": "meeting", **(frontmatter or {})}, + ) + + +ATTENDEES = SchemaField(name="attendees", type="integer", required=True) +STATUS = SchemaField( + name="status", type="enum", required=True, is_enum=True, enum_values=["open", "done"] +) + + +# --- Validation --- + + +def test_a_frontmatter_key_satisfies_a_required_field(): + result = validate_note("standup", _schema(ATTENDEES), [], [], frontmatter={"attendees": 4}) + + assert result.warnings == [] + [field_result] = result.field_results + assert (field_result.status, field_result.values) == ("present", ["4"]) + + +def test_an_observation_still_satisfies_a_field(): + result = validate_note("standup", _schema(ATTENDEES), [Obs("attendees", "4")], [], {}) + + assert result.warnings == [] + assert result.field_results[0].values == ["4"] + + +def test_frontmatter_is_checked_before_observations(): + result = validate_note( + "standup", + _schema(STATUS), + [Obs("status", "blocked")], + [], + frontmatter={"status": "open"}, + ) + + assert result.warnings == [] + assert result.field_results[0].values == ["open"] + # The observation of the same name is the field's, not an unmatched category. + assert result.unmatched_observations == {} + + +def test_enum_checks_apply_to_frontmatter_values(): + result = validate_note("standup", _schema(STATUS), [], [], frontmatter={"status": "blocked"}) + + assert result.field_results[0].status == "enum_mismatch" + assert result.warnings == ["Field 'status' has invalid value(s): blocked (allowed: open, done)"] + + +def test_a_frontmatter_list_gives_one_value_per_item(): + topics = SchemaField(name="topics", type="string", required=True, is_array=True) + + result = validate_note("standup", _schema(topics), [], [], {"topics": ["infra", "hiring"]}) + + assert result.field_results[0].values == ["infra", "hiring"] + + +def test_an_empty_frontmatter_key_falls_back_to_observations(): + result = validate_note( + "standup", _schema(ATTENDEES), [Obs("attendees", "4")], [], {"attendees": []} + ) + + assert result.field_results[0].values == ["4"] + + +def test_a_missing_field_names_both_places_it_can_live(): + result = validate_note("standup", _schema(ATTENDEES), [], [], frontmatter={}) + + assert result.warnings == [ + "Missing required field: attendees " + "(expected attendees: in frontmatter or a [attendees] observation)" + ] + + +def test_frontmatter_values_skip_nulls(): + assert frontmatter_values({"a": None, "b": [None, 2], "c": [], "d": "x"}) == { + "b": ["2"], + "d": ["x"], + } + + +# --- Inference --- + + +def test_infer_counts_frontmatter_keys_and_skips_note_keys(): + notes = [ + _note("monday", {"attendees": 4, "tags": ["standup"]}, [Obs("action", "ship")]), + _note("tuesday", {"attendees": 5}, [Obs("action", "review")]), + ] + + result = infer_schema("meeting", notes) + + by_name = {freq.name: freq for freq in result.field_frequencies} + assert set(by_name) == {"attendees", "action"} + assert by_name["attendees"].source == "frontmatter" + assert by_name["attendees"].sample_values == ["4", "5"] + assert result.suggested_schema == {"attendees": "string", "action": "string"} + + +def test_infer_counts_a_field_once_per_note_from_either_place(): + notes = [ + _note("monday", {"attendees": 4}, [Obs("attendees", "four")]), + _note("tuesday", observations=[Obs("attendees", "5")]), + _note("wednesday", observations=[Obs("attendees", "6")]), + ] + + [freq] = infer_schema("meeting", notes).field_frequencies + + assert (freq.count, freq.is_array) == (3, False) + # Most of its notes keep it as an observation. + assert freq.source == "observation" + assert freq.sample_values == ["4", "5", "6"] + + +# --- Drift --- + + +def test_diff_does_not_drop_a_field_kept_in_frontmatter(): + notes = [_note("monday", {"attendees": 4}), _note("tuesday", {"attendees": 5})] + + drift = diff_schema(_schema(ATTENDEES), notes) + + assert drift.dropped_fields == [] + assert drift.new_fields == [] + + +def test_diff_reports_a_new_frontmatter_key(): + notes = [_note("monday", {"attendees": 4, "room": "A"}), _note("tuesday", {"attendees": 5})] + + drift = diff_schema(_schema(ATTENDEES), notes) + + assert [(freq.name, freq.source) for freq in drift.new_fields] == [("room", "frontmatter")] + + +def test_diff_does_not_let_frontmatter_stand_in_for_a_relation(): + owner = SchemaField(name="owner", type="Person", required=True, is_entity_ref=True) + notes = [_note("monday", {"owner": "Alice"}), _note("tuesday", {"owner": "Bob"})] + + drift = diff_schema(_schema(owner), notes) + + assert [(freq.name, freq.source) for freq in drift.dropped_fields] == [("owner", "relation")] + + +def test_diff_treats_settings_frontmatter_keys_as_declared(): + schema = _schema(ATTENDEES) + schema.frontmatter_fields = [SchemaField(name="status", type="string", required=True)] + notes = [_note("monday", {"attendees": 4, "status": "open"})] + + assert diff_schema(schema, notes).new_fields == [] + + +def test_diff_counts_a_declared_built_in_key(): + tags = SchemaField(name="tags", type="string", required=True, is_array=True) + notes = [_note("monday", {"tags": ["standup", "team"]}), _note("tuesday", {"tags": ["a", "b"]})] + + drift = diff_schema(_schema(tags), notes) + + assert drift.dropped_fields == [] + assert drift.cardinality_changes == [] + assert drift.new_fields == []