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
56 changes: 24 additions & 32 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -3158,8 +3158,14 @@ async def watch_list(x_api_key: str | None = Header(default=None)):

# ── Repair + silent-save ─────────────────────────────────────────────────────

from search_models import SilentSaveBody # noqa: E402


@app.post("/silent-save")
async def silent_save(request: Request, x_api_key: str | None = Header(default=None)):
async def silent_save(
body: SilentSaveBody,
x_api_key: str | None = Header(default=None),
):
"""
Silent Stop-hook save path. Writes a diary checkpoint during normal ops;
during /repair mode=rebuild, queues the payload to a jsonl file and
Expand All @@ -3173,40 +3179,26 @@ async def silent_save(request: Request, x_api_key: str | None = Header(default=N
}
"""
_check_auth(x_api_key)
try:
body = await request.json()
except Exception:
raise HTTPException(status_code=400, detail="invalid JSON")
if not body.get("entry"):
raise HTTPException(status_code=400, detail="'entry' is required")

# mempalace#86 surfaces wing/room validation as warnings on the write
# response, but a missing wing reaches tool_diary_write as "" and may
# not generate a warning at all depending on mempalace version. Detect
# it here so the systemMessage always flags the broken default.
# Don't reject — existing callers may rely on the empty-default — just
# warn so it shows up in the themed chain.
# palace-daemon#179: body fields (entry, wing, topic, agent_name,
# themes, message_count, session_id) already validated +
# wing-canonicalized by SilentSaveBody at parse time.
daemon_warnings: list[str] = []
raw_wing = body.get("wing")
if not raw_wing or (isinstance(raw_wing, str) and not raw_wing.strip()):
if not body.wing:
# Empty wing is allowed (existing callers may rely on the default)
# but warned about in the themed systemMessage so the hook
# surfaces the broken default rather than silently filing under
# no wing.
daemon_warnings.append(
"wing is empty — diary entry will have no wing association"
)

themes = body.get("themes") or []
raw_msg_count = body.get("message_count")
if raw_msg_count is None:
msg_count = 1
else:
try:
msg_count = int(raw_msg_count)
except (TypeError, ValueError):
raise HTTPException(
status_code=400,
detail="'message_count' must be an integer",
)
if msg_count <= 0:
msg_count = 1
themes = body.themes or []
msg_count = body.message_count if body.message_count and body.message_count > 0 else 1

# Build the payload dict for the existing helpers (_enqueue_pending_write,
# _do_silent_save_write) — they predate the model and serialize via
# json for the rebuild queue. body.model_dump() round-trips cleanly.
payload = body.model_dump()

# Acquire write slot, check rebuild flag under lock, then write or queue.
# Queue only when /repair is doing a rebuild — other modes (light/scan/
Expand All @@ -3216,15 +3208,15 @@ async def silent_save(request: Request, x_api_key: str | None = Header(default=N
_repair_state["in_progress"]
and _repair_state.get("mode") == "rebuild"
):
await _enqueue_pending_write(body)
await _enqueue_pending_write(payload)
return _ensure_warnings_fields({
"count": msg_count,
"themes": themes,
"queued": True,
"warnings": daemon_warnings,
"systemMessage": messages.save_queued(msg_count, themes),
})
result = await _do_silent_save_write(body)
result = await _do_silent_save_write(payload)

# mempalace#86: tool_diary_write may return warnings/errors lists.
# Forward them unchanged so clients/hook.py can surface them in the
Expand Down
44 changes: 44 additions & 0 deletions search_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,50 @@ def _validate_fusion_mode(cls, v):
return v


class SilentSaveBody(BaseModel):
"""Body for POST /silent-save (Stop-hook diary checkpoint write).

Differs from POST /memory's body model: empty wing stays as ``""``
rather than coercing to ``"unknown"`` — the handler warns on empty
in the themed systemMessage rather than synthesizing a default. This
preserves the existing behavioral contract that hook clients may
legitimately call /silent-save with no wing (e.g. before a workspace
is assigned).

Topic canonicalization stays in the handler via ``_canonical_topic``
— it's a synonym-rewrite (e.g. "checkpoint" → CHECKPOINT_TOPIC) with
a warning log on rewrite, semantically too involved for a pydantic
validator to handle cleanly.
"""

entry: str = Field(..., min_length=1, description="Diary entry body (required).")
wing: str = Field("", description="Optional wing slug — normalized if set, empty allowed.")
topic: "str | None" = Field(None, description="Optional topic — canonicalized in handler.")
agent_name: str = Field("session-hook", description="Diary author name.")
themes: "list | None" = Field(None, description="Optional theme tags for the systemMessage.")
message_count: "int | None" = Field(None, ge=1, description="Conversation-turn count the hook displays.")
session_id: "str | None" = Field(None, description="Optional session identifier.")

@field_validator("entry")
@classmethod
def _require_entry(cls, v):
v = (v or "").strip()
if not v:
raise ValueError("'entry' is required")
return v

@field_validator("wing")
@classmethod
def _normalize_wing(cls, v):
# /silent-save has WRITE-side wing semantics, not filter semantics —
# we normalize via the write helper (matching /memory POST and #177)
# rather than the filter helper that returns None on empty.
from rooms import normalize_wing_slug
if not v or not v.strip():
return "" # preserve empty so handler can warn
return normalize_wing_slug(v)


class BackfillAgeBody(BaseModel):
"""Body for POST /backfill-age.

Expand Down
9 changes: 6 additions & 3 deletions tests/test_silent_save_validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,14 +116,17 @@ async def _write_with_warnings(payload):
body["warnings"],
)

def test_missing_entry_still_rejected_with_400(self):
def test_missing_entry_still_rejected(self):
# The wing validation is a *warning*; the entry validation is
# still a hard 400. Don't accidentally relax that.
# still a hard rejection. Post-#179 pydantic returns 422 for
# missing-required-field rather than the previous inline 400 —
# the contract that "entry is required" is preserved, just the
# HTTP code surface changed to pydantic's standard.
resp = self.client.post(
"/silent-save",
json={"wing": "diary_selene"},
)
self.assertEqual(resp.status_code, 400)
self.assertEqual(resp.status_code, 422)


if __name__ == "__main__":
Expand Down
Loading