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
15 changes: 15 additions & 0 deletions server/memory/api/models_apply.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

from pydantic import (
BaseModel,
ConfigDict,
Field,
model_validator,
)
Expand All @@ -22,6 +23,8 @@
class ApplyFilter(BaseModel):
"""Predicates over the identity's live rows. All given predicates AND."""

model_config = ConfigDict(extra="forbid")
Comment thread
zlareb1 marked this conversation as resolved.
Resolved

memory_type: str | None = None
tags_any: list[str] = Field(default_factory=list, max_length=50)
tags_all: list[str] = Field(default_factory=list, max_length=50)
Expand Down Expand Up @@ -53,6 +56,8 @@ def _at_least_one(self) -> ApplyFilter:


class ApplySearch(BaseModel):
model_config = ConfigDict(extra="forbid")

query: str = Field(..., min_length=1, max_length=2000)
# the least `similarity` (1 - cosine distance) a hit needs to be acted on
min_score: float | None = Field(default=None, ge=0.0, le=1.0)
Expand All @@ -61,6 +66,8 @@ class ApplySearch(BaseModel):
class ApplyTarget(BaseModel):
"""Exactly one of keys | filter | search."""

model_config = ConfigDict(extra="forbid")

keys: list[str] | None = Field(default=None, min_length=1, max_length=MAX_KEYS)
filter: ApplyFilter | None = None
search: ApplySearch | None = None
Expand All @@ -84,6 +91,8 @@ def kind(self) -> str:


class ApplyExpire(BaseModel):
model_config = ConfigDict(extra="forbid")

ttl_seconds: int | None = Field(default=None, ge=1)
until: datetime | None = None
on_expire: Literal["", "tombstone", "demote", "anonymize"] = ""
Expand All @@ -96,12 +105,16 @@ def _one_of(self) -> ApplyExpire:


class ApplyLock(BaseModel):
model_config = ConfigDict(extra="forbid")

mode: Literal["read_only", "no_delete"] = "read_only"
until: datetime | None = None
ttl_seconds: int | None = Field(default=None, ge=1)


class ApplyLabel(BaseModel):
model_config = ConfigDict(extra="forbid")

tags: list[str] = Field(..., min_length=1, max_length=50)
mode: Literal["add", "replace", "remove"] = "add"

Expand All @@ -110,6 +123,8 @@ class ApplyDemote(BaseModel):
"""Exactly one of `confidence_delta` (added, usually negative) or
`confidence_factor` (multiplied). The result is clamped to [floor, 1]."""

model_config = ConfigDict(extra="forbid")

confidence_delta: float | None = Field(default=None, ge=-1.0, le=1.0)
confidence_factor: float | None = Field(default=None, gt=0.0, le=1.0)
floor: float = Field(default=0.05, ge=0.0, le=1.0)
Expand Down
10 changes: 7 additions & 3 deletions server/transport/arg_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,11 +62,15 @@ def _alias_names(alias: Any) -> list[str]:


