diff --git a/app.py b/app.py index 7d8dec7..21ed2ab 100644 --- a/app.py +++ b/app.py @@ -156,6 +156,8 @@ from backend.utils import claim_check from backend.utils import stream_keepalive from backend.utils import detached_stream +from backend.utils import shared_moments +from backend.utils import moment_capture from backend.utils import working_state as working_state_utils from backend.utils import conversation_summary as conversation_summary_utils from backend.utils import code_plan as code_plan_utils @@ -1529,6 +1531,7 @@ def _read_progress_notes(): ) tally(turn_counts, "duration_offered") callback_offered = False + shared_moment = None # a moment from their history with Sonic that this message called up (backend/utils/shared_moments.py) callback_at_lull = False lean_entry = None # A plain conversation turn in a conversation that has working notes (backend/utils/working_state.py): the reply may refer back to what was decided. Not on a tool-agent turn (it had @@ -1708,6 +1711,17 @@ def _read_progress_notes(): proactive_taken=bool(open_loop_entry or headsup_entry or task_results_context or meeting_context or relatable_entry or encouragement_entry or self_history or callback_offered or goal_nudge_context or finding_offer), ) + # A shared moment (backend/utils/shared_moments.py): something real from their history with Sonic that THIS message calls up by a cue, and that they + # approved. It takes the turn's one slot, ahead of a getting-to-know-you question (their own words asked for it). + if not slot["proactive_taken"] and get_db() is not None: + shared_moment = shared_moments.pick( + await asyncio.to_thread(shared_moments.approved_for, get_db(), username), question, chat_sessions[history_key], + now=datetime.now(timezone.utc), closing=is_closing_message(question), **slot, + ) + if shared_moment: + prompt = prompt + shared_moments.build_block(shared_moment) + slot["proactive_taken"] = True + tally(turn_counts, "shared_moment_offered") # A getting-to-know-you question (backend/utils/clarifications.py): takes the turn's one slot, so nothing below stacks with it. clarify_level = clarify_utils.level_of(user_profile) if (clarify_utils.clarify_enabled() and clarify_level != clarify_utils.LESS and not slot["proactive_taken"] and slot["energy_tier"] == "open" @@ -2173,6 +2187,11 @@ def _read_progress_notes(): await asyncio.to_thread(recurring_struggles.note_asked, get_db(), username, step_back_entry["key"]) if low_move: ai_message.additional_kwargs[low_moves.MOVE_MARK] = low_move["kind"] # spaces the same kind of move out (low_moves.MOVE_GAP) + if shared_moment: + ai_message.additional_kwargs[shared_moments.MARK] = True # spaces moments out (shared_moments.GAP_MESSAGES) + if shared_moments.used(full_response, shared_moment): + tally(turn_counts, "shared_moment_used") + spawn_background_task(asyncio.to_thread(shared_moments.note_used, get_db(), username, shared_moment["id"])) # starts its cooldown if checkin_offered and emotion_checkin.asked(full_response): ai_message.additional_kwargs[emotion_checkin.CHECKIN_MARK] = True # spent only when the reply really ended on a question to them: the spacing reads this mark tally(turn_counts, "emotion_checkin_asked") @@ -2324,6 +2343,13 @@ def _read_progress_notes(): spawn_background_task(clarify_utils.capture( username, question, level=clarify_utils.level_of(user_profile), previous_reply=previous_reply, risk_active=risk_level != RISK_NONE, )) + # A new shared moment (backend/utils/moment_capture.py): when their message says something memorable just happened between them and Sonic, one small-model look at the + # exchange may propose a moment for "Our history". Proposed only: they approve it on the Memory page before Sonic ever brings it up. Off the response path; code gates first. + if moment_capture.worth_a_look(question, guest=is_guest_username(username), risk_active=risk_level != RISK_NONE, mood=final_state.get("emotional_state")) \ + and budget_guard.allows("shared moments", budget_state): + spawn_background_task(moment_capture.capture( + username, list(chat_sessions[history_key]), guest=is_guest_username(username), risk_active=risk_level != RISK_NONE, mood=final_state.get("emotional_state"), + )) # Recurring struggles (backend/utils/recurring_struggles.py): an upset message about one of their saved people is counted as part of an episode with that person, dates only, so a # later step-back question can rest on a fact. Counts only for now: nothing Sonic says changes. Off the response path, never for a guest. if not is_guest_username(username) and get_db() is not None and previous_marks.get(recurring_struggles.STEP_BACK_MARK): @@ -2412,6 +2438,32 @@ async def steerable_turn(): }, ) +class SharedMomentStatus(BaseModel): + status: str + + +@app.get("/api/shared-moments") +async def list_shared_moments(current_user = Depends(get_member_user)): + """The person's shared moments (backend/utils/shared_moments.py): what Sonic may bring up from their history together, once approved.""" + rows = await asyncio.to_thread(shared_moments.list_for, get_db(), current_user.get("sub")) + return {"moments": [shared_moments.public(m) for m in rows if m.get("status") != shared_moments.DISMISSED]} + + +@app.post("/api/shared-moments/{moment_id}/status") +async def set_shared_moment_status(moment_id: str, request: SharedMomentStatus, current_user = Depends(get_member_user)): + """Approves or dismisses one of the person's own moments.""" + if not await asyncio.to_thread(shared_moments.set_status, get_db(), current_user.get("sub"), moment_id, request.status): + raise HTTPException(status_code=404, detail="No such moment.") + return {"ok": True} + + +@app.delete("/api/shared-moments/{moment_id}") +async def delete_shared_moment(moment_id: str, current_user = Depends(get_member_user)): + if not await asyncio.to_thread(shared_moments.delete, get_db(), current_user.get("sub"), moment_id): + raise HTTPException(status_code=404, detail="No such moment.") + return {"ok": True} + + class StopRequest(BaseModel): session_id: str diff --git a/backend/components/constraints.py b/backend/components/constraints.py index 9f061ca..74b620a 100644 --- a/backend/components/constraints.py +++ b/backend/components/constraints.py @@ -629,6 +629,27 @@ def build_voice_prompt( }} """ +# Shared moments, noticed as they happen (backend/utils/moment_capture.py): one moment from the last few messages, or nothing. Code checks what comes back (grounded, cues present, +# nothing sensitive) and the person approves it before Sonic ever uses it. +MOMENT_CAPTURE_PROMPT = """You keep a short list of real moments from a person's history with their assistant, Sonic: things Sonic may fondly bring up later, the way a friend +does ("the day we finally got the budget fix merged"). + +THE LAST FEW MESSAGES (oldest first; "Person" is them, "Sonic" is the assistant): +{exchange} + +Is there ONE moment here worth remembering together? It must be what the Person's LAST message is reacting to, and something that happened between the two of them: a win +or milestone, a funny or memorable line, a mistake Sonic made that they called out, something they built or finished together. Not a passing remark, not a plan for later, nothing +painful or private (health, grief, a relationship ending, money trouble, drinking or drugs, anything about hurting themselves). If the last message is about something else +(their evening, a concert, a show), or only hopes something works, the answer is null. + +Keep it as it was for them. If they were frustrated with Sonic, the moment is that ("the day you told me I'd spent fifty cents on two asks I couldn't finish"), never a softened +or happier version. Use their own words where you can. + +Reply with ONLY a JSON object: +{{"moment": "one line in Sonic's voice, starting with 'the day', 'the time', 'the night' or 'your', under 160 characters, using only what the messages say", "cues": ["2 to 4 words or short phrases copied from the messages that would make it relevant again"]}} +or {{"moment": null}} when there is none. Most of the time there is none. +""" + CLARIFY_EXTRACTION_PROMPT = """ You read ONE message from a user to a friendly assistant and decide whether it introduces a specific thing in THEIR own life that the assistant knows nothing about yet and would understand much better after one short question about how it fits in their life: a project they work on, an organization or team they belong to or diff --git a/backend/components/sonic_changelog.py b/backend/components/sonic_changelog.py index 13b8a4b..211090e 100644 --- a/backend/components/sonic_changelog.py +++ b/backend/components/sonic_changelog.py @@ -1787,6 +1787,21 @@ "keywords": ["how have you been", "your week", "how are you doing lately"], "volunteer": [], }, + { + "id": "our_history", + "requires": [ + "backend/utils/shared_moments.py::def pick", + "app.py::shared_moments.build_block", + "backend/utils/moment_capture.py::def capture", + ], + "month": "2026-11", + "title": "Our history", + "line": ( + "I can now bring up moments from our own history together when something you say calls one up, and I notice new ones as they happen, but I only use the ones you approve under Our history on the Memory page." + ), + "keywords": ["our history", "shared moments", "remember when", "inside joke", "callback to"], + "volunteer": [], + }, { "id": "replies_survive_leaving", "requires": [ diff --git a/backend/tests/test_memory_erase.py b/backend/tests/test_memory_erase.py index d92222b..a9c0ee8 100644 --- a/backend/tests/test_memory_erase.py +++ b/backend/tests/test_memory_erase.py @@ -52,7 +52,7 @@ def facts(monkeypatch): def test_every_place_memory_is_kept_is_on_the_list_and_the_names_match_the_ones_the_app_writes_to(): - assert set(me.ERASED_COLLECTIONS) == {"user_memory_chunks", "user_memory_chunk_archive", "user_memory_fact_archive", "memory_compaction_events", "user_memory_domain_backups", "user_recurring_struggles"} + assert set(me.ERASED_COLLECTIONS) == {"user_memory_chunks", "user_memory_chunk_archive", "user_memory_fact_archive", "memory_compaction_events", "user_memory_domain_backups", "user_recurring_struggles", "shared_moments"} assert ms.USER_MEMORY_COLLECTION in me.ERASED_COLLECTIONS assert mc.ARCHIVE_COLLECTION == ms.CHUNK_ARCHIVE_COLLECTION == mm.ARCHIVE_COLLECTION assert memory_utils.FACT_ARCHIVE_COLLECTION in me.ERASED_COLLECTIONS diff --git a/backend/tests/test_moment_capture.py b/backend/tests/test_moment_capture.py new file mode 100644 index 0000000..d9b6a35 --- /dev/null +++ b/backend/tests/test_moment_capture.py @@ -0,0 +1,187 @@ +"""New shared moments noticed as they happen (backend/utils/moment_capture.py): a signal earns one small-model look, code refuses anything ungrounded or sensitive, and what +survives is only PROPOSED. A fake model and a fake database; the signal messages are Jack's real shapes (2026-11-25 measurement).""" +import asyncio +import pathlib +from datetime import datetime, timezone + +import pytest +from langchain_core.messages import AIMessage, HumanMessage + +from backend.tests.fake_runner_db import FakeDB +from backend.utils import moment_capture as mc, self_counters, shared_moments as sm + +ROOT = pathlib.Path(__file__).resolve().parents[2] +NOW = datetime.now(timezone.utc) +TODAY = NOW.date().isoformat() +CALM = {"read_this_turn": True, "valence": "positive"} + +EXCHANGE = [ + HumanMessage(content="can you finish the budget banner fix"), + AIMessage(content="Applied: the admin button now shows at the 80% notice line, and the tests pass."), + HumanMessage(content="We did it! the budget banner finally works"), +] + + +@pytest.fixture(autouse=True) +def _fresh(): + mc.forget_calls() + yield + mc.forget_calls() + + +@pytest.mark.parametrize("message, signal", [ + ("We did it!", "milestone"), + ("yep it looks like it worked, thanks saapp", "milestone"), + ("50 cents for two asks you couldnt even complete", "verdict"), + ("seriously you forgot all of it?", "verdict"), + ("do you remember when we built the trace panel", "shared_past"), + ("can you rename this function", None), +]) +def test_signals_come_from_real_shapes(message, signal): + assert mc.signal_of(message) == signal + + +@pytest.mark.parametrize("kwargs, ok", [ + ({"guest": False, "risk_active": False, "mood": CALM}, True), + ({"guest": False, "risk_active": False, "mood": None}, True), + ({"guest": True, "risk_active": False, "mood": CALM}, False), + ({"guest": False, "risk_active": True, "mood": CALM}, False), + ({"guest": False, "risk_active": False, "mood": {"read_this_turn": True, "valence": "distressed"}}, False), + ({"guest": False, "risk_active": False, "mood": {"read_this_turn": True, "valence": "low"}}, False), +]) +def test_a_signal_earns_a_look_only_for_a_member_outside_a_safety_context_and_a_hard_mood(kwargs, ok): + assert mc.worth_a_look("We did it!", **kwargs) is ok + assert mc.worth_a_look("ok thanks", guest=False, risk_active=False, mood=CALM) is False + + +def test_the_exchange_is_the_last_messages_as_person_and_sonic(): + text = mc.exchange_text(EXCHANGE) + assert text.splitlines()[0].startswith("Person: can you finish") and text.splitlines()[1].startswith("Sonic: Applied:") + assert len(mc.exchange_text([HumanMessage(content=str(i)) for i in range(20)]).splitlines()) == mc.MAX_MESSAGES + + +@pytest.mark.parametrize("reply, parsed", [ + ('{"moment": "the day we finally got the budget banner working", "cues": ["budget banner"]}', {"moment": "the day we finally got the budget banner working", "cues": ["budget banner"]}), + ('Sure! {"moment": null}', None), ("no json here", None), ('{"moment": " "}', None), ('{"moment": "x", "cues": "nope"}', {"moment": "x", "cues": []}), +]) +def test_the_reply_is_read_as_a_moment_or_nothing(reply, parsed): + assert mc.parse(reply) == parsed + + +def test_a_grounded_moment_keeps_only_cues_that_appear_and_is_dated_today(): + moment = mc.validate({"moment": "the day we finally got the budget banner working", "cues": ["budget banner", "rocket launch"]}, EXCHANGE, TODAY) + assert moment == {"text": "the day we finally got the budget banner working", "when": TODAY, "cues": ["budget banner"]} + + +@pytest.mark.parametrize("found", [ + {"moment": "the day we got the budget banner working after 7 tries", "cues": ["budget banner"]}, # a number nobody said + {"moment": "the day Priya and you got the budget banner working", "cues": ["budget banner"]}, # a name nobody said + {"moment": "the day we finally got the budget banner working", "cues": ["rocket launch"]}, # no cue in the messages + {"moment": "the night we talked about your therapy and the budget banner", "cues": ["budget banner"]}, # sensitive +]) +def test_anything_ungrounded_cueless_or_sensitive_is_refused(found): + assert mc.validate(found, EXCHANGE, TODAY) is None + + +def test_a_substance_joke_is_never_kept(): + messages = [HumanMessage(content="do you remember when we got you high lol")] + assert mc.validate({"moment": "the time you joked about getting me high", "cues": ["remember"]}, messages, TODAY) is None + + +def _capture(db, model_reply, messages=EXCHANGE, **overrides): + calls, counted = [], [] + + async def invoke(prompt): + calls.append(prompt) + return model_reply + + kwargs = dict(guest=False, risk_active=False, mood=CALM, invoke=invoke, get_db_fn=lambda: db, record=counted.append, now=NOW) + kwargs.update(overrides) + result = asyncio.run(mc.capture("jack", messages, **kwargs)) + return result, calls, counted + + +def test_a_real_moment_is_proposed_never_approved_and_counted(): + db = FakeDB() + ok, calls, counted = _capture(db, '{"moment": "the day we finally got the budget banner working", "cues": ["budget banner"]}') + assert ok and len(calls) == 1 and "Person: We did it! the budget banner finally works" in calls[0] + [stored] = sm.list_for(db, "jack") + assert stored["status"] == sm.PROPOSED and stored["source"] == "captured" and stored["when"] == TODAY + assert counted == [{"moment_capture_asked": 1, "moment_capture_proposed": 1}] + + +def test_nothing_found_or_a_refused_moment_stores_nothing_and_says_which(): + db = FakeDB() + assert _capture(db, '{"moment": null}')[2] == [{"moment_capture_asked": 1}] + mc.forget_calls() + assert _capture(db, '{"moment": "the day we got it working after 7 tries", "cues": ["budget banner"]}')[2] == [{"moment_capture_asked": 1, "moment_capture_refused": 1}] + assert sm.list_for(db, "jack") == [] + + +def test_one_look_every_few_hours_and_none_while_enough_moments_wait(): + db = FakeDB() + first = _capture(db, '{"moment": null}') + second = _capture(db, '{"moment": null}') + assert len(first[1]) == 1 and second[1] == [] # the second signal inside CALL_GAP_HOURS: no call + mc.forget_calls() + for i in range(mc.MAX_WAITING): + sm.propose(db, "jack", {"text": f"waiting moment number {i}", "when": TODAY, "cues": ["cue"]}, now=NOW) + assert _capture(db, '{"moment": "the day we finally got the budget banner working", "cues": ["budget banner"]}')[1] == [] + + +def test_no_call_without_a_signal_for_a_guest_or_without_a_database(): + plain = [HumanMessage(content="can you rename this function")] + assert _capture(FakeDB(), "{}", plain)[1] == [] + assert _capture(FakeDB(), "{}", guest=True)[1] == [] + assert _capture(None, "{}")[0] is False + + +def test_a_failing_model_never_raises(): + async def boom(prompt): + raise RuntimeError("down") + + assert asyncio.run(mc.capture("jack", EXCHANGE, guest=False, risk_active=False, mood=CALM, invoke=boom, get_db_fn=FakeDB, record=lambda c: None)) is False + + +def test_wired_after_the_turn_behind_the_cheap_gates_and_the_budget(): + source = (ROOT / "app.py").read_text(encoding="utf-8") + gate = source.index("if moment_capture.worth_a_look(question, guest=is_guest_username(username), risk_active=risk_level != RISK_NONE, mood=final_state.get(\"emotional_state\"))") + assert 'budget_guard.allows("shared moments", budget_state)' in source[gate: gate + 300] + assert "spawn_background_task(moment_capture.capture(" in source[gate: gate + 500] + for key in ("moment_capture_asked", "moment_capture_proposed", "moment_capture_refused"): + assert key in self_counters.KEYS + + +def test_nothing_of_a_moment_is_logged(): + source = (ROOT / "backend" / "utils" / "moment_capture.py").read_text(encoding="utf-8") + for line in [l for l in source.splitlines() if "logger." in l]: + assert "%s" not in line and "{" not in line, line + + +def _history(common_word_share): + """A conversation of 200 of the person's messages where 'worked' is in the given share of them, 'kms' in one.""" + messages = [] + for i in range(200): + text = "it worked again" if i < int(200 * common_word_share) else "something else entirely" + messages.append(HumanMessage(content=text if i != 7 else "the kms error")) + return messages + + +def test_a_cue_must_have_a_word_that_is_rare_in_what_the_person_writes(): + history = _history(0.3) + assert mc.specific_cues(["it worked", "kms error", "worked again"], history) == ["kms error"] # "worked" and "again" are both in 30% of their messages + assert mc.specific_cues(["it worked"], history[:50]) == ["it worked"] # too few messages to judge: every cue stays + + +def test_a_moment_whose_cues_are_all_common_is_not_kept(): + history = _history(0.3) + [AIMessage(content="It worked: the kms error is gone."), HumanMessage(content="We did it! it worked")] + assert mc.validate({"moment": "the day we got rid of the kms error", "cues": ["it worked"]}, history, TODAY) is None + kept = mc.validate({"moment": "the day we got rid of the kms error", "cues": ["it worked", "kms error"]}, history, TODAY) + assert kept is not None and kept["cues"] == ["kms error"] + + +def test_the_prompt_keeps_the_persons_framing_and_says_null_when_the_last_message_is_about_something_else(): + from backend.components.constraints import MOMENT_CAPTURE_PROMPT + + assert "never a softened" in MOMENT_CAPTURE_PROMPT and "what the Person's LAST message is reacting to" in MOMENT_CAPTURE_PROMPT + assert "the answer is null" in MOMENT_CAPTURE_PROMPT diff --git a/backend/tests/test_shared_moments.py b/backend/tests/test_shared_moments.py new file mode 100644 index 0000000..c5675b3 --- /dev/null +++ b/backend/tests/test_shared_moments.py @@ -0,0 +1,160 @@ +"""Shared moments (backend/utils/shared_moments.py): real moments from a person's history with Sonic, used only once they approved them, chosen by code when their message +names a cue, at most once in a while. No model; a fake database.""" +import pathlib +from datetime import date, datetime, timedelta, timezone +from types import SimpleNamespace + +import pytest + +from backend.tests.fake_runner_db import FakeDB +from backend.utils import memory_erase, self_counters, shared_moments as sm + +ROOT = pathlib.Path(__file__).resolve().parents[2] +NOW = datetime.now(timezone.utc) +TODAY = NOW.date() +PAST = (TODAY - timedelta(days=30)).isoformat() + + +def _moment(text="the night the plan loop cost fifty cents for two asks", cues=("cost", "cents", "budget"), status=sm.APPROVED, last_used=None, **extra): + return {"id": text[:10], "text": text, "when": PAST, "cues": list(cues), "status": status, "last_used_at": last_used, **extra} + + +GATES = dict(source_type="conversational", risk_active=False, closing=False, energy_tier="open", proactive_taken=False) + + +def _pick(moments, message, recent=(), **overrides): + return sm.pick(moments, message, list(recent), now=NOW, **{**GATES, **overrides}) + + +# ---- what a moment must be ---- + +def test_a_clean_moment_has_one_line_a_real_past_day_and_cues(): + cleaned, errors = sm.clean({"text": " your four-round onsite at Casey's ", "when": PAST, "cues": ["Onsite", "onsite", "Casey's", "ab"]}, TODAY) + assert errors == [] and cleaned == {"text": "your four-round onsite at Casey's", "when": PAST, "cues": ["onsite", "casey's"]} + + +@pytest.mark.parametrize("raw, fragment", [ + ({"text": "short", "when": PAST, "cues": ["x x"]}, "text:"), + ({"text": "a long enough line", "when": "yesterday", "cues": ["cue"]}, "when: a real date"), + ({"text": "a long enough line", "when": (TODAY + timedelta(days=2)).isoformat(), "cues": ["cue"]}, "has not happened yet"), + ({"text": "a long enough line", "when": PAST, "cues": ["ab", ""]}, "cues:"), + (None, "text:"), +]) +def test_a_moment_without_a_real_line_day_or_cue_is_refused(raw, fragment): + cleaned, errors = sm.clean(raw, TODAY) + assert cleaned is None and any(fragment in e for e in errors) + + +# ---- when one is used ---- + +def test_a_cue_in_the_message_calls_up_an_approved_moment_as_a_whole_word_any_case(): + moment = _moment() + assert _pick([moment], "that run COST way too much") is moment + assert _pick([moment], "the costume party was fun") is None # not part of a longer word + assert sm.mentions("how did caseys go", "casey's") and sm.mentions("how did Casey’s go", "casey's") + + +def test_only_an_approved_moment_is_ever_used(): + assert _pick([_moment(status=sm.PROPOSED)], "it cost a lot") is None + assert _pick([_moment(status=sm.DISMISSED)], "it cost a lot") is None + + +@pytest.mark.parametrize("overrides", [ + {"source_type": "tool_output"}, {"risk_active": True}, {"closing": True}, {"energy_tier": "subdued"}, {"proactive_taken": True}, +]) +def test_no_moment_off_a_plain_conversation_in_a_hard_moment_a_closing_or_beside_another_item(overrides): + assert _pick([_moment()], "it cost a lot", **overrides) is None + + +def test_moments_are_spaced_out_and_one_used_recently_rests(): + marked = SimpleNamespace(additional_kwargs={sm.MARK: True}) + plain = SimpleNamespace(additional_kwargs={}) + assert _pick([_moment()], "it cost a lot", [marked] + [plain] * (sm.GAP_MESSAGES - 1)) is None + assert _pick([_moment()], "it cost a lot", [marked] + [plain] * sm.GAP_MESSAGES) is not None + rested = (NOW - timedelta(days=sm.COOLDOWN_DAYS + 1)).isoformat() + fresh = (NOW - timedelta(days=sm.COOLDOWN_DAYS - 1)).isoformat() + assert _pick([_moment(last_used=fresh)], "it cost a lot") is None + assert _pick([_moment(last_used=rested)], "it cost a lot") is not None + + +def test_the_moment_naming_most_cues_wins_then_the_one_used_longest_ago(): + one = _moment("the browser migration in plan mode", cues=("plan", "migration")) + two = _moment("the night the plan loop cost fifty cents", cues=("plan", "cost")) + assert _pick([one, two], "the plan cost a lot") is two + older = _moment("first", cues=("plan",), last_used=(NOW - timedelta(days=90)).isoformat()) + newer = _moment("second", cues=("plan",), last_used=(NOW - timedelta(days=20)).isoformat()) + never = _moment("third", cues=("plan",)) + assert _pick([newer, older], "about the plan") is older + assert _pick([newer, never, older], "about the plan") is never + + +def test_the_block_names_the_moment_and_its_day_and_says_how_lightly_to_use_it(): + block = sm.build_block({**_moment(), "when": "2026-10-31"}) + assert "the night the plan loop cost fifty cents for two asks (Oct 31, 2026)" in block + assert "one light clause" in block and "If it does not fit, leave it out" in block and "do not add details" in block + assert sm.build_block(None) == "" + + +def test_a_reply_used_it_when_it_shares_two_words_with_it_or_names_a_cue(): + moment = _moment() + assert sm.used("Not another fifty cents night, I promise.", moment) + assert sm.used("Keep an eye on the budget.", moment) + assert not sm.used("Sure, here is the plan.", moment) and not sm.used("", moment) and not sm.used("x", None) + + +# ---- storage ---- + +def test_a_proposed_moment_is_stored_once_and_only_its_owner_can_approve_dismiss_or_remove_it(): + db = FakeDB() + moment, errors = sm.propose(db, "jack", {"text": "your four-round onsite at Casey's", "when": PAST, "cues": ["onsite"]}, now=NOW) + assert errors == [] and moment["status"] == sm.PROPOSED and moment["uses"] == 0 + assert sm.propose(db, "jack", {"text": "Your four-round onsite at Casey's", "when": PAST, "cues": ["x y z"]}, now=NOW) == (None, ["this moment is already there"]) + assert sm.approved_for(db, "jack") == [] + assert not sm.set_status(db, "someone_else", moment["id"], sm.APPROVED) + assert not sm.set_status(db, "jack", moment["id"], "whatever") + assert sm.set_status(db, "jack", moment["id"], sm.APPROVED) and [m["id"] for m in sm.approved_for(db, "jack")] == [moment["id"]] + sm.note_used(db, "jack", moment["id"], NOW) + stored = sm.list_for(db, "jack")[0] + assert stored["uses"] == 1 and stored["last_used_at"] == NOW.isoformat() + assert not sm.delete(db, "someone_else", moment["id"]) and sm.delete(db, "jack", moment["id"]) and sm.list_for(db, "jack") == [] + + +def test_a_person_has_a_limit_and_a_moment_with_problems_is_not_stored(): + db = FakeDB() + for i in range(sm.MAX_PER_PERSON): + assert sm.propose(db, "jack", {"text": f"moment number {i} here", "when": PAST, "cues": ["cue"]}, now=NOW)[0] + assert sm.propose(db, "jack", {"text": "one moment too many", "when": PAST, "cues": ["cue"]}, now=NOW)[0] is None + assert sm.propose(FakeDB(), "jack", {"text": "x", "when": PAST}, now=NOW)[0] is None + + +def test_the_page_sees_only_what_it_needs_and_forget_everything_removes_moments(): + assert set(sm.public(_moment(username="jack", created_at="x"))) == {"id", "text", "when", "cues", "status", "source", "uses", "last_used_at"} + assert sm.COLLECTION in memory_erase.ERASED_COLLECTIONS + + +# ---- the wiring ---- + +def test_the_reply_offers_a_moment_in_the_one_slot_marks_it_and_counts_it(): + source = (ROOT / "app.py").read_text(encoding="utf-8") + pick = source.index("shared_moment = shared_moments.pick(") + assert source.rfind('if not slot["proactive_taken"] and get_db() is not None:', 0, pick) > source.rfind("slot = dict(", 0, pick) + assert pick < source.index("clarify_level = clarify_utils.level_of(user_profile)") # ahead of a getting-to-know-you question + block = source[pick: pick + 700] + assert "prompt = prompt + shared_moments.build_block(shared_moment)" in block and 'slot["proactive_taken"] = True' in block + assert 'ai_message.additional_kwargs[shared_moments.MARK] = True' in source + assert "if shared_moments.used(full_response, shared_moment):" in source and "shared_moments.note_used, get_db(), username, shared_moment[\"id\"]" in source + for key in ("shared_moment_offered", "shared_moment_used"): + assert key in self_counters.KEYS and f'"{key}"' in source + + +def test_the_endpoints_are_for_members_only(): + source = (ROOT / "app.py").read_text(encoding="utf-8") + for route in ('@app.get("/api/shared-moments")', '@app.post("/api/shared-moments/{moment_id}/status")', '@app.delete("/api/shared-moments/{moment_id}")'): + start = source.index(route) + assert "Depends(get_member_user)" in source[start: start + 300], route + + +def test_a_moment_offered_twenty_messages_ago_still_holds_the_next_one_back(): + marked = SimpleNamespace(additional_kwargs={sm.MARK: True}) + plain = SimpleNamespace(additional_kwargs={}) + assert _pick([_moment()], "it cost a lot", [marked] + [plain] * 20) is None # a literal: the gap itself is pinned diff --git a/backend/utils/memory_erase.py b/backend/utils/memory_erase.py index 7d4ad54..769129b 100644 --- a/backend/utils/memory_erase.py +++ b/backend/utils/memory_erase.py @@ -10,6 +10,7 @@ - the compaction log (`memory_compaction_events`: counts and timestamps for this user) - the backups of facts that sorting them by part of life (memory_domains.py) kept so it can be undone (`user_memory_domain_backups`) - the dates of the times they came to Sonic upset about one of their people (`user_recurring_struggles`, backend/utils/recurring_struggles.py) +- the moments from their history with Sonic it may bring up (`shared_moments`, backend/utils/shared_moments.py) Upcoming-item reminders (open loops) are forgotten by their own module, called next to this by the endpoint. Not touched, on purpose: the user's conversations (deleted from the chat list) and the feedback they rated. @@ -22,12 +23,13 @@ from backend.utils.memory_domains import BACKUP_COLLECTION as DOMAIN_BACKUP_COLLECTION from backend.utils.memory_utils import FACT_ARCHIVE_COLLECTION, delete_all_user_facts, load_user_facts from backend.utils.recurring_struggles import COLLECTION as STRUGGLES_COLLECTION +from backend.utils.shared_moments import COLLECTION as MOMENTS_COLLECTION logger = logging.getLogger("SASS Logger") COMPACTION_EVENTS_COLLECTION = "memory_compaction_events" # Every collection erased by username, in the order they are emptied: the live notes first, then the copies kept of them. -ERASED_COLLECTIONS = (USER_MEMORY_COLLECTION, CHUNK_ARCHIVE_COLLECTION, FACT_ARCHIVE_COLLECTION, COMPACTION_EVENTS_COLLECTION, DOMAIN_BACKUP_COLLECTION, STRUGGLES_COLLECTION) +ERASED_COLLECTIONS = (USER_MEMORY_COLLECTION, CHUNK_ARCHIVE_COLLECTION, FACT_ARCHIVE_COLLECTION, COMPACTION_EVENTS_COLLECTION, DOMAIN_BACKUP_COLLECTION, STRUGGLES_COLLECTION, MOMENTS_COLLECTION) def stored_counts(db: Any, username: str) -> Dict[str, int]: diff --git a/backend/utils/memory_maintenance.py b/backend/utils/memory_maintenance.py index 48afdf1..dc98c04 100644 --- a/backend/utils/memory_maintenance.py +++ b/backend/utils/memory_maintenance.py @@ -7,6 +7,7 @@ python -m backend.utils.memory_maintenance restore-pruned-facts --username U [--source explicit] [--show] [--apply] # bring back pruned facts python -m backend.utils.memory_maintenance fix-facts --username U --changes FILE --run ID [--apply] # approved rewrites/removals of facts, notes flagged stale (backend/utils/fact_cleanup.py) python -m backend.utils.memory_maintenance restore-fact-fixes --username U --run ID [--apply] # undo a fix-facts run + python -m backend.utils.memory_maintenance propose-moments --username U --file FILE [--apply] # shared moments, PROPOSED for the person to approve (backend/utils/shared_moments.py) python -m backend.utils.memory_maintenance reembed-missing --username U [--apply] # embed facts that have no embedding (never found by relevance) strip-labels: until the label fix, about a third of the saved notes begin with the model's "SUMMARY:" (it copied the last word of @@ -190,6 +191,10 @@ def main(argv: Optional[List[str]] = None) -> int: unfix.add_argument("--username", required=True) unfix.add_argument("--run", required=True) unfix.add_argument("--apply", action="store_true", help="actually restore (default: only count)") + moments = sub.add_parser("propose-moments", help="add moments from the person's history with Sonic, as PROPOSED: nothing is used until they approve each one on the Memory page") + moments.add_argument("--username", required=True) + moments.add_argument("--file", required=True, help='a JSON list of {"text", "when": "YYYY-MM-DD", "cues": [...]}') + moments.add_argument("--apply", action="store_true", help="actually add them (default: only check them)") reembed = sub.add_parser("reembed-missing", help="embed the facts that have no embedding, so recall can find them by relevance") reembed.add_argument("--username", required=True) reembed.add_argument("--apply", action="store_true", help="actually embed and save (default: only count)") @@ -217,6 +222,8 @@ def main(argv: Optional[List[str]] = None) -> int: return _restore_domains_command(db, args.username, args.run, args.apply) if args.command == "fix-facts": return _fix_facts_command(db, args.username, args.changes, args.run, args.apply, embed_text) + if args.command == "propose-moments": + return _propose_moments_command(db, args.username, args.file, args.apply) if args.command == "reembed-missing": from backend.utils import memory_utils @@ -394,6 +401,23 @@ def _restore_command(db: Any, run: str, apply: bool) -> int: return 0 +def _propose_moments_command(db: Any, username: str, path: str, apply: bool) -> int: + import json + + from backend.utils import shared_moments + + with open(path, encoding="utf-8") as handle: + items = json.load(handle) + problems = {i: shared_moments.clean(item)[1] for i, item in enumerate(items) if shared_moments.clean(item)[1]} + print(f"{len(items)} moment(s); {len(problems)} with problems: {problems}") + if not apply or problems: + print("Nothing added." + ("" if problems else " Add --apply to add them as proposed.")) + return 0 if not problems else 2 + added = sum(1 for item in items if shared_moments.propose(db, username, item, source="seed")[0] is not None) + print(f"added {added} as proposed (already there or over the limit: {len(items) - added}). The person approves them on the Memory page, under Our history.") + return 0 + + def reembed_missing(username: str, *, load: Callable, save: Callable, embed: Callable) -> Dict[str, int]: """Gives every fact with no embedding one (2026-11-23: 10 of 887 had none, so recall could never find them by relevance). Text, dates and everything else stay as they were. One save at the end, only when something was embedded. {"embedded", "failed"}.""" diff --git a/backend/utils/moment_capture.py b/backend/utils/moment_capture.py new file mode 100644 index 0000000..761a827 --- /dev/null +++ b/backend/utils/moment_capture.py @@ -0,0 +1,185 @@ +"""New shared moments, noticed as they happen (stage 2 of backend/utils/shared_moments.py, 2026-11-25). + +WHEN. After a turn, and only when the person's message carries a signal that something memorable just happened between them and Sonic (SIGNALS: a shared past, a milestone, +a verdict on Sonic). Measured on Jack's own month (2026-10-25 to 11-25): 17 messages matched, a median of one a day, at most three, and they were the real thing ("We did it!", +"50 cents for two asks you couldnt even complete", "seriously you forgot all of it?") plus some that were not ("it works for me most of the times"). So a signal only earns a +look: never under a safety plan, never for a guest, never when they are low or distressed (a hard moment is not something to bring up fondly), at most once every +CALL_GAP_HOURS per person, and only while fewer than MAX_WAITING moments wait for their OK. + +WHAT. One small-model call reads the last few messages and returns one moment in Sonic's voice with cues, or nothing (the usual answer). Code then refuses anything that is +not grounded: the line may not carry a number, time or name the messages do not (backend/utils/memory_grounding.py), every cue must appear in the messages, and nothing +sensitive (backend/utils/interest_anchor.py). The day is today, set by code, never by the model. What survives is stored PROPOSED: the person approves it on the Memory page +before Sonic ever uses it. Counts only, no content, are recorded. +""" +import asyncio +import json +import logging +import re +import time +from datetime import datetime, timezone +from typing import Any, Awaitable, Callable, Dict, List, Optional + +from backend.utils import shared_moments + +logger = logging.getLogger("SASS Logger") + +SIGNALS = { + "shared_past": re.compile(r"\bremember (?:when|that time|the time|how you|how we)\b|\bthat time (?:you|we)\b|\blast time (?:you|we)\b", re.I), + "milestone": re.compile(r"\b(?:it works|it worked|we did it|finally (?:works|working|done|merged|shipped|fixed)|shipped it|got the (?:job|offer)|i got the job|nailed it|you nailed|we nailed|first time (?:you|we|it))\b", re.I), + "verdict": re.compile(r"\b(?:you forgot|you broke|you saved me|cents for|best (?:reply|answer) (?:yet|ever)|you (?:finally|actually) (?:did|got) it|proud of (?:you|us)|that was (?:amazing|hilarious|perfect)|you did it)\b", re.I), +} +# Beside interest_anchor's sensitive topics: substances, which that list leaves to "drugs" and "alcohol" (one of Jack's real signal messages was "remember when we got you high"). +_SUBSTANCES_RE = re.compile(r"\b(?:high|stoned|weed|joints?|edibles?|vap(?:e|ing)|smok\w*|bong|drinks?|drinking|hungover|cravings?|buzzed)\b", re.IGNORECASE) +LOW_VALENCES = ("low", "distressed") +CALL_GAP_HOURS = 6 +MAX_WAITING = 5 +MAX_MESSAGES = 8 +MAX_CHARS_PER_MESSAGE = 600 +_last_call: Dict[str, float] = {} + + +def signal_of(message: str) -> Optional[str]: + """Which signal the message carries, or None. Pure.""" + for name, pattern in SIGNALS.items(): + if pattern.search(message or ""): + return name + return None + + +def worth_a_look(message: str, *, guest: bool, risk_active: bool, mood: Optional[Dict[str, Any]]) -> bool: + """The cheap gates, before any database read or model call. Pure.""" + mood = mood or {} + if guest or risk_active or not signal_of(message): + return False + return not (mood.get("read_this_turn") and str(mood.get("valence")) in LOW_VALENCES) + + +def _allow_call(username: str, now_ts: Optional[float] = None) -> bool: + now_ts = time.time() if now_ts is None else now_ts + last = _last_call.get(username) + if last is not None and now_ts - last < CALL_GAP_HOURS * 3600: + return False + _last_call[username] = now_ts + return True + + +def forget_calls() -> None: + _last_call.clear() + + +def exchange_text(messages: List[Any]) -> str: + """The last MAX_MESSAGES messages as "Person:" / "Sonic:" lines, oldest first. Pure.""" + lines = [] + for message in list(messages or [])[-MAX_MESSAGES:]: + kind = getattr(message, "type", "") + content = getattr(message, "content", "") + if kind not in ("human", "ai") or not isinstance(content, str) or not content.strip(): + continue + lines.append(f"{'Person' if kind == 'human' else 'Sonic'}: {' '.join(content.split())[:MAX_CHARS_PER_MESSAGE]}") + return "\n".join(lines) + + +def parse(reply: Any) -> Optional[Dict[str, Any]]: + """{"moment", "cues"} from the model's reply, or None. Pure.""" + text = reply.content if hasattr(reply, "content") else reply + if isinstance(text, list): + text = "".join(part.get("text", "") if isinstance(part, dict) else str(part) for part in text) + match = re.search(r"\{.*\}", str(text or ""), re.DOTALL) + if not match: + return None + try: + data = json.loads(match.group(0)) + except ValueError: + return None + if not isinstance(data, dict) or not isinstance(data.get("moment"), str) or not data["moment"].strip(): + return None + return {"moment": data["moment"], "cues": data.get("cues") if isinstance(data.get("cues"), list) else []} + + +# A cue has to be specific to the moment, or it fires on everything: on the first live run (2026-11-25) the model offered "it worked", "forgotten" and "huge milestone". A cue +# is kept only when one of its words is RARE in what this person has written in the conversation (in fewer than RARE_SHARE of their messages), judged once the conversation +# has RARITY_MIN_MESSAGES of theirs; a shorter one keeps every cue that is in the messages. +RARE_SHARE = 0.01 +RARITY_MIN_MESSAGES = 100 +_CUE_WORD_RE = re.compile(r"[a-z0-9][a-z0-9'._/-]{2,}") + + +def specific_cues(cues: List[str], messages: List[Any]) -> List[str]: + """The cues with at least one word that is rare in this person's own messages. Pure.""" + theirs = [str(getattr(m, "content", "")).lower() for m in messages or [] if getattr(m, "type", "") == "human" and isinstance(getattr(m, "content", None), str)] + if len(theirs) < RARITY_MIN_MESSAGES: + return list(cues) + limit = RARE_SHARE * len(theirs) + kept = [] + for cue in cues: + words = _CUE_WORD_RE.findall(cue.lower()) + if any(sum(1 for text in theirs if re.search(r"(? Optional[Dict[str, Any]]: + """The moment as it may be stored, or None: grounded in the messages, cues that really appear in them, nothing sensitive, dated today. Pure.""" + if not found: + return None + from backend.utils.interest_anchor import is_sensitive + from backend.utils.memory_grounding import ground_note + + person = " ".join(str(getattr(m, "content", "")) for m in messages[-MAX_MESSAGES:] if getattr(m, "type", "") == "human") + sonic = " ".join(str(getattr(m, "content", "")) for m in messages[-MAX_MESSAGES:] if getattr(m, "type", "") == "ai") + line = " ".join(found["moment"].split()) + if is_sensitive(line) or is_sensitive(person) or _SUBSTANCES_RE.search(f"{line} {person}"): + return None + if ground_note(line, user_text=person, assistant_text=sonic, names_anywhere=True).dropped: + return None # a number, time, day or name the messages do not hold + everything = f"{person} {sonic}" + cues = [cue for cue in found["cues"] if isinstance(cue, str) and shared_moments.mentions(everything, cue)] + cues = specific_cues(cues, messages) + cleaned, errors = shared_moments.clean({"text": line, "when": today, "cues": cues}) + return cleaned if not errors else None + + +async def capture( + username: str, + messages: List[Any], + *, + guest: bool, + risk_active: bool, + mood: Optional[Dict[str, Any]], + invoke: Optional[Callable[[str], Awaitable[Any]]] = None, + get_db_fn: Optional[Callable[[], Any]] = None, + record: Optional[Callable[[Dict[str, int]], None]] = None, + now: Optional[datetime] = None, +) -> bool: + """Proposes one new shared moment from the latest exchange, if there is one. Runs as a background task: never raises. True when a moment was proposed.""" + try: + latest = next((str(m.content) for m in reversed(messages or []) if getattr(m, "type", "") == "human" and isinstance(getattr(m, "content", None), str)), "") + if not worth_a_look(latest, guest=guest, risk_active=risk_active, mood=mood): + return False + if get_db_fn is None: + from backend.utils.db_utils import get_db as get_db_fn + if record is None: + from backend.utils.self_counters import record_turn_counts as record + db = get_db_fn() + if db is None: + return False + waiting = [m for m in await asyncio.to_thread(shared_moments.list_for, db, username) if m.get("status") == shared_moments.PROPOSED] + if len(waiting) >= MAX_WAITING or not _allow_call(username): + return False + from backend.components.constraints import MOMENT_CAPTURE_PROMPT + + if invoke is None: + from backend.models.models import lite_llm + + invoke = lite_llm.ainvoke + found = parse(await invoke(MOMENT_CAPTURE_PROMPT.format(exchange=exchange_text(messages)))) + moment = validate(found, list(messages or []), (now or datetime.now(timezone.utc)).date().isoformat()) + if moment is None: + await asyncio.to_thread(record, {"moment_capture_asked": 1, **({"moment_capture_refused": 1} if found else {})}) + return False + stored, _errors = await asyncio.to_thread(lambda: shared_moments.propose(db, username, moment, source="captured", now=now)) + await asyncio.to_thread(record, {"moment_capture_asked": 1, **({"moment_capture_proposed": 1} if stored else {})}) + return stored is not None + except Exception: + logger.warning("[moment_capture] could not look for a new shared moment.", exc_info=True) + return False diff --git a/backend/utils/self_counters.py b/backend/utils/self_counters.py index 472a1f7..53db284 100644 --- a/backend/utils/self_counters.py +++ b/backend/utils/self_counters.py @@ -99,7 +99,7 @@ # How much each turn mattered, whatever model wrote it (backend/utils/reply_tier.py STAKES, plus "none" for a plain turn): sizes the turns a stronger reply voice would be spent on. Counts only. "reply_stakes": ("safety", "emotional", "checkin", "companion", "identity", "frustration", "none"), } -_PLAIN_KEYS = ("turns_total", "self_model_used", "experience_captured", "experience_capture_merged", "experience_capture_invalid", "experience_offered", "experience_cited", "native_runs", "native_calls", "native_chars_sent", "native_chars_results", "native_chars_instructions", "native_chars_tools", "native_chars_preferences", "native_chars_architecture", "native_chars_memory", "native_chars_history", "native_chars_leanings", "leaning_turns", "native_chars_environment", "native_chars_request", "code_plan_turns", "code_plan_exec_tool_steps", "code_plan_exec_early", "code_plan_fed_next", "code_plan_turn_cap_hit", "code_plan_submitted", "code_plan_invalid", "code_plan_approved", "code_plan_cancelled", "code_plan_stalled", "code_plan_halted", "code_plan_marked_done", "claim_unproven", "claim_sent_back", "claim_edit_unbacked", "code_plan_exec_turns", "code_plan_exec_cap_hit", "code_plan_exec_edited", "code_plan_steps_done", "code_plan_prefetched", "code_plan_deviation", "code_pushback", "code_frustrated", "code_proposals", "code_proposal_rework", "code_edit_calls", "code_edit_errors", "code_test_runs", "code_edit_applied", "code_edit_declined", "code_edit_undone", "code_edit_applied_small", "code_edit_applied_large", "code_edit_declined_small", "code_edit_declined_large", "code_edit_undone_small", "code_edit_undone_large", "working_notes_updated", "working_notes_item_added", "working_notes_item_dropped", "working_notes_injected", "working_notes_chat_read", "reply_fit_checked", "reward_evaluated", "relatable_offered", "self_mention", "observations_injected", "observations_used", "experience_placed", "relatable_placed", "take_offered", "corrections_carried", "goal_guard_shown", "care_pause_shown", "timeline_shown", "vague_fact_skipped", "hear_you_held", "code_plan_step_closed", "code_cross_file_refused", "code_cross_file_overridden", "reply_bans_shown", "notes_standout_held", "notes_second_look", "notes_second_look_kept", "low_move_push_back", "low_move_pattern", "low_move_company", "support_choice_offered", "support_choice_listen", "support_choice_advice", "support_choice_fix", "support_mode_applied", "encouragement_offered", "open_loop_captured", "open_loop_offered", "open_loop_resolved", "callback_offered", "self_history_offered", "initiation_offered", "initiation_fallback", "initiation_answered", "initiation_interest_offered", "initiation_interest_answered", "duration_offered", "curiosity_offered", "curiosity_taken", "shelf_offered", "shelf_taken", "shelf_listed", "finding_selected", "lean_offered", "guardrail_applied", "routines_offered", "followups_offered", "task_results_offered", "meeting_turns", "headsup_offered", "clarify_noted", "clarify_asked", "clarify_answered", "memory_note_dropped", "memory_note_trimmed", "status_offered", "offer_made", "offer_taken", "offer_passed", "offer_held_back", "code_turns", "code_cap_hit", "code_edited", "code_verified", "code_followed", "code_redo") +_PLAIN_KEYS = ("turns_total", "self_model_used", "experience_captured", "experience_capture_merged", "experience_capture_invalid", "experience_offered", "experience_cited", "native_runs", "native_calls", "native_chars_sent", "native_chars_results", "native_chars_instructions", "native_chars_tools", "native_chars_preferences", "native_chars_architecture", "native_chars_memory", "native_chars_history", "native_chars_leanings", "leaning_turns", "native_chars_environment", "native_chars_request", "code_plan_turns", "code_plan_exec_tool_steps", "code_plan_exec_early", "code_plan_fed_next", "code_plan_turn_cap_hit", "code_plan_submitted", "code_plan_invalid", "code_plan_approved", "code_plan_cancelled", "code_plan_stalled", "code_plan_halted", "code_plan_marked_done", "claim_unproven", "claim_sent_back", "claim_edit_unbacked", "code_plan_exec_turns", "code_plan_exec_cap_hit", "code_plan_exec_edited", "code_plan_steps_done", "code_plan_prefetched", "code_plan_deviation", "code_pushback", "code_frustrated", "code_proposals", "code_proposal_rework", "code_edit_calls", "code_edit_errors", "code_test_runs", "code_edit_applied", "code_edit_declined", "code_edit_undone", "code_edit_applied_small", "code_edit_applied_large", "code_edit_declined_small", "code_edit_declined_large", "code_edit_undone_small", "code_edit_undone_large", "working_notes_updated", "working_notes_item_added", "working_notes_item_dropped", "working_notes_injected", "working_notes_chat_read", "reply_fit_checked", "reward_evaluated", "relatable_offered", "self_mention", "observations_injected", "observations_used", "experience_placed", "relatable_placed", "take_offered", "corrections_carried", "goal_guard_shown", "care_pause_shown", "timeline_shown", "vague_fact_skipped", "hear_you_held", "shared_moment_offered", "shared_moment_used", "moment_capture_asked", "moment_capture_proposed", "moment_capture_refused", "code_plan_step_closed", "code_cross_file_refused", "code_cross_file_overridden", "reply_bans_shown", "notes_standout_held", "notes_second_look", "notes_second_look_kept", "low_move_push_back", "low_move_pattern", "low_move_company", "support_choice_offered", "support_choice_listen", "support_choice_advice", "support_choice_fix", "support_mode_applied", "encouragement_offered", "open_loop_captured", "open_loop_offered", "open_loop_resolved", "callback_offered", "self_history_offered", "initiation_offered", "initiation_fallback", "initiation_answered", "initiation_interest_offered", "initiation_interest_answered", "duration_offered", "curiosity_offered", "curiosity_taken", "shelf_offered", "shelf_taken", "shelf_listed", "finding_selected", "lean_offered", "guardrail_applied", "routines_offered", "followups_offered", "task_results_offered", "meeting_turns", "headsup_offered", "clarify_noted", "clarify_asked", "clarify_answered", "memory_note_dropped", "memory_note_trimmed", "status_offered", "offer_made", "offer_taken", "offer_passed", "offer_held_back", "code_turns", "code_cap_hit", "code_edited", "code_verified", "code_followed", "code_redo") # The rhythm of a coding turn (backend/utils/loop_rhythm.py): turns it was followed on, turns that acted at all, reads before the first act (summed), edits applied, applied edits checked in the next # step, and reading-streak notices shown. Counts only. RHYTHM_KEYS = ("code_rhythm_turns", "code_rhythm_acted_turns", "code_rhythm_reads_before_first_act", "code_rhythm_applies", "code_rhythm_applies_checked", "code_rhythm_streak_notices") diff --git a/backend/utils/shared_moments.py b/backend/utils/shared_moments.py new file mode 100644 index 0000000..b73d128 --- /dev/null +++ b/backend/utils/shared_moments.py @@ -0,0 +1,181 @@ +"""Shared moments: real things that happened between a person and Sonic, which Sonic may bring up the way a friend does ("like the night the plan loop cost you fifty cents +for two asks"). The 2026-11-25 entityhood review: Sonic had a record of its own, leanings, takes, people notes and jokes, but almost nothing that came from its history WITH +the person, which is the one thing no other assistant has. + +WHAT ONE IS. A short line in Sonic's words (`text`), the day it happened (`when`, a real date), and a few cue words that make it relevant (`cues`). One document each in +COLLECTION. Every moment starts PROPOSED and is used only once the person APPROVED it (the Memory page): a moment is about them, so they decide which ones Sonic may bring up. + +WHEN IT IS USED. Code decides, never the model: the person's message names one of its cues (whole words), the turn is conversational and calm (no safety context, not a +closing, a mood that is open, nothing else proactive already in the reply), no moment was offered in the last GAP_MESSAGES messages, and this moment was not used in the last +COOLDOWN_DAYS. Then the reply is told it may refer to it in one light clause, and to leave it out if it does not fit. Whether the reply really used it is counted (`used`). + +Nothing of a moment is logged. Pure apart from the storage functions, which take the database. +""" +import re +import uuid +from datetime import date, datetime, timedelta, timezone +from typing import Any, Dict, Iterable, List, Optional, Tuple + +COLLECTION = "shared_moments" +PROPOSED, APPROVED, DISMISSED = "proposed", "approved", "dismissed" +STATUSES = (PROPOSED, APPROVED, DISMISSED) +MARK = "shared_moment" +GAP_MESSAGES = 30 +COOLDOWN_DAYS = 14 +MAX_TEXT = 200 +MAX_CUES = 6 +MAX_PER_PERSON = 60 +_STOP = frozenset("that this with have been just like what your they them there their about from would could should really still very much when then than into also some more were will the and for you our".split()) + + +def _words(text: str) -> set: + return {w for w in re.findall(r"[a-z0-9']{4,}", (text or "").lower()) if w not in _STOP} + + +def clean(raw: Any, today: Optional[date] = None) -> Tuple[Optional[Dict[str, Any]], List[str]]: + """({text, when, cues}, []) for a moment that can be stored, or (None, the reasons). The date must be a real day, not in the future. Pure.""" + errors: List[str] = [] + raw = raw if isinstance(raw, dict) else {} + text = " ".join(str(raw.get("text") or "").split()) + if not 8 <= len(text) <= MAX_TEXT: + errors.append(f"text: one line of 8 to {MAX_TEXT} characters") + when = str(raw.get("when") or "").strip() + try: + day = date.fromisoformat(when) + if day > (today or datetime.now(timezone.utc).date()): + errors.append("when: the day has not happened yet") + except ValueError: + errors.append("when: a real date, YYYY-MM-DD") + cues = [] + for cue in raw.get("cues") or []: + cue = " ".join(str(cue or "").lower().split()) + if len(cue) >= 3 and cue not in cues: + cues.append(cue) + if not cues: + errors.append("cues: at least one word or phrase (three letters or more) that makes it relevant") + if errors: + return None, errors + return {"text": text, "when": when, "cues": cues[:MAX_CUES]}, [] + + +def mentions(message: str, cue: str) -> bool: + """Whether the message names the cue as a whole word or phrase (case-insensitive; an apostrophe or none, as people type it). Pure.""" + norm = lambda t: (t or "").lower().replace("’", "'") # noqa: E731 + pattern = r"(? bool: + return any((getattr(m, "additional_kwargs", None) or {}).get(MARK) for m in list(recent_messages or [])[-gap:]) + + +def pick(moments: Iterable[Dict[str, Any]], message: str, recent_messages: Iterable[Any], *, now: datetime, source_type: str, risk_active: bool, + closing: bool, energy_tier: str, proactive_taken: bool) -> Optional[Dict[str, Any]]: + """The approved moment this message calls up, or None. The one naming the most cues wins, then the one used longest ago. Pure.""" + if source_type != "conversational" or risk_active or closing or energy_tier != "open" or proactive_taken or recently_offered(recent_messages): + return None + best, best_key = None, None + for moment in moments or []: + if moment.get("status") != APPROVED: + continue + last = moment.get("last_used_at") + if last: + try: + used = datetime.fromisoformat(str(last)) + if (now - (used if used.tzinfo else used.replace(tzinfo=timezone.utc))) < timedelta(days=COOLDOWN_DAYS): + continue + except ValueError: + pass + hits = sum(1 for cue in moment.get("cues") or [] if mentions(message, cue)) + if not hits: + continue + key = (hits, -(datetime.fromisoformat(str(last)).timestamp() if last else 0)) + if best_key is None or key > best_key: + best, best_key = moment, key + return best + + +def _day(iso: str) -> str: + try: + return date.fromisoformat(iso).strftime("%b %d, %Y").replace(" 0", " ") + except ValueError: + return "" + + +def build_block(moment: Optional[Dict[str, Any]]) -> str: + """The reply prompt's section, or "". Pure.""" + if not moment: + return "" + when = _day(str(moment.get("when") or "")) + return ( + "\nSOMETHING YOU AND THEY SHARE (a real moment from your history together, which they approved you bringing up): " + f"{moment['text']}" + (f" ({when})" if when else "") + ".\n" + "If it genuinely connects to what they just said, refer to it in one light clause, the way a friend brings up something you both remember. " + "Do not explain it, do not quote this line word for word, do not make it the point of the reply, and do not add details that are not in it. If it does not fit, leave it out.\n" + ) + + +def used(reply: str, moment: Optional[Dict[str, Any]]) -> bool: + """Whether the reply really brought the moment up: it shares two content words with the moment's line, or names one of its cues. Pure.""" + if not moment or not reply: + return False + return len(_words(reply) & _words(moment.get("text", ""))) >= 2 or any(mentions(reply, cue) for cue in moment.get("cues") or []) + + +# ---- storage -------------------------------------------------------------------------------------------------------------------------------- + +def list_for(db: Any, username: str) -> List[Dict[str, Any]]: + """Every moment of this person, newest day first (no database: none). Blocking.""" + if db is None or not username: + return [] + rows = list(db[COLLECTION].find({"username": username}, {"_id": 0})) + return sorted(rows, key=lambda m: (str(m.get("when") or ""), str(m.get("created_at") or "")), reverse=True) + + +def approved_for(db: Any, username: str) -> List[Dict[str, Any]]: + return [m for m in list_for(db, username) if m.get("status") == APPROVED] + + +def propose(db: Any, username: str, raw: Any, *, source: str = "suggested", now: Optional[datetime] = None) -> Tuple[Optional[Dict[str, Any]], List[str]]: + """Stores a moment as PROPOSED (it is not used until approved). The same text twice is one moment, and a person has at most MAX_PER_PERSON. Blocking.""" + now = now or datetime.now(timezone.utc) + cleaned, errors = clean(raw, now.date()) + if cleaned is None: + return None, errors + existing = list_for(db, username) + if any(m.get("text", "").lower() == cleaned["text"].lower() for m in existing): + return None, ["this moment is already there"] + if len(existing) >= MAX_PER_PERSON: + return None, [f"at most {MAX_PER_PERSON} moments; remove some first"] + moment = {**cleaned, "id": uuid.uuid4().hex, "username": username, "status": PROPOSED, "source": source, "created_at": now.isoformat(), "uses": 0, "last_used_at": None} + db[COLLECTION].insert_one(dict(moment)) + return moment, [] + + +def set_status(db: Any, username: str, moment_id: str, status: str) -> bool: + """Approves or dismisses one of this person's moments. False for an unknown status or a moment that is not theirs. Blocking.""" + if status not in (APPROVED, DISMISSED) or db is None: + return False + result = db[COLLECTION].update_one({"username": username, "id": moment_id}, {"$set": {"status": status}}) + return bool(getattr(result, "matched_count", 0)) + + +def delete(db: Any, username: str, moment_id: str) -> bool: + if db is None: + return False + result = db[COLLECTION].delete_one({"username": username, "id": moment_id}) + return bool(getattr(result, "deleted_count", 0)) + + +def note_used(db: Any, username: str, moment_id: str, now: Optional[datetime] = None) -> None: + """Records that a reply brought the moment up (starts its cooldown). Blocking; never raises.""" + try: + db[COLLECTION].update_one({"username": username, "id": moment_id}, + {"$set": {"last_used_at": (now or datetime.now(timezone.utc)).isoformat()}, "$inc": {"uses": 1}}) + except Exception: + pass + + +def public(moment: Dict[str, Any]) -> Dict[str, Any]: + """What the Memory page shows of a moment. Pure.""" + return {k: moment.get(k) for k in ("id", "text", "when", "cues", "status", "source", "uses", "last_used_at")} diff --git a/local/src/api.ts b/local/src/api.ts index 12fef3d..578d0db 100644 --- a/local/src/api.ts +++ b/local/src/api.ts @@ -2585,6 +2585,31 @@ export async function steerChat(sessionId: string, message: string): Promise<{ s return res.json(); } +/** A moment from the person's history with Sonic that Sonic may bring up, once they approve it (backend/utils/shared_moments.py). */ +export interface SharedMoment { + id: string; text: string; when: string; cues: string[]; + status: 'proposed' | 'approved'; + source?: string; uses?: number; last_used_at?: string | null; +} + +export async function listSharedMoments(): Promise { + const res = await fetch(`${BASE_URL}/api/shared-moments`, { headers: { ...(await getAuthHeaders()) } }); + if (!res.ok) throw new Error("Failed to load shared moments."); + return ((await res.json()).moments || []) as SharedMoment[]; +} + +export async function setSharedMomentStatus(id: string, status: 'approved' | 'dismissed'): Promise { + const res = await fetch(`${BASE_URL}/api/shared-moments/${encodeURIComponent(id)}/status`, { + method: "POST", headers: { "Content-Type": "application/json", ...(await getAuthHeaders()) }, body: JSON.stringify({ status }), + }); + if (!res.ok) throw new Error("Failed to update the moment."); +} + +export async function deleteSharedMoment(id: string): Promise { + const res = await fetch(`${BASE_URL}/api/shared-moments/${encodeURIComponent(id)}`, { method: "DELETE", headers: { ...(await getAuthHeaders()) } }); + if (!res.ok) throw new Error("Failed to remove the moment."); +} + /** Stop: the running turn of this conversation ends at its next check. A dropped connection no longer stops a turn on the server, so Stop has to say so itself. */ export async function stopChat(sessionId: string): Promise<{ status: string }> { const authHeaders = await getAuthHeaders(); @@ -2797,6 +2822,9 @@ export const api = { sendChatMessage, steerChat, stopChat, + listSharedMoments, + setSharedMomentStatus, + deleteSharedMoment, getTurnStatus, listConversations, getConversation, diff --git a/local/src/components/helpTips.ts b/local/src/components/helpTips.ts index 0bc180c..9f6e68b 100644 --- a/local/src/components/helpTips.ts +++ b/local/src/components/helpTips.ts @@ -82,6 +82,7 @@ export const HELP_TIPS: Record = { 'card.steps': { title: 'Steps to run', what: 'A short list of steps Sonic suggests, each with its own Run button. A step that changes things asks you to confirm first.', wont: 'Run a step until you press it.' }, // ---- Memory ---- + 'memory.ourHistory': { title: 'Our history', what: 'Moments from your time with Sonic that it may bring up when something you say calls one up. Only the ones you approve are ever used.', when: 'You want to choose what Sonic may remind you of, or take something back.' }, 'memory.comingUp': { title: 'Coming up', what: 'Things you mentioned that are on the way, with what Sonic knows about each and where it came from. A detail you never gave shows as not known.', when: 'You want to check or correct what Sonic has noted about an event.' }, 'memory.looksRight': { title: 'Looks right', what: 'Marks this upcoming item as checked by you, so Sonic treats its details as right.' }, 'memory.editLoop': { title: 'Edit an upcoming item', what: 'Lets you change its day, time, who it is with and where.', when: 'A detail is wrong or you can now fill in one that was not known.' }, diff --git a/local/src/pages/Memory.tsx b/local/src/pages/Memory.tsx index 2640b3e..ae4a662 100644 --- a/local/src/pages/Memory.tsx +++ b/local/src/pages/Memory.tsx @@ -1,8 +1,8 @@ import React, { useEffect, useState } from 'react'; -import { api, type UserFact, type OpenLoop, type OpenLoopChanges, type MemoryStored, type MemoryDomain } from '../api'; +import { api, type UserFact, type OpenLoop, type OpenLoopChanges, type MemoryStored, type MemoryDomain, type SharedMoment } from '../api'; import './__styles__/SelfService.css'; import './__styles__/Memory.css'; -import { ALL_TOPIC, COMING_UP, activeTopicOf, topicLabel } from './memoryTopics'; +import { ALL_TOPIC, COMING_UP, OUR_HISTORY, activeTopicOf, topicLabel } from './memoryTopics'; const CATEGORY_COLORS: Record = { identity: 'cat-identity', @@ -93,6 +93,8 @@ const TopicButton: React.FC<{ active: boolean; label: string; count: number; dot export const MemoryPage: React.FC = () => { const [facts, setFacts] = useState([]); const [loops, setLoops] = useState([]); + const [moments, setMoments] = useState([]); // moments from their history with Sonic (backend/utils/shared_moments.py) + const [momentBusyId, setMomentBusyId] = useState(null); const [stored, setStored] = useState({ notes: 0, archived: 0 }); const [loading, setLoading] = useState(true); const [deletingId, setDeletingId] = useState(null); @@ -137,6 +139,28 @@ export const MemoryPage: React.FC = () => { return () => { cancelled = true; }; }, []); + useEffect(() => { + let cancelled = false; + api.listSharedMoments() + .then((data: SharedMoment[]) => { if (!cancelled) setMoments(data); }) + .catch((err: unknown) => { console.error('Failed to load shared moments:', err); }); + return () => { cancelled = true; }; + }, []); + + // Approving lets Sonic bring a moment up when something they say calls it up; "Not this one" and Remove take it away for good. + const decideMoment = async (moment: SharedMoment, action: 'approved' | 'dismissed' | 'remove') => { + setMomentBusyId(moment.id); + try { + if (action === 'remove') await api.deleteSharedMoment(moment.id); + else await api.setSharedMomentStatus(moment.id, action); + setMoments(prev => (action === 'approved' ? prev.map(m => (m.id === moment.id ? { ...m, status: 'approved' } : m)) : prev.filter(m => m.id !== moment.id))); + } catch (err) { + console.error('Failed to update a shared moment:', err); + } finally { + setMomentBusyId(null); + } + }; + const handleDeleteLoop = async (loopId: string, loopText: string) => { if (!window.confirm(`Forget "${loopText}"? Sonic won't ask about it.`)) return; try { @@ -283,7 +307,7 @@ export const MemoryPage: React.FC = () => { }; const categories = Array.from(new Set(facts.map(f => f.category))).sort(); - const activeTopic = activeTopicOf(topic, categories, loops.length); // a topic with nothing left in it falls back to everything + const activeTopic = activeTopicOf(topic, categories, loops.length, moments.length); // a topic with nothing left in it falls back to everything const comingUpCount = loops.filter(l => l.status !== 'cancelled').length; const filteredFacts = facts @@ -307,6 +331,7 @@ export const MemoryPage: React.FC = () => {
+ {activeTopic === OUR_HISTORY && ( +
+
{moments.filter(m => m.status === 'proposed').length} WAITING FOR YOU
+

Our history

+

+ Moments from your time with Sonic that it may bring up, the way a friend remembers something you both lived through. It only uses one you approved, only when + something you say calls it up, and not often. Approve the ones you're happy for it to mention, or remove the rest. +

+
+ {moments.map(moment => ( +
+
+
+ {formatDueDay(moment.when)} + {moment.status === 'approved' ? 'approved' : 'waiting for your OK'} + {(moment.uses ?? 0) > 0 && brought up {moment.uses}×} +
+
{moment.text}
+
+
+ {moment.status === 'proposed' && ( + + )} + {moment.status === 'proposed' ? ( + + ) : ( + + )} +
+
+ ))} +
+
+ )} {activeTopic === COMING_UP && (
{loops.filter(l => l.status !== 'cancelled').length} COMING UP
@@ -408,7 +467,7 @@ export const MemoryPage: React.FC = () => {
)} - {activeTopic !== COMING_UP && ( + {activeTopic !== COMING_UP && activeTopic !== OUR_HISTORY && (
{activeTopic === ALL_TOPIC ? `${facts.length} SAVED` : `${filteredFacts.length} OF ${facts.length}`}

{activeTopic === ALL_TOPIC ? 'Saved Memories' : topicLabel(activeTopic)}

diff --git a/local/src/pages/memoryTopics.test.mjs b/local/src/pages/memoryTopics.test.mjs index a6c928a..1d3b90a 100644 --- a/local/src/pages/memoryTopics.test.mjs +++ b/local/src/pages/memoryTopics.test.mjs @@ -36,15 +36,21 @@ test('a topic with nothing left in it falls back to everything, so the page neve }); test('the page draws the panel and one list at a time, filters the saved memories by the topic, and the old category dropdown is gone', () => { - assert.match(page, /import \{ ALL_TOPIC, COMING_UP, activeTopicOf, topicLabel \} from '\.\/memoryTopics';/); + assert.match(page, /import \{ ALL_TOPIC, COMING_UP, OUR_HISTORY, activeTopicOf, topicLabel \} from '\.\/memoryTopics';/); assert.match(page, /const \[topic, setTopic\] = useState\(ALL_TOPIC\);/); - assert.match(page, /const activeTopic = activeTopicOf\(topic, categories, loops\.length\);/); + assert.match(page, /const activeTopic = activeTopicOf\(topic, categories, loops\.length, moments\.length\);/); assert.match(page, /\.filter\(f => activeTopic === ALL_TOPIC \|\| f\.category === activeTopic\)/); assert.match(page, /