@lru_cache(maxsize=2048)
def known_fields(model: type[BaseModel]) -> frozenset[str] | None:
def known_fields(
model: type[BaseModel], *, include_forbidden: bool = False
) -> frozenset[str] | None:
"""Every key `model` reads at the top level — field names and their
aliases — or None when the model keeps extras itself (``extra='allow'``)
or refuses them (``extra='forbid'``), where nothing is silently lost."""
if model.model_config.get("extra") in ("allow", "forbid"):
or refuses them (``extra='forbid'``, unless ``include_forbidden`` is set),
where nothing is silently lost."""
extra = model.model_config.get("extra")
if extra == "allow" or (extra == "forbid" and not include_forbidden):
return None
names: set[str] = set()
for name, info in model.model_fields.items():
Expand Down
113 changes: 86 additions & 27 deletions server/transport/arg_feedback.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,19 @@
from __future__ import annotations

import json
from typing import Any
import types
from typing import Annotated, Any, Union, get_args, get_origin

from pydantic import BaseModel, ValidationError

from server.core.errors import ValidationError as LoomValidationError
from server.transport.arg_check import IDENTITY_KEYS, TRANSPORT_KEYS, did_you_mean, unknown_args
from server.transport.arg_check import (
IDENTITY_KEYS,
TRANSPORT_KEYS,
did_you_mean,
known_fields,
unknown_args,
)

_MAX_ERRORS = 4
_MAX_OPTIONAL = 14
Expand Down Expand Up @@ -48,9 +55,26 @@ def optional_args(model: type[BaseModel]) -> list[str]:
return _args(model, required=False)


def _nested_model(model: type[BaseModel], field: str) -> type[BaseModel] | None:
def _model_from_annotation(ann: Any) -> type[BaseModel] | None:
if isinstance(ann, type) and issubclass(ann, BaseModel):
return ann
origin = get_origin(ann)
if origin is Annotated:
return _model_from_annotation(get_args(ann)[0])
if origin in (Union, types.UnionType):
non_none = [arg for arg in get_args(ann) if arg is not type(None)]
if len(non_none) == 1:
return _model_from_annotation(non_none[0])
return None


def _nested_model(
model: type[BaseModel], field: str, *, unwrap_optional: bool = False
) -> type[BaseModel] | None:
info = model.model_fields.get(field)
ann = getattr(info, "annotation", None)
if unwrap_optional:
return _model_from_annotation(ann)
return ann if isinstance(ann, type) and issubclass(ann, BaseModel) else None


Expand All @@ -65,27 +89,39 @@ def shaped(model: type[BaseModel], field: str) -> str:
return f"{field}{{{'|'.join(inner)}}}" if inner else field


def _unknown_nested_keys(model: type[BaseModel], value: dict[str, Any]) -> list[str]:
known = known_fields(model, include_forbidden=True)
if known is None:
return []
return sorted(k for k in value if isinstance(k, str) and k not in known)


def _walk_guesses(
model: type[BaseModel],
arguments: dict[str, Any],
prefix: str,
out: dict[str, str | None],
seen: frozenset[type[BaseModel]],
) -> None:
keys = unknown_args(model, arguments) if not prefix else _unknown_nested_keys(model, arguments)
near = did_you_mean(model, keys)
out.update({f"{prefix}{k}": (f"{prefix}{near[k]}" if k in near else None) for k in keys})
for field, value in arguments.items():
if not isinstance(field, str) or not isinstance(value, dict):
continue
sub = _nested_model(model, field, unwrap_optional=True)
if sub is None or sub in seen:
continue
_walk_guesses(sub, value, f"{prefix}{field}.", out, seen | {sub})


def guesses(model: type[BaseModel], arguments: Any) -> dict[str, str | None]:
"""`{unknown key path: field it meant or None}` at the top level and one
level into each nested-model argument."""
"""`{unknown key path: field it meant or None}` at the top level and into
each nested-model argument."""
out: dict[str, str | None] = {}
if not isinstance(arguments, dict):
return out
keys = unknown_args(model, arguments)
near = did_you_mean(model, keys)
out.update({k: near.get(k) for k in keys})
for field, value in arguments.items():
sub = _nested_model(model, field) if isinstance(field, str) else None
if sub is None or not isinstance(value, dict):
continue
sub_keys = unknown_args(sub, value)
sub_near = did_you_mean(sub, sub_keys)
out.update(
{
f"{field}.{k}": (f"{field}.{sub_near[k]}" if k in sub_near else None)
for k in sub_keys
}
)
_walk_guesses(model, arguments, "", out, frozenset({model}))
return out


Expand Down Expand Up @@ -122,6 +158,29 @@ def _renamed(
return out


def _rename_nested(
model: type[BaseModel],
value: dict[str, Any],
near: dict[str, str | None],
prefix: str,
seen: frozenset[type[BaseModel]],
) -> dict[str, Any] | None:
renamed = _renamed(value, near, prefix)
if renamed is None:
return None
for field, item in list(renamed.items()):
if not isinstance(field, str) or not isinstance(item, dict):
continue
sub = _nested_model(model, field, unwrap_optional=True)
if sub is None or sub in seen:
continue
child = _rename_nested(sub, item, near, f"{prefix}{field}.", seen | {sub})
if child is None:
return None
renamed[field] = child
return renamed


def example(
model: type[BaseModel],
arguments: dict[str, Any],
Expand All @@ -133,15 +192,15 @@ def example(
skip = IDENTITY_KEYS | TRANSPORT_KEYS
if any(target in skip for target in near.values()):
return None
call = _renamed({k: v for k, v in arguments.items() if k not in skip}, near, "")
call = _rename_nested(
model,
{k: v for k, v in arguments.items() if k not in skip},
near,
"",
frozenset({model}),
)
if call is None:
return None
for field, value in list(call.items()):
if isinstance(value, dict) and _nested_model(model, field) is not None:
renamed = _renamed(value, near, f"{field}.")
if renamed is None:
return None
call[field] = renamed
if fill_missing:
for field in required_args(model):
call.setdefault(field, _placeholder(model, field))
Expand Down
8 changes: 2 additions & 6 deletions server/transport/mcp_descriptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -559,12 +559,8 @@ def revision_policy(update: str) -> str:
"memory.apply": (
"WHAT: One change over many EXISTING memories, previewed first; it "
"never creates one (save facts with memory.set, one per fact). target names "
"exactly one of keys | filter (tags_any/tags_all, memory_type, "
"key_prefix, created_before/after, confidence_lte, source_trace) | "
"search {query}; limit is required for filter/search; action is "
"delete | expire | lock | label | demote with its block (expire "
"{ttl_seconds|until, on_expire}, lock {mode}, label {tags, mode "
"add|replace|remove}, demote {confidence_factor | confidence_delta}); "
"exactly one of keys | filter | search; limit is required for filter/search; "
"action is delete | expire | lock | label | demote with its matching block; "
"reason is required. dry_run defaults to TRUE and lists every row it "
"would touch (would_apply / refused); call again with dry_run=false "
"to write. A locked row comes back as status 'refused', never an "
Expand Down
60 changes: 59 additions & 1 deletion tests/unit/test_arg_feedback.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ def test_memory_apply_names_the_nested_key_and_shows_the_corrected_call() -> Non
"expire": {"ttl_seconds": 60},
},
)
assert "target must name exactly one of keys | filter | search" in msg
assert "target.memory_keys: Extra inputs are not permitted" in msg
assert "'target.memory_keys' — did you mean 'target.keys'?" in msg
assert "required: target, action, reason" in msg and "optional: " in msg
assert data["example"]["target"] == {"keys": ["test/x/a", "test/x/b"]}
Expand Down Expand Up @@ -235,6 +235,64 @@ def test_guesses_skip_a_nested_value_that_is_not_an_object() -> None:
assert guesses(_model("memory.apply"), {"target": "k"}) == {}


def test_deep_nested_misspelling_suggests_and_unknown_key_omits_example() -> None:
msg, data = _fail(
"memory.apply",
{
"target": {"filter": {"key_prefix": "notes/", "tag_any": ["stale"]}},
"action": "expire",
"reason": "Retire stale notes",
"limit": 100,
"expire": {"ttl_seconds": 60},
},
)
assert "target.filter.tag_any: Extra inputs are not permitted" in msg
assert "'target.filter.tag_any' — did you mean 'target.filter.tags_any'?" in msg
assert data["unknown"] == {"target.filter.tag_any": "target.filter.tags_any"}
assert data["example"]["target"]["filter"] == {
"key_prefix": "notes/",
"tags_any": ["stale"],
}

msg_unknown, data_unknown = _fail(
"memory.apply",
{
"target": {"filter": {"key_prefix": "notes/", "pinned": False}},
"action": "expire",
"reason": "Retire stale notes",
"limit": 100,
"expire": {"ttl_seconds": 60},
},
)
assert "target.filter.pinned: Extra inputs are not permitted" in msg_unknown
assert data_unknown["unknown"] == {"target.filter.pinned": None}
assert "example" not in data_unknown

msg_label, data_label = _fail(
"memory.apply",
{
"target": {"keys": ["notes/a"]},
"action": "label",
"reason": "Drop tag",
"label": {"tags": ["keep"], "op": "remove"},
},
)
assert "label.op: Extra inputs are not permitted" in msg_label
assert data_label["unknown"] == {"label.op": None}
assert "example" not in data_label

model = _model("memory.apply")
conflict = {
"target": {"filter": {"tags_any": ["a"], "tag_any": ["b"]}},
"action": "delete",
"reason": "r",
"limit": 10,
}
near = guesses(model, conflict)
assert near == {"target.filter.tag_any": "target.filter.tags_any"}
assert example(model, conflict, near) is None


# ---------------------------------------------------- over the MCP transport


Expand Down
Loading
Loading