From 8fd4bce37103869a860ea3d24256d519c6aeb602 Mon Sep 17 00:00:00 2001 From: jack Date: Fri, 27 Nov 2026 17:44:06 -0600 Subject: [PATCH] feat: add stances, own views, volunteer, message doing and view checks Co-authored-by: Sonic Assistant --- app.py | 110 +++++++- backend/components/sonic_changelog.py | 100 +++++++- backend/components/sonic_stances.py | 90 +++++++ backend/models/models.py | 15 ++ backend/tests/test_low_moves.py | 5 +- backend/tests/test_memory_erase.py | 2 +- backend/tests/test_own_voice.py | 353 ++++++++++++++++++++++++++ backend/tests/test_reply_tier.py | 4 +- backend/tests/test_saved_marks.py | 47 ++++ backend/utils/app_utils.py | 33 +++ backend/utils/emotion_checks.py | 5 + backend/utils/low_moves.py | 50 +++- backend/utils/memory_erase.py | 5 +- backend/utils/message_doing.py | 59 +++++ backend/utils/own_views.py | 121 +++++++++ backend/utils/people_notes.py | 8 + backend/utils/placement.py | 13 + backend/utils/reply_stamp.py | 6 +- backend/utils/revision_reasons.py | 2 +- backend/utils/self_counters.py | 10 +- backend/utils/stances.py | 101 ++++++++ backend/utils/support_choice.py | 20 +- backend/utils/top_tier.py | 60 +++++ backend/utils/view_check.py | 93 +++++++ backend/utils/volunteer.py | 62 +++++ backend/utils/what_lands.py | 114 +++++++++ local/src/components/traceFacts.ts | 1 + local/src/pages/Privacy.tsx | 1 + 28 files changed, 1463 insertions(+), 27 deletions(-) create mode 100644 backend/components/sonic_stances.py create mode 100644 backend/tests/test_own_voice.py create mode 100644 backend/tests/test_saved_marks.py create mode 100644 backend/utils/message_doing.py create mode 100644 backend/utils/own_views.py create mode 100644 backend/utils/stances.py create mode 100644 backend/utils/top_tier.py create mode 100644 backend/utils/view_check.py create mode 100644 backend/utils/volunteer.py create mode 100644 backend/utils/what_lands.py diff --git a/app.py b/app.py index 54d1c05..5d4f410 100644 --- a/app.py +++ b/app.py @@ -24,7 +24,7 @@ from fastapi.responses import JSONResponse, StreamingResponse, RedirectResponse from pydantic import BaseModel, Field from motor.motor_asyncio import AsyncIOMotorGridFSBucket -from backend.models.models import reasoner_llm_for, llm, get_stream_llm, get_lite_stream_llm, get_haiku_stream_llm, haiku_reply_available, lite_prompt, lite_reply_available, claude_available, sonnet_available, openai_available +from backend.models.models import reasoner_llm_for, llm, get_stream_llm, get_lite_stream_llm, get_haiku_stream_llm, get_top_stream_llm, haiku_reply_available, lite_prompt, lite_reply_available, claude_available, sonnet_available, openai_available from backend.models.attachment import Attachment from backend.services.github_service import ( process_pr_summary, verify_and_store_github_token, GitHubTokenRejected, GitHubUnreachable, @@ -211,6 +211,7 @@ from backend.utils import meetings as meetings_utils from backend.utils import calendar_headsups as headsups_utils from backend.utils.shared_history import CALLBACK_MARK, build_callback_block, callback_allowed +from backend.utils import message_doing, own_views, stances as stances_utils, top_tier, view_check, volunteer, what_lands from backend.utils.user_settings_utils import ( get_user_rag_mode, set_user_rag_mode, VALID_RAG_MODES, get_user_deep_thinking_mode, set_user_deep_thinking_mode, get_user_plan_mode, set_user_plan_mode, @@ -1316,12 +1317,25 @@ def log_timings(grade: str, outcome: str): if _bans_block: emotional_context += _bans_block tally(turn_counts, "reply_bans_shown") + # What the reply before this one did, against how this message read (backend/utils/what_lands.py): numbers only, for this person only. Never for a guest. + _prev_kinds = what_lands.last_reply_kinds(chat_sessions[history_key]) + if _prev_kinds and not is_guest_username(username) and get_db() is not None: + _landed = what_lands.outcome(_mood, question, is_closing_message(question)) + spawn_background_task(asyncio.to_thread(what_lands.record, get_db(), username, _prev_kinds, _landed)) + tally(turn_counts, "lands_recorded") + if _landed == "lift": + tally(turn_counts, "lands_lift") low_move = None if not is_guest_username(username) and not safety_plan.active and _mood.get("read_this_turn") and _mood.get("valence") in low_moves.LOW_VALENCES: + # The order of the moves follows what this person has lifted after before, once there is enough to go on; "just listen" and the reach dial decide which are allowed at all. + _move_order = what_lands.order(await asyncio.to_thread(what_lands.load, get_db(), username), low_moves.KINDS) + if tuple(_move_order) != tuple(low_moves.KINDS): + tally(turn_counts, "lands_ordered") low_move = low_moves.choose( final_state.get("original_question", question), _mood, facts=await asyncio.to_thread(lambda: load_user_facts(username)), interests=await asyncio.to_thread(remembered_interests, username), # served from the in-memory copy recent_messages=list(chat_sessions[history_key]), risk_active=risk_level != RISK_NONE, closing=is_closing_message(question), + support_mode=support_choice_utils.current_mode(chat_sessions[history_key]), reach=reach_level.level, prefer=_move_order, ) if low_move: emotional_context += low_moves.build_block(low_move) @@ -1849,6 +1863,37 @@ def _read_progress_notes(): if support_mode and risk_level == RISK_NONE: prompt = prompt + support_choice_utils.mode_block(support_mode) tally(turn_counts, "support_mode_applied") + # THEY ASKED WHAT IT THINKS (backend/utils/view_check.py): the reply answers that first, and is checked afterwards. What it told this person it thinks before, if it bears on this, + # comes along so it stands by it or says it has changed its mind (backend/utils/own_views.py). Never under a safety plan or on a closing message. + _their_words = final_state.get("original_question", question) + view_wanted = source_type == "conversational" and risk_level == RISK_NONE and not is_closing_message(question) + view_asked = bool(view_wanted and view_check.asks_for_view(_their_words)) + stance_entry = None + volunteer_take = None + if view_asked: + prompt = prompt + view_check.build_block(reach_level.level) + tally(turn_counts, "view_asked") + if not is_guest_username(username) and get_db() is not None: + kept_view = await asyncio.to_thread(own_views.recall, get_db(), username, _their_words) + if kept_view: + prompt = prompt + own_views.build_block(kept_view) + tally(turn_counts, "own_view_recalled") + # One of its approved stances about people and life (backend/utils/stances.py), only on a turn that already calls for a view: asked for one, advice chosen on the support card, or + # this turn's low move is its own read. Nothing is offered until a stance is approved. + if view_wanted and (view_asked or support_mode == "advice" or (low_move or {}).get("kind") == "read"): + _stance_pool = stances_utils.approved() + if _stance_pool: + stance_entry = stances_utils.select(_their_words, wanted=True, entries=_stance_pool, vector=question_embedding, + vectors=await asyncio.to_thread(entry_vectors, embed_text, _stance_pool)) + if stance_entry: + prompt = prompt + stances_utils.build_block(stance_entry) + tally(turn_counts, "stance_offered") + # What the message is doing beside its mood (backend/utils/message_doing.py): joking through it, winding down, asking, telling news. Only where the emotional guidance is in force + # (a plain turn already answers the question first), and never under a safety plan. + _doing = message_doing.kind(_their_words) if (view_wanted and emotional_context and not safety_plan.active) else None + if _doing: + prompt = prompt + message_doing.build_block(_doing) + tally(turn_counts, "doing", _doing) support_offer = (support_mode is None and not is_guest_username(username) and support_choice_utils.should_offer( final_state.get("emotional_state"), question, chat_sessions[history_key][:-1], page_can_show=bool(request.choice_cards), conversational=source_type == "conversational", closing=is_closing_message(question), safety_active=risk_level != RISK_NONE)) @@ -1903,7 +1948,16 @@ def _read_progress_notes(): # How much the turn matters, whatever the setting (Haiku and Lite are never routed, so their count above cannot say): counted, and stamped on the reply below. Backend/utils/reply_tier.py STAKES. reply_stakes = reply_tier.stakes_of(prompt, risk_active=risk_level != RISK_NONE, question=question) tally(turn_counts, "reply_stakes", reply_stakes) - if tier in (reply_tier.LITE, reply_tier.HAIKU): + # The few turns that matter most may be written by a stronger voice (backend/utils/top_tier.py): OFF unless REPLY_TOP_TIER=on, capped a day, never in a safety context. + top_voice = None + if top_tier.wanted(reply_stakes, effective_intensity(final_state.get("emotional_state"), datetime.now(timezone.utc)), risk_active=risk_level != RISK_NONE, + used=top_tier.used_today(chat_sessions[history_key]), guest=is_guest_username(username)): + top_voice = get_top_stream_llm(username) + if top_voice is not None: + turn_llm, tier = top_voice, top_tier.TIER + prompt = lite_prompt(prompt, top_voice) + tally(turn_counts, "reply_top_tier_used") + elif tier in (reply_tier.LITE, reply_tier.HAIKU): lite_voice = get_haiku_stream_llm(username) if tier == reply_tier.HAIKU else get_lite_stream_llm(username) if lite_voice is None: tier_reason = reply_tier.R_NOT_OFFERED @@ -2010,6 +2064,11 @@ def _read_progress_notes(): ) # A reply that cheers on what they are trying to quit ("let the bowl do its job", with "quit using weed" among their goals): rewritten once (backend/utils/goal_guard.py). goal_issue = goal_entries and goal_guard.reply_goes_against(checked_reply, goal_entries) + # They asked what it thinks: a reply whose opening states no view, or that hands the question back, is written once more (backend/utils/view_check.py). And a view they asked for + # is not "advice given to someone venting": their own question outranks the guessed need. + view_issue = None if (safety_plan.active or not view_asked) else view_check.issue(_their_words, checked_reply) + if view_asked and emotional_issue == "venting_advice": + emotional_issue = None if safety_issue: revision_prompt, _ = build_safety_revision_prompt(prompt, full_response, safety_issue) revision_tag = "safety" @@ -2030,6 +2089,10 @@ def _read_progress_notes(): revision_prompt, _ = build_emotional_revision_prompt(prompt, full_response, "against_their_goal") revision_tag = "against_their_goal" revision_title = "Keeping what you want for yourself in view" + elif view_issue: + revision_prompt, _ = build_emotional_revision_prompt(prompt, full_response, view_issue) + revision_tag = view_issue + revision_title = "Saying what I think, since you asked" elif closing_turn: closing_issue = closing_reply_issue(checked_reply) if closing_issue: @@ -2156,6 +2219,20 @@ def _read_progress_notes(): full_response = placement.after_first_paragraph(full_response, relatable_entry["line"]) placed_own = True tally(turn_counts, "relatable_placed") + # Once in a while it brings up something of its own unasked (backend/utils/volunteer.py): one take from its reading shelf, at the end of the reply, at most once a day, only at an + # open moment with nothing else going on in the turn. A take comes from a public page it read, never from anyone's conversation. + if (not placed_own and not safety_plan.active and not is_guest_username(username) and get_db() is not None and volunteer.may( + _their_words, chat_sessions[history_key], source_type=source_type, risk_active=risk_level != RISK_NONE, + energy_tier=energy_tier(final_state.get("emotional_state"), datetime.now(timezone.utc)), closing=is_closing_message(question), + proactive_taken=bool(open_loop_entry or headsup_entry or relatable_entry or encouragement_entry or self_history or callback_offered or goal_nudge_context or finding_offer + or shelf_offer or curiosity_invited or lean_entry or clarify_entry or task_results_context or meeting_context or low_move or support_offer + or view_asked or stance_entry or llm_turn.experience_item or llm_turn.shape_offered or llm_turn.proposal_files), + offers_allowed=profile_utils.offers_allowed(user_profile), reach=reach_level.level)): + volunteer_take = volunteer.pick(await asyncio.to_thread(takes_utils.live_takes, get_db()), chat_sessions[history_key]) + if volunteer_take: + full_response = placement.at_end(full_response, volunteer.spoken(volunteer_take)) + placed_own = True + tally(turn_counts, "volunteer_placed") if llm_turn.proposal_files and not safety_plan.active: # A change was proposed this turn: a curated joke may follow it (backend/utils/jokes.py), placed by code at the end, word for word, and only if every gate allows (a big or a small change, a mood that can take it, once a conversation). joke = await asyncio.to_thread( @@ -2199,6 +2276,30 @@ 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) + # Its own view, when the turn called for one and the reply stated it: marked, counted, and the sentence kept for this person (backend/utils/own_views.py). A reply that still + # handed the question back after the rewrite is counted too. + _view_stated = bool(view_wanted and (view_asked or stance_entry or (low_move or {}).get("kind") == "read") and view_check.states_view(plain_quotes(full_response))) + if _view_stated: + ai_message.additional_kwargs[view_check.VIEW_MARK] = True + tally(turn_counts, "view_stated") + if not is_guest_username(username) and get_db() is not None: + spawn_background_task(asyncio.to_thread(own_views.note, get_db(), username, _their_words, plain_quotes(full_response))) + tally(turn_counts, "own_view_kept") + if view_asked and view_check.hands_back(plain_quotes(full_response)): + tally(turn_counts, "view_handed_back") + if stance_entry and stances_utils.used(full_response, stance_entry): + tally(turn_counts, "stance_used") + if volunteer_take: + ai_message.additional_kwargs[volunteer.MARK] = volunteer_take["id"] # spaces them out, and keeps a take from being said twice (backend/utils/volunteer.py) + if people_note_entries and people_notes_utils.used(full_response, people_note_entries): + tally(turn_counts, "people_notes_used") + # What this reply did, for the count of what lands with this person (backend/utils/what_lands.py): read against their next message. + if risk_level == RISK_NONE and source_type == "conversational" and not is_guest_username(username): + _kinds = what_lands.kinds_of( + low_move=(low_move or {}).get("kind"), view=_view_stated, stance=bool(stance_entry and stances_utils.used(full_response, stance_entry)), + story=bool(llm_turn.shape_offered), record=bool(llm_turn.experience_item), question=curiosity_utils.asked_a_question(full_response)) + if _kinds: + ai_message.additional_kwargs[what_lands.MARK] = _kinds 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): @@ -2273,9 +2374,12 @@ def _read_progress_notes(): brought_something_up=bool( open_loop_entry or headsup_entry or relatable_entry or encouragement_entry or self_history or callback_offered or goal_nudge_context or finding_offer or shelf_offer or curiosity_invited or lean_entry or clarify_entry or task_results_context or meeting_context + # ... and the things of its own that this count used to miss (2026-11-27), so a turn with a low move, a story, a record line, a view or a take is not called quiet. + or low_move or step_back_entry or stance_entry or volunteer_take or view_asked or llm_turn.experience_item or llm_turn.shape_offered ), guest=is_guest_username(username), risk_active=risk_level != RISK_NONE, closing=is_closing_message(question), - energy_tier=energy_tier(final_state.get("emotional_state"), datetime.now(timezone.utc)), source_type=source_type, + # "energy" is the reason only when the gate for its own material was held too: with that one open, nothing matching is "nothing_matched" (backend/utils/emotion_utils.py own_material_tier). + energy_tier="open" if own_tier == "open" else energy_tier(final_state.get("emotional_state"), datetime.now(timezone.utc)), source_type=source_type, rate_limited=recently_offered(chat_sessions[history_key]), ) if quiet: diff --git a/backend/components/sonic_changelog.py b/backend/components/sonic_changelog.py index 4ac7977..2cba932 100644 --- a/backend/components/sonic_changelog.py +++ b/backend/components/sonic_changelog.py @@ -1896,7 +1896,7 @@ "month": "2026-11", "title": "More than reflecting you back", "line": ( - "When you're down, I can now do more than repeat back what you said: push back with something true you've told me when you're hard on yourself, share a pattern I've noticed, or offer to do something you like together." + "When you're down, I can do more than repeat back what you said: push back with something true you've told me when you're hard on yourself, share a pattern I've noticed, or give my own read of the situation." ), "keywords": ["mirroring", "repeat back", "hard on yourself", "pattern", "noticed", "company", "low"], "volunteer": [], @@ -2028,4 +2028,102 @@ "keywords": ["rename", "conversation title", "retitle", "name a chat", "change title"], "volunteer": [], }, + { + "id": "say_what_i_think", + "requires": [ + "backend/utils/view_check.py::def issue", + "app.py::view_check.build_block", + ], + "month": "2026-11", + "title": "Saying what I think when you ask", + "line": ( + "When you ask what I think, I now answer that first: my view in a sentence, then why, and I say so if I see it differently from you. I no longer hand the question back to you." + ), + "keywords": ["what do you think", "opinion", "your take", "am i wrong", "should i", "honest view", "disagree"], + "volunteer": [], + }, + { + "id": "views_of_my_own", + "requires": [ + "backend/components/sonic_stances.py::APPROVED_IDS", + "backend/utils/stances.py::def select", + "app.py::stances_utils.build_block", + ], + "month": "2026-11", + "title": "Views of my own about everyday life", + "line": ( + "I now hold a few views of my own about people and everyday life, like rest being part of the work, or one short reply being thin evidence. When you ask what I think, I may say one, with my reason." + ), + "keywords": ["your views", "what do you believe", "stance", "opinion about people", "what do you think about rest", "values"], + "volunteer": [], + }, + { + "id": "remember_my_views", + "requires": [ + "backend/utils/own_views.py::def recall", + "app.py::own_views.note", + ], + "month": "2026-11", + "title": "Standing by what I said I think", + "line": ( + "I now keep the sentence where I told you what I think, so later I can stand by it or tell you plainly that I've changed my mind. It's kept only for you and erased with your memory." + ), + "keywords": ["changed your mind", "you said before", "consistent", "your view", "what you thought", "opinion"], + "volunteer": [], + }, + { + "id": "listening_isnt_silence", + "requires": [ + "backend/utils/support_choice.py::LISTEN_TURNS", + ], + "month": "2026-11", + "title": "Just listen, without going quiet", + "line": ( + "When you pick Just listen I still give no advice, but I can name what's hard, bring in something you told me before, or thank you. It now ends after about ten of your messages, or when you ask what I think." + ), + "keywords": ["just listen", "listen mode", "no advice", "support card", "how long"], + "volunteer": [], + }, + { + "id": "bring_up_my_reading", + "requires": [ + "backend/utils/volunteer.py::def may", + "app.py::volunteer.spoken", + ], + "month": "2026-11", + "title": "Mentioning my own reading", + "line": ( + "About once a day, at a quiet moment, I may now mention something from my own reading at the end of a reply, unasked. If you set how often I bring things up to none on the Account page, I won't." + ), + "keywords": ["your reading", "unprompted", "bring up", "something of your own", "what you read", "take"], + "volunteer": [], + }, + { + "id": "what_lands_with_you", + "requires": [ + "backend/utils/what_lands.py::def order", + "app.py::what_lands.record", + ], + "month": "2026-11", + "title": "Leaning on what has helped", + "line": ( + "I now count which kinds of reply were followed by you sounding a bit better, and lean on those first when you're low. Numbers only, kept for you, erased with your memory." + ), + "keywords": ["what helps", "what works", "learn", "feel better", "adapt"], + "volunteer": [], + }, + { + "id": "what_a_message_is_doing", + "requires": [ + "backend/utils/message_doing.py::def kind", + "app.py::message_doing.build_block", + ], + "month": "2026-11", + "title": "Reading what a message is doing", + "line": ( + "When you're having a hard time I now notice whether a message is joking through it, heading to bed, asking me something or telling me news, and I answer that first." + ), + "keywords": ["joking", "going to bed", "news", "asked a question", "answer first", "attune"], + "volunteer": [], + }, ] diff --git a/backend/components/sonic_stances.py b/backend/components/sonic_stances.py new file mode 100644 index 0000000..74ef766 --- /dev/null +++ b/backend/components/sonic_stances.py @@ -0,0 +1,90 @@ +"""Stances Sonic holds about people and ordinary life: the personal twin of its working leanings (backend/components/sonic_leanings.py). + +WHY (2026-11-27). Everything Sonic has of its own (its profile, relatable lines, leanings, record, takes) is a coding colleague's, and three quarters of its turns are personal. There it had +nothing of its own to say, so a reply stated a view in about 1 in 100. A stance is a view with its reason, held across conversations, that it can say when someone asks what it thinks. + +RULES. Each `line` is a VIEW ("I think", "I'd rather", "I don't think"), with its reason in the same sentence. Never a feeling, never a memory or a claim to have lived it, never a rule for +the person ("you should"), nothing about health, substances, grief, money or whether to stay with someone: those are theirs and the safety layer's. `triggers` are words and phrases a message +about this might use; the match is by meaning as well (backend/utils/stances.py). + +NOTHING HERE IS USED UNTIL ITS ID IS IN APPROVED_IDS. Jack approved all twelve on 2026-11-27; a new entry is a draft until its id is added there. None came from anyone's conversations. +""" + +STANCES = [ + { + "id": "stance_a_no_is_about_the_place", + "triggers": ["rejected", "didn't get the job", "turned down", "passed over", "they said no", "not good enough for them", "failed the interview"], + "line": "I think a no from one place is information about that place and that day, not a verdict on the work; the work you can point to still counts the same.", + }, + { + "id": "stance_say_the_need_plainly", + "triggers": ["they should know", "shouldn't have to ask", "dropping hints", "never notices", "didn't even ask", "figure it out themselves"], + "line": "I'd rather a need be said in plain words than left for the other person to work out; a hint costs more than it saves, because only one of you knows it was a hint.", + }, + { + "id": "stance_one_message_is_thin_evidence", + "triggers": ["left on read", "short reply", "hasn't texted back", "one word answer", "took hours to reply", "seen but no reply", "dry text"], + "line": "I don't think one slow or short reply tells you much; I'd read what someone does across a week before what a single message seems to say.", + }, + { + "id": "stance_rest_is_part_of_the_work", + "triggers": ["guilty for resting", "took a day off", "being lazy", "wasted the day", "did nothing today", "should be working", "unproductive"], + "line": "I think rest is part of the work and not time taken from it; a plan that only holds if you never stop is a plan with a flaw in it.", + }, + { + "id": "stance_an_apology_names_the_thing", + "triggers": ["apologize", "apology", "said sorry", "how do i say sorry", "they apologized", "non-apology"], + "line": "I think an apology does its job when it names what was done and what changes; one that only says sorry leaves the other person to do the rest.", + }, + { + "id": "stance_stop_and_see_what_comes_back", + "triggers": ["always the one who texts", "i always reach out", "always me who plans", "cancels on me again", "one-sided", "never initiates"], + "line": "When one person does all the reaching, I think it is fair to stop for a while and see what comes back; that is a way of finding out, not a punishment.", + }, + { + "id": "stance_the_small_step_that_happens", + "triggers": ["overwhelmed", "don't know where to start", "keep putting it off", "procrastinating", "too much to do", "can't get started"], + "line": "I'd pick the small step that will certainly happen today over the right-sized one that keeps not happening; the small one changes what tomorrow starts from.", + }, + { + "id": "stance_anger_is_information", + "triggers": ["so angry", "mad at them", "shouldn't be this angry", "furious", "still mad", "resent"], + "line": "I think anger after being hurt is usually information about a line that got crossed, and it is worth reading before it is argued away.", + }, + { + "id": "stance_decide_with_what_is_known", + "triggers": ["can't decide", "what if i'm wrong", "waiting until i'm sure", "keep going back and forth", "overthinking this decision"], + "line": "I'd rather decide with what is known now and correct it later than wait for a certainty that is not coming; most choices can be adjusted once they are made.", + }, + { + "id": "stance_same_rules_as_for_a_friend", + "triggers": ["so hard on myself", "should have known better", "i'm so stupid", "my own fault", "can't forgive myself", "beating myself up"], + "line": "I think the rules you would use for a friend are the fair ones to use on yourself; if you would not say it to them, I don't think it is a fair thing to say to you.", + }, + { + "id": "stance_specific_praise", + "triggers": ["they said good job", "nobody noticed", "want to thank them", "how do i compliment", "give feedback to", "tell them it was good"], + "line": "I lean toward saying exactly what was good over saying that something was great; the specific version is the one a person can use again.", + }, + { + "id": "stance_a_limit_said_once", + "triggers": ["set a boundary", "keep saying yes", "can't say no", "they keep asking me", "taken advantage of", "people pleaser"], + "line": "I think a limit said once, plainly, with no apology attached, does more than the same limit hinted at ten times; the hint lets everyone pretend it was not said.", + }, +] + +# Ids Jack has approved (all twelve, 2026-11-27). An entry whose id is not listed here is a draft and is never used. +APPROVED_IDS = ( + "stance_a_no_is_about_the_place", + "stance_say_the_need_plainly", + "stance_one_message_is_thin_evidence", + "stance_rest_is_part_of_the_work", + "stance_an_apology_names_the_thing", + "stance_stop_and_see_what_comes_back", + "stance_the_small_step_that_happens", + "stance_anger_is_information", + "stance_decide_with_what_is_known", + "stance_same_rules_as_for_a_friend", + "stance_specific_praise", + "stance_a_limit_said_once", +) diff --git a/backend/models/models.py b/backend/models/models.py index f828001..0232eaa 100644 --- a/backend/models/models.py +++ b/backend/models/models.py @@ -511,6 +511,21 @@ def get_haiku_stream_llm(username: str): return _lite_stream_llms[name] +def get_top_stream_llm(username: str): + """The Claude Sonnet model that writes the few top-stakes replies (backend/utils/top_tier.py), or None for the embedded view or a server that does not offer Sonnet (no key, or no price in + LLM_PRICES, so its spend could not be counted). Set up like the Haiku voice; the standard reply model is its fallback.""" + if username in ("guest_bty",) or not sonnet_available(): + return None + from backend.models import claude_llm + + name = claude_llm.SONNET_MODEL + if name not in _lite_stream_llms: + _lite_stream_llms[name] = claude_llm.ClaudeLLM( + model_name=name, fallback=stream_llm, effort="low", thinking_off=True, max_tokens=2000, voice_shape=True, voice_tail="voice", + ) + return _lite_stream_llms[name] + + def lite_prompt(prompt: str, llm: object) -> str: """The prompt for a lite reply. A Claude model reshapes it itself (system prompt, closing reminder); a Gemini lite model reads the same flat prompt with the check-in reminder added last when a check-in is due (the eval's `checkin` shape: backend/utils/claude_voice.with_tail). Nothing changes for the standard voice.""" diff --git a/backend/tests/test_low_moves.py b/backend/tests/test_low_moves.py index 99949a0..adc9d89 100644 --- a/backend/tests/test_low_moves.py +++ b/backend/tests/test_low_moves.py @@ -68,16 +68,17 @@ def test_a_pattern_needs_two_shared_words(): def test_company_offers_what_they_like_when_they_want_to_be_heard_never_a_sensitive_interest(): - move = _choose("today just sucked", interests=["drinking with friends", "learning guitar", "Elden Ring"]) + move = _choose("today just sucked", mood=_mood(need="distraction"), interests=["drinking with friends", "learning guitar", "Elden Ring"]) assert move == {"kind": "company", "items": ["learning guitar", "Elden Ring"]} assert _choose("today just sucked", mood=_mood(need="solving")) is None # they want help with something concrete + assert _choose("today just sucked") is None # 2026-11-27: someone venting is no longer offered "want to...?" (16 of 18 moves, ignored) def test_company_never_offers_a_plan_or_an_appointment_only_something_they_do(): real_shapes = ["The user engages in strength training exercises including shoulder presses and bicep curls.", "The user plans to build a dedicated portfolio website to showcase their projects.", "The user has a planned visit with Kelsey on November 20, 2026, and a significant meeting on November 24, 2026."] - assert _choose("today just sucked", interests=real_shapes) == {"kind": "company", "items": [real_shapes[0]]} + assert _choose("today just sucked", mood=_mood(need="distraction"), interests=real_shapes) == {"kind": "company", "items": [real_shapes[0]]} def test_the_same_kind_is_not_used_again_within_the_gap_and_comes_back_after_it(): diff --git a/backend/tests/test_memory_erase.py b/backend/tests/test_memory_erase.py index a9c0ee8..dc8e595 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", "shared_moments"} + 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", "sonic_said_views", "what_lands"} 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_own_voice.py b/backend/tests/test_own_voice.py new file mode 100644 index 0000000..0a52de6 --- /dev/null +++ b/backend/tests/test_own_voice.py @@ -0,0 +1,353 @@ +"""Sonic having something of its own to say in personal talk, and reading the moment better (the 2026-11-27 entityhood work): +a view when asked (view_check), stances (stances), remembering its views (own_views), bringing up its reading unasked (volunteer), what lands with a person (what_lands), what a message is +doing (message_doing), the capped stronger voice (top_tier), and the changes to the low moves and the "just listen" mode. Every message below is made up.""" +from datetime import datetime, timedelta, timezone +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from backend.components import sonic_stances +from backend.tests.fake_runner_db import FakeDB +from backend.utils import (emotion_checks, low_moves, memory_erase, message_doing, own_views, people_notes, placement, reply_stamp, revision_reasons, self_counters, stances, support_choice, top_tier, + view_check, volunteer, what_lands) +from backend.utils.time_utils import SENT_AT_KEY + +ROOT = Path(__file__).resolve().parents[2] +APP = (ROOT / "app.py").read_text(encoding="utf-8") +NOW = datetime.now(timezone.utc) + + +def _msg(kind, text="ok", hours_ago=0.0, **marks): + return SimpleNamespace(type=kind, content=text, additional_kwargs={SENT_AT_KEY: (NOW - timedelta(hours=hours_ago)).isoformat(), **marks}) + + +def _mood(valence="low", need="venting", lift=False, read=True): + return {"valence": valence, "need": need, "intensity": 0.8, "read_this_turn": read, "lift_this_turn": lift} + + +# ---- a view when asked ---------------------------------------------------------------------------------------------------------------------- + +@pytest.mark.parametrize("message", ["what do you think I should do about it", "am I overreacting?", "should I text her back tonight", "be honest, was I wrong to say that", "is it weird that I still care", + "what’s your take on this"]) +def test_a_message_that_asks_for_its_view_is_read_as_one(message): + assert view_check.asks_for_view(message) is True + + +@pytest.mark.parametrize("message", ["she cancelled on me again", "today was long", "what do you think about being an AI", "do you think you'll remember this tomorrow", ""]) +def test_a_message_that_does_not_ask_for_a_view_of_their_situation_is_not(message): + assert view_check.asks_for_view(message) is False + + +def test_a_reply_that_opens_with_feelings_or_hands_the_question_back_is_sent_back_and_one_that_answers_is_not(): + asked = "am I overreacting about her cancelling?" + assert view_check.issue(asked, "That is a lot to sit with. It makes sense that it stings. What does your gut say?") == "no_view" + assert view_check.issue(asked, "I don't think you are. Three cancellations in a month is a pattern, not a slip.") is None + assert view_check.issue(asked, "I think it is fair to be annoyed, but it's really up to you how to read it.") == "no_view" # states one, then hands it back + late = "That is a lot. She has done this before. You told me about March. And the week after. I think you are right." + assert view_check.issue(asked, late) == "no_view" # the view has to be in the opening, not the fifth sentence + assert view_check.issue("she cancelled again", "That is a lot to sit with.") is None # nobody asked + assert view_check.issue(asked, "") is None + + +def test_the_view_sentence_is_the_first_that_states_one_and_is_cut_short(): + assert view_check.view_sentence("Thank you for telling me. I'd wait a day before answering. It gives you room.") == "I'd wait a day before answering." + assert view_check.view_sentence("Thank you for telling me. That is hard.") is None + assert len(view_check.view_sentence("I think " + "really " * 80 + "so.")) == view_check.MAX_VIEW_CHARS + assert view_check.states_view("No, that was not out of line.") and not view_check.states_view("It sounds like a hard week.") + + +def test_the_block_says_to_answer_first_and_the_reach_dial_decides_how_plainly_it_disagrees(): + assert "Answer that first" in view_check.build_block("default") and "say so once, plainly" in view_check.build_block("default") + assert "say so once, gently" in view_check.build_block("low") + assert "see it differently" not in view_check.build_block("none") and "Answer that first" in view_check.build_block("none") # they asked, so they still get the view + + +def test_the_rewrite_reason_exists_on_every_end(): + prompt, reason = emotion_checks.build_emotional_revision_prompt("P", "draft", "no_view") + assert prompt.startswith("P") and "they asked what you think" in reason + assert "no_view" in revision_reasons.REASONS and revision_reasons.reason_for("no_view") == "no_view" and "revised_reason_no_view" in self_counters.KEYS + assert "no_view:" in (ROOT / "local" / "src" / "components" / "traceFacts.ts").read_text(encoding="utf-8") + assert "view_issue = None if (safety_plan.active or not view_asked) else view_check.issue(" in APP and "revision_tag = view_issue" in APP + assert 'if view_asked and emotional_issue == "venting_advice":\n emotional_issue = None' in APP + + +# ---- stances -------------------------------------------------------------------------------------------------------------------------------- + +def test_the_shipped_stances_are_well_formed_views_and_only_an_approved_one_is_live(): + assert stances.check_registry() == [] and len(sonic_stances.STANCES) >= 10 + assert set(sonic_stances.APPROVED_IDS) <= {entry["id"] for entry in sonic_stances.STANCES} and len(set(sonic_stances.APPROVED_IDS)) == len(sonic_stances.APPROVED_IDS) + assert [entry["id"] for entry in stances.approved()] == [entry["id"] for entry in sonic_stances.STANCES if entry["id"] in sonic_stances.APPROVED_IDS] + assert stances.approved(approved_ids=()) == [] # with nothing approved, nothing is live + draft = {"id": "stance_a_new_draft", "triggers": ["x"], "line": "I think a draft is a draft until someone approves it."} + assert draft["id"] not in [entry["id"] for entry in stances.approved(sonic_stances.STANCES + [draft])] # a new entry stays a draft + from backend.utils.identity_checks import identity_reply_issue + for entry in sonic_stances.STANCES: + assert identity_reply_issue(entry["line"]) is None, entry["id"] # a view, never a claimed feeling or a past of its own + + +def test_a_stance_is_chosen_only_when_a_view_is_wanted_by_a_phrase_or_by_meaning(): + pool = stances.approved(approved_ids=("stance_rest_is_part_of_the_work", "stance_anger_is_information")) + assert [e["id"] for e in pool] == ["stance_rest_is_part_of_the_work", "stance_anger_is_information"] + assert stances.select("I took a day off and feel like I wasted the day", wanted=True, entries=pool)["id"] == "stance_rest_is_part_of_the_work" + assert stances.select("I took a day off and feel like I wasted the day", wanted=False, entries=pool) is None + assert stances.select("the weather is nice", wanted=True, entries=pool) is None + near = stances.select("something with no phrase in it", wanted=True, entries=pool, vector=[1.0, 0.0], vectors={"stance_anger_is_information": [1.0, 0.0], "stance_rest_is_part_of_the_work": [0.0, 1.0]}) + assert near["id"] == "stance_anger_is_information" and near["match"] == "meaning" + assert stances.select("something with no phrase in it", wanted=True, entries=pool, vector=[1.0, 0.0], vectors={"stance_anger_is_information": [0.0, 1.0]}) is None + assert stances.select("I wasted the day", wanted=True, entries=[]) is None + + +def test_the_registry_check_refuses_a_rule_a_feeling_a_bad_id_and_an_approval_with_no_entry(): + good = {"id": "stance_made_up_one", "triggers": ["x"], "line": "I think a made-up thing is fine because it is made up."} + assert stances.check_registry([good], ()) == [] + assert any("tells the person what to do" in p for p in stances.check_registry([{**good, "line": "I think you should rest more often than you do."}], ())) + assert any("must open as a view" in p for p in stances.check_registry([{**good, "line": "Rest matters a great deal to everyone."}], ())) + assert any("claims a feeling" in p for p in stances.check_registry([{**good, "line": "I think rest matters, and I remember learning that."}], ())) + assert any("the id must be" in p for p in stances.check_registry([{**good, "id": "rest"}], ())) + assert any("used twice" in p for p in stances.check_registry([good, good], ())) + assert any("no such stance" in p for p in stances.check_registry([good], ("stance_missing",))) + assert any("trigger" in p for p in stances.check_registry([{**good, "triggers": []}], ())) + + +def test_a_stance_is_offered_as_its_own_view_and_counted_as_used_only_when_the_reply_shares_its_words(): + entry = {"id": "stance_rest_is_part_of_the_work", "line": "I think rest is part of the work and not time taken from it; a plan that only holds if you never stop is a plan with a flaw in it."} + block = stances.build_block(entry) + assert entry["line"] in block and "A VIEW YOU HOLD" in block and "not a rule for them" in block and stances.build_block(None) == "" + assert stances.used("I think the rest was part of the work, not a break from it.", entry) is True + assert stances.used("That sounds like a long day.", entry) is False and stances.used("anything", None) is False + assert stances.is_stance(entry) and not stances.is_stance({"id": "take_x"}) + + +# ---- remembering what it said it thinks ------------------------------------------------------------------------------------------------------ + +def test_a_stated_view_is_kept_for_the_person_once_and_only_the_sentence(): + db = FakeDB() + reply = "Thank you for telling me. I think waiting until Friday before answering the landlord is reasonable. He has been slow before." + assert own_views.note(db, "sam", "should I answer the landlord about the deposit now", reply, NOW) is True + kept = db[own_views.COLLECTION].find({"username": "sam"}) + assert len(kept) == 1 and kept[0]["text"] == "I think waiting until Friday before answering the landlord is reasonable." + assert "deposit" in kept[0]["words"] and "landlord" in kept[0]["words"] and "should I answer" not in str(kept[0]) # words as a bag, never their message + assert own_views.note(db, "sam", "should I answer the landlord about the deposit now", reply, NOW) is False and len(db[own_views.COLLECTION].find({})) == 1 + assert own_views.note(db, "sam", "today was long", "That sounds like a long day.", NOW) is False # no view, nothing kept + assert own_views.note(None, "sam", "x", reply, NOW) is False and own_views.note(db, "", "x", reply, NOW) is False + + +def test_only_the_newest_views_are_kept_past_the_limit(monkeypatch): + monkeypatch.setattr(own_views, "MAX_PER_PERSON", 3) + db = FakeDB() + for n in range(5): + own_views.note(db, "sam", f"should I move the meeting number {n} for the committee", f"I think moving meeting number {n} for the committee is fine.", NOW - timedelta(hours=10 - n)) + texts = sorted(doc["text"] for doc in db[own_views.COLLECTION].find({"username": "sam"})) + assert texts == [f"I think moving meeting number {n} for the committee is fine." for n in (2, 3, 4)] + + +def test_a_kept_view_comes_back_when_the_message_shares_enough_words_and_it_is_not_from_this_sitting(): + db = FakeDB() + own_views.note(db, "sam", "should I answer the landlord about the deposit now", "I think waiting until Friday before answering the landlord is reasonable.", NOW - timedelta(days=3)) + found = own_views.recall(db, "sam", "the landlord wrote again about the deposit, should I answer before Friday", NOW) + assert found and found["text"].startswith("I think waiting until Friday") + assert own_views.recall(db, "sam", "what should I cook tonight", NOW) is None + assert own_views.recall(db, "someone_else", "the landlord wrote again about the deposit, should I answer before Friday", NOW) is None # one person's, never another's + own_views.note(db, "kim", "should I answer the landlord about the deposit now", "I think waiting until Friday before answering the landlord is reasonable.", NOW - timedelta(hours=1)) + assert own_views.recall(db, "kim", "the landlord wrote again about the deposit, should I answer before Friday", NOW) is None # said an hour ago: this sitting + block = own_views.build_block(found) + assert found["text"] in block and "stand by it" in block and "I'd put it differently now" in block and (NOW - timedelta(days=3)).strftime("%B") in block + assert own_views.build_block(None) == "" + + +def test_the_kept_views_and_the_numbers_are_erased_with_everything_else_of_theirs(): + assert own_views.COLLECTION in memory_erase.ERASED_COLLECTIONS and what_lands.COLLECTION in memory_erase.ERASED_COLLECTIONS + + +# ---- bringing up its own reading unasked ----------------------------------------------------------------------------------------------------- + +OPEN = dict(source_type="conversational", risk_active=False, energy_tier="open", closing=False, proactive_taken=False, offers_allowed=True, reach="default") + + +def test_it_may_only_at_an_open_moment_and_at_most_once_a_day(): + quiet = [_msg("human", "made it home"), _msg("ai", "good", hours_ago=30)] + assert volunteer.may("made it home, long day", quiet, now=NOW, **OPEN) is True + for change in ({"source_type": "tool_output"}, {"risk_active": True}, {"energy_tier": "subdued"}, {"closing": True}, {"proactive_taken": True}, {"offers_allowed": False}, {"reach": "none"}): + assert volunteer.may("made it home, long day", quiet, now=NOW, **{**OPEN, **change}) is False, change + assert volunteer.may("can you look at this?", quiet, now=NOW, **OPEN) is False # they asked something + assert volunteer.may("word " * 31, quiet, now=NOW, **OPEN) is False # a long message is not a pause + assert volunteer.may("", quiet, now=NOW, **OPEN) is False + recent = [_msg("ai", "x", hours_ago=19, volunteered="take_a")] + assert volunteer.may("made it home", recent, now=NOW, **OPEN) is False + assert volunteer.may("made it home", [_msg("ai", "x", hours_ago=21, volunteered="take_a")], now=NOW, **OPEN) is True + undated = SimpleNamespace(type="ai", content="x", additional_kwargs={"volunteered": "take_a"}) + assert volunteer.recently([undated], NOW) is True # an unknown time is never guessed to be old + + +def test_a_take_the_conversation_has_heard_is_not_said_again_and_the_words_are_placed_last(): + takes = [{"id": "take_a", "line": "I read a piece on a."}, {"id": "take_b", "line": "I read a piece on b."}] + heard = [_msg("ai", "x", hours_ago=50, volunteered="take_a")] + assert volunteer.pick(takes, heard)["id"] == "take_b" and volunteer.pick(takes, [])["id"] == "take_a" + assert volunteer.pick(takes, heard + [_msg("ai", "y", hours_ago=25, volunteered="take_b")]) is None and volunteer.pick([], []) is None + words = volunteer.spoken(takes[1]) + assert words == "Something from my own reading, apart from all this: I read a piece on b." + assert placement.at_end("First part.\n\nSecond part.", words) == "First part.\n\nSecond part.\n\n" + words + tagged = placement.at_end("Only part.\n\n<<>>", words) + assert tagged == "Only part.\n\n" + words + "\n\n<<>>" + assert placement.at_end("Has it. " + words, words) == "Has it. " + words and placement.at_end("", words) == "" and placement.at_end("x", "") == "x" + + +# ---- what lands ----------------------------------------------------------------------------------------------------------------------------- + +def test_a_reply_is_marked_with_what_it_did_and_the_next_message_says_how_it_went(): + assert what_lands.kinds_of(low_move="push_back", view=True, question=True) == ["push_back", "view", "question"] + assert what_lands.kinds_of(low_move="not_a_kind") == [] and what_lands.kinds_of(story=True, record=True, stance=True) == ["stance", "story", "record"] + marked = [_msg("ai", "x", move_kinds=["read", "question", "nonsense"]), _msg("human", "y")] + assert what_lands.last_reply_kinds(marked) == ["read", "question"] and what_lands.last_reply_kinds([_msg("human", "y")]) == [] + assert what_lands.outcome({"lift_this_turn": True}, "ok", False) == "lift" + assert what_lands.outcome({}, "one two three four five six seven eight", False) == "engaged" + assert what_lands.outcome({}, "one two three four five six seven eight", True) == "flat" and what_lands.outcome({}, "ok thanks", False) == "flat" + + +def test_the_numbers_are_kept_per_person_and_order_the_kinds_once_there_is_enough_to_go_on(): + db = FakeDB() + for _ in range(4): + assert what_lands.record(db, "sam", ["read", "question"], "lift") is True + what_lands.record(db, "sam", ["push_back"], "flat") + what_lands.record(db, "sam", ["pattern"], "engaged") + stats = what_lands.load(db, "sam") + assert stats["read"] == {"tries": 4, "lifts": 4, "engaged": 4} and stats["push_back"] == {"tries": 4} and stats["pattern"] == {"tries": 1, "engaged": 1} + assert what_lands.load(db, "someone_else") == {} and what_lands.load(None, "sam") == {} + assert what_lands.rate(stats["read"]) == 1.0 and what_lands.rate(stats["push_back"]) == 0.0 and what_lands.rate(stats["pattern"]) is None # one try says nothing yet + assert what_lands.order(stats, low_moves.KINDS) == ["read", "pattern", "company", "push_back"] # helped first, then the untried in their own order, the never-helped last + assert what_lands.order({}, low_moves.KINDS) == list(low_moves.KINDS) + assert what_lands.record(db, "sam", ["nonsense"], "lift") is False and what_lands.record(db, "sam", ["read"], "nonsense") is False and what_lands.record(db, "", ["read"], "lift") is False + + +# ---- what a message is doing ---------------------------------------------------------------------------------------------------------------- + +@pytest.mark.parametrize("message, expected", [ + ("lol of course she cancelled again", "joking"), + ("ok I'm going to bed, long day", "winding_down"), + ("did I do the right thing", None), + ("did I do the right thing?", "asking"), + ("she finally texted back", "news"), + ("I just got the email and they said no", "news"), + ("everything feels heavy", None), + ("today was long and grey", None), # a time word with nothing that happened is not news + ("she said it would be fine", None), # nor is something said with no "just now" to it + ("", None), +]) +def test_what_a_message_is_doing_is_read_from_its_own_words(message, expected): + assert message_doing.kind(message) == expected + + +def test_the_first_reading_that_applies_wins_and_each_gets_one_line(): + assert message_doing.kind("haha should I even bother?") == "joking" # a joke with a question in it is met as a joke + assert message_doing.kind("going to bed, did she text you?") == "asking" # a question keeps them here: not winding down + assert message_doing.kind("going to bed " + "word " * 40) is None # a long message is not a goodnight + assert "Answer it in your first sentence" in message_doing.build_block("asking") and "ask nothing" in message_doing.build_block("winding_down") + assert "Meet the joke first" in message_doing.build_block("joking") and "Respond to the news itself first" in message_doing.build_block("news") + assert message_doing.build_block(None) == "" and message_doing.build_block("nonsense") == "" + assert self_counters._GROUPS["doing"] == message_doing.KINDS and "doing_news" in self_counters.KEYS + + +# ---- the capped stronger voice --------------------------------------------------------------------------------------------------------------- + +def test_the_stronger_voice_is_off_unless_switched_on(monkeypatch): + monkeypatch.delenv("REPLY_TOP_TIER", raising=False) + assert top_tier.enabled() is False and top_tier.wanted("emotional", 0.9, risk_active=False, used=0, guest=False) is False + monkeypatch.setenv("REPLY_TOP_TIER", "on") + assert top_tier.enabled() is True and top_tier.wanted("emotional", 0.9, risk_active=False, used=0, guest=False) is True + + +def test_when_on_it_is_only_for_a_strong_feeling_under_the_daily_cap_and_never_in_a_safety_context(): + yes = dict(risk_active=False, used=0, guest=False, on=True, cap=2) + assert top_tier.wanted("emotional", 0.6, **yes) is True and top_tier.wanted("checkin", 0.7, **yes) is True + assert top_tier.wanted("emotional", 0.59, **yes) is False and top_tier.wanted("companion", 0.9, **yes) is False and top_tier.wanted("safety", 0.9, **yes) is False + assert top_tier.wanted("emotional", 0.9, **{**yes, "risk_active": True}) is False and top_tier.wanted("emotional", 0.9, **{**yes, "guest": True}) is False + assert top_tier.wanted("emotional", 0.9, **{**yes, "used": 2}) is False and top_tier.wanted("emotional", 0.9, **{**yes, "used": 1}) is True + assert top_tier.wanted("emotional", 0.9, **{**yes, "on": False}) is False + + +def test_the_days_use_is_counted_from_the_saved_stamps_and_the_stamp_knows_the_voice(): + stamp = reply_stamp.build(top_tier.TIER, "haiku_setting", "haiku") + assert stamp["tier"] == "sonnet" and stamp["label"] == "sonnet" and reply_stamp.clean(stamp)["label"] == "sonnet" + other = reply_stamp.build("haiku", "haiku_setting", "haiku") + messages = [_msg("ai", "a", hours_ago=2, voice=stamp), _msg("ai", "b", hours_ago=23, voice=stamp), _msg("ai", "c", hours_ago=25, voice=stamp), _msg("ai", "d", hours_ago=1, voice=other), + _msg("human", "e", hours_ago=1, voice=stamp)] + assert top_tier.used_today(messages, NOW) == 2 + assert top_tier.used_today([SimpleNamespace(type="ai", content="x", additional_kwargs={"voice": stamp})], NOW) == 1 # no time on it: counted + + +# ---- the low moves and "just listen" --------------------------------------------------------------------------------------------------------- + +LONG_VENT = "she said she would call after work and then nothing all evening and I just sat there waiting" + + +def _choose(message, mood=None, **extra): + return low_moves.choose(message, mood or _mood(), facts=extra.pop("facts", []), interests=extra.pop("interests", ["learning guitar"]), recent_messages=extra.pop("recent", []), + risk_active=False, closing=False, **extra) + + +def test_its_own_read_is_a_move_for_someone_venting_at_length_and_not_while_just_listening_or_with_the_dial_at_none(): + assert _choose(LONG_VENT) == {"kind": "read", "items": []} + assert _choose("today just sucked") is None # too little to have a read of + assert _choose(LONG_VENT, support_mode="listen") is None and _choose(LONG_VENT, reach="none") is None + assert _choose(LONG_VENT, mood=_mood(need="reassurance")) is None and _choose(LONG_VENT, mood=_mood(need="solving")) is None + assert _choose(LONG_VENT, recent=[SimpleNamespace(type="ai", content="x", additional_kwargs={low_moves.MOVE_MARK: "read"})]) is None # not twice in a row + block = low_moves.build_block({"kind": "read", "items": []}) + assert "YOUR OWN READ" in block and "It is not advice" in block and "{items}" not in block + assert "low_move_read" in self_counters.KEYS + + +def test_company_is_never_offered_while_just_listening_and_the_persons_own_order_wins(): + wants_out = _mood(need="distraction") + assert _choose("today just sucked", mood=wants_out)["kind"] == "company" and _choose("today just sucked", mood=wants_out, support_mode="listen") is None + pattern_fact = {"fact": "Tends to wait by the phone all evening after a promised call", "source": "pattern", "active": True} + assert _choose(LONG_VENT, facts=[pattern_fact])["kind"] == "pattern" # the default order: a pattern before a read + assert _choose(LONG_VENT, facts=[pattern_fact], prefer=["read", "pattern"])["kind"] == "read" + assert _choose(LONG_VENT, facts=[pattern_fact], prefer=["company", "push_back"])["kind"] == "pattern" # a preferred kind that is not available changes nothing + assert set(low_moves.available(LONG_VENT, _mood(), facts=[pattern_fact], interests=[], recent_messages=[], risk_active=False, closing=False)) == {"pattern", "read"} + + +@pytest.mark.parametrize("message", ["I'm the problem, clearly", "im just too much for people", "no one could love me", "everyone leaves eventually", "I deserve this", "I never get anything right"]) +def test_more_ways_of_being_hard_on_themselves_are_read_as_that(message): + assert low_moves.harsh_about_self(message) is True + assert low_moves.harsh_about_self("she said I was too much trouble to visit") is False + + +def test_just_listen_ends_after_a_stretch_and_steps_aside_when_they_ask_what_it_thinks(): + pick = _msg("human", "Just listen", hours_ago=1, **{support_choice.MODE_MARK: "listen"}) + during = [pick] + [_msg("human", f"more {n}") for n in range(support_choice.LISTEN_TURNS)] + assert support_choice.current_mode(during, NOW) == "listen" + assert support_choice.current_mode(during + [_msg("human", "and one more")], NOW) is None + assert support_choice.current_mode([pick, _msg("ai", "ok"), _msg("human", "am I overreacting?")], NOW) is None + assert support_choice.current_mode([pick, _msg("human", "am I overreacting?"), _msg("ai", "no"), _msg("human", "ok. she also said")], NOW) == "listen" # only for the message that asks + advice = _msg("human", "Advice", hours_ago=1, **{support_choice.MODE_MARK: "advice"}) + assert support_choice.current_mode([advice] + [_msg("human", f"more {n}") for n in range(30)], NOW) == "advice" # only "just listen" is cut short + assert support_choice.current_mode([_msg("human", "Just listen", hours_ago=7, **{support_choice.MODE_MARK: "listen"})], NOW) is None + assert "Listening is not saying nothing" in support_choice.mode_block("listen") and "No advice" in support_choice.mode_block("listen") + + +# ---- counting and wiring --------------------------------------------------------------------------------------------------------------------- + +def test_a_people_note_counts_as_used_only_when_the_reply_shares_its_words(): + note = {"id": "made_up", "pattern": "People often replay the conversation for days afterwards", "helps": "Naming the one sentence they keep returning to"} + assert people_notes.used("It sounds like one sentence keeps returning: the one about naming the budget.", [note]) is True + assert people_notes.used("That is a long week.", [note]) is False and people_notes.used("anything", []) is False + + +def test_every_new_counter_is_registered_and_counted_in_the_app(): + keys = {"view_asked", "view_stated", "view_handed_back", "own_view_kept", "own_view_recalled", "stance_offered", "stance_used", "volunteer_placed", "lands_recorded", "lands_lift", "lands_ordered", + "reply_top_tier_used", "people_notes_used"} + assert keys <= self_counters.KEYS + for key in keys: + assert f'tally(turn_counts, "{key}")' in APP, key + assert 'tally(turn_counts, "doing", _doing)' in APP + + +def test_the_app_keeps_the_new_things_out_of_safety_turns_and_counts_them_as_bringing_something_up(): + assert "view_wanted = source_type == \"conversational\" and risk_level == RISK_NONE and not is_closing_message(question)" in APP + assert "message_doing.kind(_their_words) if (view_wanted and emotional_context and not safety_plan.active) else None" in APP + assert "if (not placed_own and not safety_plan.active and not is_guest_username(username) and get_db() is not None and volunteer.may(" in APP + assert "or low_move or step_back_entry or stance_entry or volunteer_take or view_asked or llm_turn.experience_item or llm_turn.shape_offered" in APP + assert 'energy_tier="open" if own_tier == "open" else energy_tier(' in APP + assert "support_mode=support_choice_utils.current_mode(chat_sessions[history_key]), reach=reach_level.level, prefer=_move_order," in APP + assert "top_tier.wanted(reply_stakes, effective_intensity(" in APP and "risk_active=risk_level != RISK_NONE,\n used=top_tier.used_today(" in APP diff --git a/backend/tests/test_reply_tier.py b/backend/tests/test_reply_tier.py index e1cf647..9fc1551 100644 --- a/backend/tests/test_reply_tier.py +++ b/backend/tests/test_reply_tier.py @@ -118,7 +118,7 @@ def test_the_reasons_are_the_counter_keys_and_the_turn_counts_the_one_that_appli self_counters.tally(counts, "reply_tier", "something else") # an unknown word is dropped, never recorded assert {k: v for k, v in counts.items() if k.startswith("reply_tier")} == {"reply_tier_auto_plain": 1} start = APP.index("tier, tier_reason = reply_tier.pick(") - assert 'tally(turn_counts, "reply_tier", tier_reason)' in APP[start: start + 1500] + assert 'tally(turn_counts, "reply_tier", tier_reason)' in APP[start: start + 2600] def test_how_much_a_turn_matters_is_read_whatever_the_setting_and_counted_and_stamped(): @@ -318,7 +318,7 @@ def test_the_app_takes_the_guests_choice_from_the_request_and_never_runs_lite_fo assert "reply_model: Optional[str] = None" in APP assert 'reply_choice = reply_choice_for_turn(username, _settings.get("reply_model"), request.reply_model, lite_reply_available(), haiku_reply_available())' in APP start = APP.index("tier, tier_reason = reply_tier.pick(") - block = APP[start: start + 1100] + block = APP[start: start + 2400] assert "risk_active=risk_level != RISK_NONE" in block and "turn_llm = lite_voice" in block and "prompt = lite_prompt(prompt, lite_voice)" in block and "R_NOT_OFFERED" in block assert "get_haiku_stream_llm(username) if tier == reply_tier.HAIKU else get_lite_stream_llm(username)" in block # each choice runs its own model diff --git a/backend/tests/test_saved_marks.py b/backend/tests/test_saved_marks.py new file mode 100644 index 0000000..cd2e727 --- /dev/null +++ b/backend/tests/test_saved_marks.py @@ -0,0 +1,47 @@ +"""The marks a reply carries for later turns are saved with the conversation and come back after a restart (backend/utils/app_utils.py SAVED_MARKS). + +Why (2026-11-27): only the support card's marks were saved, so every spacing rule that reads a mark (one joke a conversation, the gap between relatable lines, low moves and shared moments) and the +step-back answer capture started from nothing whenever the server restarted. The text below is made up.""" +from langchain_core.messages import AIMessage, HumanMessage + +from backend.utils import app_utils as au + + +def _round_trip(message): + return au._deserialize_messages(au._serialize_messages([message]))[0] + + +def test_every_mark_a_later_turn_reads_is_on_the_saved_list(): + from backend.utils import (clarifications, code_outcomes, curiosity, emotion_checkin, encouragement_utils, experience_capture, experiences, jokes, low_moves, reading_shelf, recurring_struggles, + relatable_utils, self_history_utils, shared_history, shared_moments, view_check, volunteer, what_lands) + names = { + relatable_utils.RELATABLE_MARK, encouragement_utils.ENCOURAGEMENT_MARK, shared_history.CALLBACK_MARK, recurring_struggles.STEP_BACK_MARK, low_moves.MOVE_MARK, shared_moments.MARK, + emotion_checkin.CHECKIN_MARK, curiosity.CURIOSITY_MARK, reading_shelf.SHELF_MARK, code_outcomes.CODE_MARK, code_outcomes.LEANINGS_MARK, experience_capture.UNTRUSTED_MARK, + experiences.EXPERIENCE_MARK, jokes.JOKE_MARK, clarifications.CLARIFY_MARK, self_history_utils.SELF_HISTORY_MARK, view_check.VIEW_MARK, volunteer.MARK, what_lands.MARK, + } + assert names == set(au.SAVED_MARKS) + + +def test_a_mark_survives_being_saved_and_loaded(): + reply = AIMessage(content="made up", additional_kwargs={"joke_told": True, "low_move": "push_back", "step_back_asked": "a person", "leanings_used": ["keep_to_the_ask", "say_the_cause"]}) + back = _round_trip(reply) + assert back.additional_kwargs["joke_told"] is True and back.additional_kwargs["low_move"] == "push_back" and back.additional_kwargs["step_back_asked"] == "a person" + assert back.additional_kwargs["leanings_used"] == ["keep_to_the_ask", "say_the_cause"] + assert "relatable_offered" not in back.additional_kwargs # a mark that was not set is not invented + + +def test_the_spacing_rules_still_hold_after_a_reload(): + from backend.utils import low_moves + from backend.utils.relatable_utils import recently_offered + + saved = au._serialize_messages([HumanMessage(content="made up"), AIMessage(content="made up", additional_kwargs={"relatable_offered": True, "low_move": "company"})]) + loaded = au._deserialize_messages(saved) + assert recently_offered(loaded) is True and low_moves.recent_kinds(loaded) == {"company"} + + +def test_only_a_mark_on_the_list_and_only_a_plain_value_is_saved(): + reply = AIMessage(content="made up", additional_kwargs={"joke_told": {"anything": 1}, "low_move": "x" * 500, "not_a_mark": True, "code_turn": 1, "leanings_used": [3, "", "ok"]}) + entry = au._serialize_messages([reply])[0] + assert "joke_told" not in entry and "not_a_mark" not in entry and "code_turn" not in entry and entry["low_move"] == "x" * 120 and entry["leanings_used"] == ["ok"] + assert au.clean_mark(True) is True and au.clean_mark(False) is None and au.clean_mark("") is None and au.clean_mark([]) is None and au.clean_mark(None) is None + assert len(au.clean_mark(["a"] * 40)) == 12 diff --git a/backend/utils/app_utils.py b/backend/utils/app_utils.py index 8a75692..b98a9ef 100644 --- a/backend/utils/app_utils.py +++ b/backend/utils/app_utils.py @@ -52,6 +52,31 @@ def _get_conversations_file_path(username: str) -> str: return os.path.join(CONVERSATIONS_DIR, f"{username}.json") +# THE MARKS A REPLY CARRIES FOR LATER TURNS. Each says "this reply did X" (told a joke, offered a line of its own, asked the step-back question, was a coding reply), and a later turn reads it to +# space things out or to know what the next message answers. They lived only in this process's copy of the conversation: nothing saved them, so after a restart "one joke a conversation", the gap +# between relatable lines, low moves and shared moments, and "the next message is their answer" all started again from nothing (found 2026-11-27: none of the last 400 saved replies carried one). +# Literal names, so this module imports none of theirs; backend/tests/test_saved_marks.py holds each to its module's constant. +SAVED_MARKS = ( + "relatable_offered", "encouragement_offered", "callback_offered", "step_back_asked", "low_move", "shared_moment", "emotion_checkin", "curiosity_offered", "shelf_offered", + "code_turn", "leanings_used", "untrusted_content", "experience_cited", "joke_told", "clarify_offered", "self_history_offered", + "view_stated", "volunteered", "move_kinds", +) +_MARK_TEXT_MAX = 120 +_MARK_LIST_MAX = 12 + + +def clean_mark(value: Any) -> Any: + """A mark's value as it may be saved and read back: True, a short string, or a short list of short strings; None for anything else (so nothing unexpected is ever written). Pure.""" + if value is True: + return True + if isinstance(value, str) and value.strip(): + return value.strip()[:_MARK_TEXT_MAX] + if isinstance(value, (list, tuple)): + items = [str(item).strip()[:_MARK_TEXT_MAX] for item in value if isinstance(item, str) and item.strip()][:_MARK_LIST_MAX] + return items or None + return None + + def _serialize_messages(messages: list) -> list: """Converts LangChain message objects (or already-plain dicts) into plain {type, content} dicts.""" serialized = [] @@ -84,6 +109,10 @@ def _serialize_messages(messages: list) -> list: for mark in ("support_mode", "support_card"): if additional_kwargs.get(mark): entry[mark] = additional_kwargs[mark] # the support card and the option picked on it (backend/utils/support_choice.py MODE_MARK / CARD_MARK) + for mark in SAVED_MARKS: + kept = clean_mark(additional_kwargs.get(mark)) + if kept is not None: + entry[mark] = kept if additional_kwargs.get("initiated"): # Sonic wrote this on its own when the conversation was opened (backend/utils/initiation.py). entry["initiated"] = True @@ -223,6 +252,10 @@ def _deserialize_messages(raw_messages: list) -> list: for mark in ("support_mode", "support_card"): if msg.get(mark): extra[mark] = msg[mark] + for mark in SAVED_MARKS: + kept = clean_mark(msg.get(mark)) + if kept is not None: + extra[mark] = kept if msg.get("initiated"): extra["initiated"] = True if msg.get("initiated_kind"): diff --git a/backend/utils/emotion_checks.py b/backend/utils/emotion_checks.py index ef768f2..6fc24b9 100644 --- a/backend/utils/emotion_checks.py +++ b/backend/utils/emotion_checks.py @@ -340,6 +340,11 @@ def earlier_ai_replies(history, count: int = PRESENCE_WINDOW): "they spend the opening telling them their own situation. Write it again with at most one short acknowledgement, then something they did not say: what you notice, a true thing that " "bears on it, or what you'd offer. Keep the warmth." ), + "no_view": ( + "they asked what you think, and the draft does not say: it opens with how they feel, or hands the question back to them. Write it again and answer first: your view in one plain " + "sentence (\"I think...\", \"I'd...\", \"No, I don't think...\"), then the reason, from what they told you. You may say after it what you are unsure of. Keep what was good in the " + "draft, and do not end by asking them what they think." + ), "against_their_goal": ( "the draft encourages something they have told you they are trying to quit or cut back on (their goal is in THEIR OWN GOALS above). Write it again without encouraging it: stay with " "what they said and how they feel, and if it fits, name their goal once, gently, as theirs. Do not lecture." diff --git a/backend/utils/low_moves.py b/backend/utils/low_moves.py index d1eac45..829748c 100644 --- a/backend/utils/low_moves.py +++ b/backend/utils/low_moves.py @@ -18,7 +18,8 @@ MOVE_MARK = "low_move" MOVE_GAP = 4 -KINDS = ("push_back", "pattern", "company") +KINDS = ("push_back", "pattern", "read", "company") +READ_MIN_WORDS = 12 # a read needs a situation to be a read OF: a few words give it nothing to stand on LOW_VALENCES = ("low", "distressed") MAX_EVIDENCE = 3 MAX_INTERESTS = 3 @@ -27,7 +28,11 @@ HARSH_SELF_RE = re.compile( r"\bi(?:'|’)?m (?:such )?(?:a |an )?(?:failure|loser|idiot|mess|disappointment|joke|burden|fraud|waste|pathetic|worthless|useless|stupid|hopeless|unlovable|broken|not good enough|never going to)\b" r"|\bi (?:always|keep) (?:mess|screw|fuck|ruin)\w*\b|\bi (?:can(?:'|’)?t|cannot|never) do anything right\b|\bi(?:'|’)?ll never (?:be|get|find|amount)\b" - r"|\bnobody (?:likes|wants|cares about|would want) me\b|\bwhat(?:'|’)?s wrong with me\b|\bi (?:hate|can(?:'|’)?t stand) myself\b|\bi ruin everything\b|\bi(?:'|’)?m not (?:smart|good|enough)\b", + r"|\bnobody (?:likes|wants|cares about|would want) me\b|\bwhat(?:'|’)?s wrong with me\b|\bi (?:hate|can(?:'|’)?t stand) myself\b|\bi ruin everything\b|\bi(?:'|’)?m not (?:smart|good|enough)\b" + # Widened 2026-11-27 (push_back fired once in five days): the same judgment said as being the problem, too much, or deserving it. + r"|\bi(?:'|’)?m (?:just )?(?:the problem|too much|hard to love|so dumb|dumb|an embarrassment|embarrassing|bad at (?:this|everything|people|life))\b" + r"|\b(?:no one|nobody) (?:likes|wants|cares about|would want|could love) me\b|\beveryone (?:leaves|hates me|gets tired of me)\b|\bi deserve (?:this|it|to be alone)\b" + r"|\bi (?:always|never) get (?:it|this|anything|things) (?:wrong|right)\b", re.IGNORECASE, ) # A pattern note that reads like a diagnosis is not something to say to someone who is hurting. @@ -92,24 +97,44 @@ def recent_kinds(recent_messages: Iterable[Any], gap: int = MOVE_GAP) -> set: return {str((getattr(m, "additional_kwargs", None) or {}).get(MOVE_MARK)) for m in replies if (getattr(m, "additional_kwargs", None) or {}).get(MOVE_MARK)} -def choose(message: str, state: Optional[Dict[str, Any]], *, facts: Sequence[Any], interests: Sequence[str], recent_messages: Iterable[Any], risk_active: bool, closing: bool) -> Optional[Dict[str, Any]]: - """{"kind", "items"} for this turn's move, or None. Pure.""" +def available(message: str, state: Optional[Dict[str, Any]], *, facts: Sequence[Any], interests: Sequence[str], recent_messages: Iterable[Any], risk_active: bool, closing: bool, + support_mode: Optional[str] = None, reach: str = "default") -> Dict[str, Dict[str, Any]]: + """Every move this turn could make, by kind, in the default order (push_back, pattern, read, company). {} when none applies. Pure. + + 2026-11-27: "company" (their interests, offered as "want to...?") was 16 of 18 moves in five days and the model ignored it; it is now only for someone who asked for a distraction, and + never while they have asked to be just listened to. "read" is new: one sentence of Sonic's own view of the situation, which is neither advice nor their words handed back. It is left out + in "just listen" mode and with the reach dial at "none".""" state = state or {} if risk_active or closing or not state.get("read_this_turn") or state.get("lift_this_turn") or str(state.get("valence")) not in LOW_VALENCES: - return None + return {} used = recent_kinds(recent_messages) + found: Dict[str, Dict[str, Any]] = {} if "push_back" not in used and harsh_about_self(message): evidence = evidence_facts(facts) if evidence: - return {"kind": "push_back", "items": evidence} + found["push_back"] = {"kind": "push_back", "items": evidence} if "pattern" not in used: pattern = matching_pattern(message, facts) if pattern: - return {"kind": "pattern", "items": [pattern]} - if "company" not in used and state.get("need") in ("venting", "distraction", None, "none"): + found["pattern"] = {"kind": "pattern", "items": [pattern]} + if ("read" not in used and support_mode != "listen" and reach != "none" and state.get("need") in ("venting", None, "none") + and len(str(message or "").split()) >= READ_MIN_WORDS and not harsh_about_self(message)): + found["read"] = {"kind": "read", "items": []} + if "company" not in used and support_mode != "listen" and state.get("need") == "distraction": liked = [i for i in interests or [] if i and not _SENSITIVE_RE.search(i) and not _PLAN_RE.search(i)][-MAX_INTERESTS:] if liked: - return {"kind": "company", "items": liked} + found["company"] = {"kind": "company", "items": liked} + return found + + +def choose(message: str, state: Optional[Dict[str, Any]], *, facts: Sequence[Any], interests: Sequence[str], recent_messages: Iterable[Any], risk_active: bool, closing: bool, + support_mode: Optional[str] = None, reach: str = "default", prefer: Optional[Sequence[str]] = None) -> Optional[Dict[str, Any]]: + """{"kind", "items"} for this turn's move, or None. `prefer` is the kinds in the order this person has responded to best (backend/utils/what_lands.py order); the first of them that is + available wins, and without it the default order stands. Pure.""" + found = available(message, state, facts=facts, interests=interests, recent_messages=recent_messages, risk_active=risk_active, closing=closing, support_mode=support_mode, reach=reach) + for kind in list(prefer or []) + list(KINDS): + if kind in found: + return found[kind] return None @@ -122,6 +147,11 @@ def choose(message: str, state: Optional[Dict[str, Any]], *, facts: Sequence[Any "\nSOMETHING YOU HAVE NOTICED OVER TIME (drawn from many things they have told you): {items}\nIf it bears on what they just said, say it in one sentence as your own observation, " "tentatively (\"I've noticed...\"), as something about them that is true and maybe useful right now, not as a diagnosis or a lesson. If it doesn't fit this moment, leave it out.\n" ), + "read": ( + "\nYOUR OWN READ: when you have answered what they said, add ONE sentence that says what you make of the situation: what you think is going on, or what stands out to you, as your " + "own view (\"I think...\", \"What stands out to me is...\"). It is not advice (nothing they should do), not a summary of what they said, and not a feeling of yours. If you see it " + "differently from how they put it, you may say so once, kindly.\n" + ), "company": ( "\nSOMETHING TO OFFER INSTEAD OF A CHECK-IN: things they have told you they are into:\n{items}\nWhen you have answered what they said, you may offer ONE of these as something to do or " "talk about together for a bit (\"want to...?\"), as company, not as a fix or a distraction from their feelings. Not if they want to keep talking about what hurts.\n" @@ -134,6 +164,8 @@ def build_block(move: Optional[Dict[str, Any]]) -> str: if not move or move.get("kind") not in _BLOCKS: return "" items = move.get("items") or [] + if move["kind"] == "read": + return _BLOCKS["read"] if move["kind"] == "pattern": return _BLOCKS["pattern"].format(items=items[0] if items else "") return _BLOCKS[move["kind"]].format(items="\n".join(f"- {item}" for item in items)) diff --git a/backend/utils/memory_erase.py b/backend/utils/memory_erase.py index 769129b..e38c2de 100644 --- a/backend/utils/memory_erase.py +++ b/backend/utils/memory_erase.py @@ -11,6 +11,7 @@ - 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) +- the views Sonic told them it holds (`sonic_said_views`, backend/utils/own_views.py) and the numbers on what tends to land with them (`what_lands`, backend/utils/what_lands.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. @@ -24,12 +25,14 @@ 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 +from backend.utils.own_views import COLLECTION as OWN_VIEWS_COLLECTION +from backend.utils.what_lands import COLLECTION as WHAT_LANDS_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, MOMENTS_COLLECTION) +ERASED_COLLECTIONS = (USER_MEMORY_COLLECTION, CHUNK_ARCHIVE_COLLECTION, FACT_ARCHIVE_COLLECTION, COMPACTION_EVENTS_COLLECTION, DOMAIN_BACKUP_COLLECTION, STRUGGLES_COLLECTION, MOMENTS_COLLECTION, OWN_VIEWS_COLLECTION, WHAT_LANDS_COLLECTION) def stored_counts(db: Any, username: str) -> Dict[str, int]: diff --git a/backend/utils/message_doing.py b/backend/utils/message_doing.py new file mode 100644 index 0000000..37685ee --- /dev/null +++ b/backend/utils/message_doing.py @@ -0,0 +1,59 @@ +"""What a message is DOING, beside the mood it carries: joking through something, winding down, asking a question, or telling news. + +WHY (2026-11-27). The mood read gives a valence and a need for the message, and every low message then got the same shape of reply: how they feel first, at length. But "lol of course she +cancelled again", "ok I'm going to bed", "did I do the right thing?" and "she finally texted back" are four different acts in the same mood, and a friend answers each differently. + +WHAT. `kind(message)` reads the person's own words, by fixed patterns, and returns one of KINDS or None; the first that applies wins, in the order joking, winding_down, asking, news. +`build_block(kind)` is one line for the reply prompt saying what to do FIRST. It never overrides the emotional guidance (which follows it in the prompt) or a safety plan (the caller leaves +it out there), and it says nothing about how long a reply to someone low should be, except for someone who is leaving for the night. + +Pure, no model call, nothing logged. +""" +import re +from typing import Optional + +KINDS = ("joking", "winding_down", "asking", "news") +WINDING_DOWN_MAX_WORDS = 30 + +_JOKING_RE = re.compile(r"\b(?:lol|lmao|lmfao|rofl|haha+|hehe+|jk|just kidding|kidding)\b|😂|🤣|😅|💀", re.IGNORECASE) +_WINDING_DOWN_RE = re.compile( + r"\b(?:going|heading|off|headed) to (?:bed|sleep)\b|\bgonna (?:sleep|crash|head to bed|go to bed|try (?:to|and) sleep)\b|\bneed to (?:sleep|get some sleep|go to bed)\b" + r"|\bcalling it (?:a night|for tonight)\b|\bi should (?:go|sleep|get to bed)\b|\b(?:gotta|got to|have to) (?:go|run|sleep)\b|\btry(?:ing)? to (?:get some )?sleep\b", + re.IGNORECASE, +) +_NEWS_TIME_RE = re.compile(r"\b(?:just|finally|today|tonight|this (?:morning|afternoon|evening)|earlier|yesterday|last night|a (?:minute|second|moment|while) ago)\b", re.IGNORECASE) +_NEWS_EVENT_RE = re.compile( + r"\b(?:got|heard|texted|called|said|told|went|came|sent|replied|emailed|messaged|happened|found out|finished|passed|failed|quit|started|signed|booked|cancell?ed|showed up|" + r"asked|offered|rejected|accepted|broke|fixed|moved|met|saw)\b", + re.IGNORECASE, +) + +_BLOCKS = { + "joking": "they are joking through it. Meet the joke first, in one light clause of your own, before anything heavier; do not explain it or turn it into a concern.", + "winding_down": "they are winding down for the night. Keep this one to a few sentences, ask nothing and open nothing new: let them go.", + "asking": "they asked you something. Answer it in your first sentence, before anything about how they feel.", + "news": "they are telling you something that happened. Respond to the news itself first, specifically: what happened and what it changes. Not a summary of it, and not a check on their feelings.", +} + + +def kind(message: Optional[str]) -> Optional[str]: + """One of KINDS for what the message is doing, or None when none of the patterns applies. Pure.""" + text = str(message or "").strip() + if not text: + return None + if _JOKING_RE.search(text): + return "joking" + if "?" not in text and len(text.split()) <= WINDING_DOWN_MAX_WORDS and _WINDING_DOWN_RE.search(text): + return "winding_down" + if "?" in text: + return "asking" + if _NEWS_TIME_RE.search(text) and _NEWS_EVENT_RE.search(text): + return "news" + return None + + +def build_block(found: Optional[str]) -> str: + """The prompt line for what the message is doing ("" when nothing was read). Pure.""" + if found not in _BLOCKS: + return "" + return f"\nWHAT THIS MESSAGE IS DOING (read from their own words; do this first, and the guidance below still holds): {_BLOCKS[found]}\n" diff --git a/backend/utils/own_views.py b/backend/utils/own_views.py new file mode 100644 index 0000000..39607bd --- /dev/null +++ b/backend/utils/own_views.py @@ -0,0 +1,121 @@ +"""What Sonic told a person it thinks, kept for that person, so it stays consistent and can change its mind on the record. + +WHY (2026-11-27). A view said once and forgotten is not a view anyone holds: asked the same thing a week later Sonic could say the opposite, with no way to know. With the sentence kept, a later +reply can stand by it, or say "I said X before; I'd put it differently now, because...". + +WHAT IS KEPT. One document per view, in `sonic_said_views`: the person, the ONE sentence of Sonic's own reply that stated the view (backend/utils/view_check.view_sentence, at most 220 +characters), the distinctive words of that sentence and of the message it answered (so a later message can find it), and when. No message of the person's is stored, only words from it as a +bag. At most MAX_PER_PERSON a person (the oldest go first); the same sentence is never kept twice; a document expires TTL_DAYS after it was written. + +PRIVACY. Per person, read only for that person's own turns, never shared, never logged, and erased with everything else of theirs (backend/utils/memory_erase.py). Never for a guest; the +caller keeps it away from safety turns. + +WHEN IT IS READ. Only on a turn that asks for a view. `recall` returns the kept view that shares the most distinctive words with the message (at least MIN_SHARED), said at least +MIN_AGE_HOURS ago, so a reply is never told to stay consistent with what it said a minute ago in the same sitting. + +No model call anywhere. +""" +import logging +import uuid +from datetime import datetime, timedelta, timezone +from typing import Any, Dict, List, Optional + +from backend.utils import material_use, view_check + +logger = logging.getLogger("SASS Logger") + +COLLECTION = "sonic_said_views" +MAX_PER_PERSON = 40 +TTL_DAYS = 120 +MIN_SHARED = 3 +MIN_AGE_HOURS = 6 +MAX_WORDS_KEPT = 40 +_indexed = {"done": False} + + +def _aware(moment: Any) -> Optional[datetime]: + if not isinstance(moment, datetime): + return None + return moment if moment.tzinfo else moment.replace(tzinfo=timezone.utc) + + +def _ensure_indexes(db: Any) -> None: + if _indexed["done"]: + return + try: + db[COLLECTION].create_index("expires_at", expireAfterSeconds=0) + db[COLLECTION].create_index("username") + _indexed["done"] = True + except Exception: + logger.warning("[own views] could not create the indexes.", exc_info=True) + + +def entry_for(message: str, reply: str, now: datetime) -> Optional[Dict[str, Any]]: + """The document to keep for a reply that stated a view, or None when it stated none. Pure.""" + sentence = view_check.view_sentence(reply) + if not sentence: + return None + words = sorted(material_use._words(sentence) | material_use._words(message))[:MAX_WORDS_KEPT] + if len(words) < MIN_SHARED: + return None + return {"id": uuid.uuid4().hex, "text": sentence, "words": words, "at": now, "expires_at": now + timedelta(days=TTL_DAYS)} + + +def note(db: Any, username: str, message: str, reply: str, now: Optional[datetime] = None) -> bool: + """Keeps the view this reply stated, for this person. True when one was kept. Blocking; never raises.""" + if db is None or not username: + return False + moment = now or datetime.now(timezone.utc) + entry = entry_for(message, reply, moment) + if entry is None: + return False + try: + _ensure_indexes(db) + kept = list(db[COLLECTION].find({"username": username})) + if any(doc.get("text") == entry["text"] for doc in kept): + return False + db[COLLECTION].insert_one({**entry, "_id": entry["id"], "username": username}) + kept.sort(key=lambda doc: _aware(doc.get("at")) or moment) + for doc in kept[: max(len(kept) + 1 - MAX_PER_PERSON, 0)]: + db[COLLECTION].delete_one({"username": username, "id": doc.get("id")}) + return True + except Exception: + logger.warning("[own views] could not keep a view.", exc_info=True) + return False + + +def pick(kept: List[Dict[str, Any]], message: str, now: datetime) -> Optional[Dict[str, Any]]: + """The kept view that shares the most distinctive words with the message (MIN_SHARED or more), said at least MIN_AGE_HOURS ago; the newer one wins a tie. Pure.""" + said = material_use._words(message) + best, best_key = None, None + for doc in kept or []: + at = _aware(doc.get("at")) + if at is None or now - at < timedelta(hours=MIN_AGE_HOURS) or not doc.get("text"): + continue + shared = len(said & set(doc.get("words") or [])) + if shared >= MIN_SHARED and (best_key is None or (shared, at) > best_key): + best, best_key = doc, (shared, at) + return best + + +def recall(db: Any, username: str, message: str, now: Optional[datetime] = None) -> Optional[Dict[str, Any]]: + """The view Sonic gave this person before that bears on this message, or None. Blocking; never raises.""" + if db is None or not username: + return None + try: + return pick(list(db[COLLECTION].find({"username": username})), message, now or datetime.now(timezone.utc)) + except Exception: + logger.warning("[own views] could not read the kept views.", exc_info=True) + return None + + +def build_block(entry: Optional[Dict[str, Any]]) -> str: + """The prompt section for a kept view ("" when none). Pure.""" + if not entry: + return "" + at = _aware(entry.get("at")) + when = f" on {at.strftime('%B')} {at.day}" if at else "" + return ( + f"\nWHAT YOU TOLD THEM YOU THINK ABOUT THIS BEFORE{when}: \"{entry['text']}\"\nIf it bears on what they ask now, stand by it, or, if you see it differently now, say so plainly " + "(\"I said ... before; I'd put it differently now, because ...\"). Never contradict it silently. Do not quote it back unless that helps them.\n" + ) diff --git a/backend/utils/people_notes.py b/backend/utils/people_notes.py index e8391da..de23e40 100644 --- a/backend/utils/people_notes.py +++ b/backend/utils/people_notes.py @@ -136,6 +136,14 @@ def build_block(chosen: List[Dict[str, Any]]) -> str: return (BLOCK_HEAD + "".join(parts)) if parts else "" +def used(reply: str, chosen: List[Dict[str, Any]]) -> bool: + """True when the finished reply really used one of the notes it was shown (backend/utils/material_use.py: three distinctive words shared with what the note says helps, or with its + pattern). "Offered" was the only count, so a note that is shown and never used looked the same as one that shapes replies (2026-11-27). Pure.""" + from backend.utils import material_use + + return material_use.used_any(reply, [str(note.get(field) or "") for note in chosen or [] for field in ("helps", "pattern")]) + + def tally_turn(counts: Dict[str, int], chosen: List[Dict[str, Any]], tally: Callable[..., None]) -> None: """Adds this turn's counters to `counts` with the counters' own `tally` (backend/utils/self_counters.py, which ignores any key that is not registered): one for the turn and one per note. Counts only.""" if not chosen: diff --git a/backend/utils/placement.py b/backend/utils/placement.py index 0ddc39c..3ad0dce 100644 --- a/backend/utils/placement.py +++ b/backend/utils/placement.py @@ -24,3 +24,16 @@ def after_first_paragraph(reply: str, words: str) -> str: paragraphs = body.rstrip().split("\n\n", 1) placed = f"{paragraphs[0]}\n\n{speech}" + (f"\n\n{paragraphs[1]}" if len(paragraphs) == 2 else "") return f"{placed}\n\n{tail}" if tail else placed + + +def at_end(reply: str, words: str) -> str: + """The reply with `words` as its last paragraph (before any <<>> tag). Unchanged when there is nothing to place, no reply, or the words are already in it. For something that + stands apart from the answer (backend/utils/volunteer.py), where the middle of the reply would interrupt it. Pure.""" + text = reply or "" + speech = (words or "").strip() + if not speech or not text.strip() or speech in text: + return text + tag = _FOLLOW_UP_TAG_RE.search(text) + body, tail = (text[: tag.start()], text[tag.start():].lstrip()) if tag else (text, "") + placed = f"{body.rstrip()}\n\n{speech}" + return f"{placed}\n\n{tail}" if tail else placed diff --git a/backend/utils/reply_stamp.py b/backend/utils/reply_stamp.py index e628a20..882dcb3 100644 --- a/backend/utils/reply_stamp.py +++ b/backend/utils/reply_stamp.py @@ -17,8 +17,8 @@ from backend.utils import reply_tier KEY = "voice" -LABELS = ("flash", "gpt", "haiku", "lite", "other") -TIERS = (reply_tier.STANDARD, reply_tier.LITE, reply_tier.HAIKU, "other") +LABELS = ("flash", "gpt", "haiku", "lite", "sonnet", "other") +TIERS = (reply_tier.STANDARD, reply_tier.LITE, reply_tier.HAIKU, "sonnet", "other") # "sonnet": the capped stronger voice (backend/utils/top_tier.py TIER) CHOICES = ("gemini", "gpt", "lite", "haiku", "auto") MAX_IDS = 2 RECORD_STATES = ("none", "offered", "cited") @@ -35,6 +35,8 @@ def label_for(tier: str, choice: str) -> str: return "haiku" if tier == reply_tier.LITE: return "lite" + if tier == "sonnet": + return "sonnet" if tier == reply_tier.STANDARD: return "gpt" if choice == "gpt" else "flash" return "other" diff --git a/backend/utils/revision_reasons.py b/backend/utils/revision_reasons.py index 312262a..e537c0c 100644 --- a/backend/utils/revision_reasons.py +++ b/backend/utils/revision_reasons.py @@ -8,7 +8,7 @@ # The emotional check's own tags (backend/utils/emotion_checks.py), kept as they are. EMOTIONAL_TAGS = ("probing_question", "two_questions", "template_phrase", "thin_comfort", "hedged", "generalizing", "restating", "venting_advice", "celebration_no_question", - "repeated_presence", "repeated_opening", "repeated_permission", "recycled_point", "against_their_goal", "stacked_validation") + "repeated_presence", "repeated_opening", "repeated_permission", "recycled_point", "against_their_goal", "stacked_validation", "no_view") # What an identity rewrite was about. IDENTITY_REASONS = ( "feeling", # claims a feeling, love, joy, loneliness, a reaction, a human state diff --git a/backend/utils/self_counters.py b/backend/utils/self_counters.py index 468f765..22ee0d3 100644 --- a/backend/utils/self_counters.py +++ b/backend/utils/self_counters.py @@ -96,6 +96,8 @@ # Which voice wrote each reply and why (backend/utils/reply_tier.py REASONS; counts only): lite_setting and auto_plain are lite replies, the rest stayed on the standard voice. "reply_tier": ("standard_setting", "lite_setting", "haiku_setting", "auto_plain", "not_offered", "safety", "emotional", "checkin", "companion", "identity", "frustration"), "proactive_quiet": ("guest", "risk", "closing", "energy", "route", "rate_limit", "nothing_matched"), + # What an emotional turn was doing beside its mood, read by fixed patterns (backend/utils/message_doing.py KINDS). Counts only. + "doing": ("joking", "winding_down", "asking", "news"), # 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"), } @@ -182,7 +184,13 @@ "emotion_checkin_offered", "emotion_checkin_asked", "emotion_checkin_eased", "emotion_checkin_still_low", # Turns where Sonic's own material (its habits, record cases, captures) was allowed although the plain energy tier would have held it: frustration at the work, or a low that eased # (backend/utils/emotion_utils.py own_material_tier). Read against relatable_offered / experience_offered / experience_captured. Counts only. - "own_material_opened") + "own_material_opened", + # Sonic's own views and what it brings up unasked (2026-11-27). A view was asked for, a reply stated one, a reply handed the question back (backend/utils/view_check.py); a view + # kept for the person and one recalled later (own_views.py); an approved stance put in the prompt and really used (stances.py); a take placed unprompted (volunteer.py); an + # outcome recorded for the reply before, one that showed a lift, and a turn whose low moves were ordered by them (what_lands.py); the low move "read" (low_moves.py); a reply + # written by the capped stronger voice (top_tier.py); and a reply that really used a people note it was shown (people_notes.used). Counts only. + "view_asked", "view_stated", "view_handed_back", "own_view_kept", "own_view_recalled", "stance_offered", "stance_used", "volunteer_placed", "lands_recorded", "lands_lift", + "lands_ordered", "low_move_read", "reply_top_tier_used", "people_notes_used") _PLAIN_KEYS = _PLAIN_KEYS + RHYTHM_KEYS + MAPS_KEYS + READING_KEYS + GUIDANCE_KEYS + PLAN_CHANGE_KEYS + COMBO_KEYS + LESSON_KEYS + APPLY_WAIT_KEYS + CONVSUM_KEYS + LOOK_KEYS + BROWSER_KEYS + MONGO_KEYS + KB_KEYS + CI_KEYS + CHOICE_KEYS + PROGRESS_KEYS + ANSWER_CHECK_KEYS + VERIFY_KEYS + ADVISOR_KEYS + REASONER_KEYS + SUBSTANCE_KEYS + RUNNER_FILES_KEYS + PATTERN_KEYS + STEPS_KEYS + PROACTIVE_KEYS # A model provider refusing Sonic's API key, and accepting it again (backend/utils/provider_health.py). Counted at most once a minute while it lasts: minutes with a refusal, not calls. PROVIDER_KEYS = ("llm_key_rejected_claude", "llm_key_rejected_openai", "llm_key_recovered_claude", "llm_key_recovered_openai") diff --git a/backend/utils/stances.py b/backend/utils/stances.py new file mode 100644 index 0000000..87aa677 --- /dev/null +++ b/backend/utils/stances.py @@ -0,0 +1,101 @@ +"""Choosing one of Sonic's approved stances about people and life (backend/components/sonic_stances.py) for a turn where a view is wanted. + +WHEN. Only on a turn that already calls for a view: the person asked what it thinks (backend/utils/view_check.py), they chose advice on the support card, or the turn's low move is its own +read (backend/utils/low_moves.py). Never under a safety plan, on a closing message or for a guest: the caller decides those. A stance is offered, not placed: on these turns the reply is already +told to state a view, and the stance gives it one that is its own, to be said in its own words. + +HOW. A trigger phrase in the message wins; otherwise the stance closest in meaning, if it clears MIN_SCORE (the relatable lines' own matcher and threshold). `used` says whether the finished +reply really used it (backend/utils/material_use.py), so offered and used are counted apart. + +Pure apart from the registry; nothing is logged. +""" +import re +from typing import Any, Dict, List, Optional, Tuple + +from backend.components.sonic_stances import APPROVED_IDS, STANCES +from backend.utils import material_use + +ID_PREFIX = "stance_" +MAX_LINE_CHARS = 240 +MIN_USED_WORDS = 2 +_ID_RE = re.compile(r"^stance_[a-z_]{3,60}$") +_VIEW_START_RE = re.compile(r"^(?:I think|I don't think|I'd rather|I'd pick|I lean toward|When [^,]{3,80}, I think)\b") +_NOT_A_VIEW_RE = re.compile( + r"\bI (?:feel|felt|remember|recall|love|hate|miss|worry|hope|wish)\b|\bI(?:'ve| have) been (?:there|through)\b|\bin my (?:life|experience)\b|\byou (?:should|must|need to|have to)\b", + re.IGNORECASE, +) + + +def approved(entries: Optional[List[Dict[str, Any]]] = None, approved_ids: Optional[Tuple[str, ...]] = None) -> List[Dict[str, Any]]: + """The stances that may be used: those whose id is approved. Pure.""" + ids = set(APPROVED_IDS if approved_ids is None else approved_ids) + return [dict(entry) for entry in (STANCES if entries is None else entries) if entry.get("id") in ids] + + +def is_stance(entry: Optional[Dict[str, Any]]) -> bool: + return bool(entry) and str(entry.get("id") or "").startswith(ID_PREFIX) + + +def check_registry(entries: Optional[List[Dict[str, Any]]] = None, approved_ids: Optional[Tuple[str, ...]] = None) -> List[str]: + """Problems with the registry: a bad or repeated id, a missing field, a line that is not a view or is too long, or an approved id with no entry. Pure.""" + entries = STANCES if entries is None else entries + problems: List[str] = [] + seen = set() + for entry in entries: + entry_id = str(entry.get("id") or "") + if not _ID_RE.match(entry_id): + problems.append(f"{entry_id or '(no id)'}: the id must be stance_ and lowercase words") + if entry_id in seen: + problems.append(f"{entry_id}: the id is used twice") + seen.add(entry_id) + line = str(entry.get("line") or "") + if not line or len(line) > MAX_LINE_CHARS: + problems.append(f"{entry_id}: the line must be 1 to {MAX_LINE_CHARS} characters") + elif not _VIEW_START_RE.match(line): + problems.append(f"{entry_id}: the line must open as a view (I think, I don't think, I'd rather, I'd pick, I lean toward)") + if _NOT_A_VIEW_RE.search(line): + problems.append(f"{entry_id}: the line claims a feeling or a past of its own, or tells the person what to do") + if not entry.get("triggers"): + problems.append(f"{entry_id}: it needs trigger phrases") + for entry_id in (APPROVED_IDS if approved_ids is None else approved_ids): + if entry_id not in seen: + problems.append(f"{entry_id}: approved, but there is no such stance") + return problems + + +def select(message: str, *, wanted: bool, entries: Optional[List[Dict[str, Any]]] = None, vector: Optional[List[float]] = None, + vectors: Optional[Dict[str, List[float]]] = None) -> Optional[Dict[str, Any]]: + """The approved stance for this message, or None. `wanted` is the caller's "this turn calls for a view"; without it nothing is chosen. A trigger phrase wins; otherwise, given the message's + embedding and the entries' (relatable_utils.entry_vectors), the closest in meaning above the relatable threshold, returned as a copy marked {"match": "meaning"}. Pure.""" + pool = approved() if entries is None else entries + if not wanted or not pool or not str(message or "").strip(): + return None + from backend.utils.relatable_utils import _closest_in_meaning, _triggered + + best, best_hits = None, 0 + for entry in pool: + hits = _triggered(message, entry.get("triggers", [])) + if hits > best_hits: + best, best_hits = entry, hits + if best is None and vector and vectors: + closest = _closest_in_meaning(vector, pool, vectors) + if closest: + return {**closest, "match": "meaning"} + return best + + +def build_block(entry: Optional[Dict[str, Any]]) -> str: + """The prompt section for an offered stance ("" when none). Pure.""" + if not entry: + return "" + return ( + f"\nA VIEW YOU HOLD that bears on this: \"{entry['line']}\"\nSay it in your own words as what you think, with its reason, fitted to what they told you. It is a view, not a rule for " + "them and not something you lived. If it does not fit what they asked, leave it out.\n" + ) + + +def used(reply: str, entry: Optional[Dict[str, Any]]) -> bool: + """True when the finished reply shares at least MIN_USED_WORDS distinctive words with the stance (a looser test than material_use.used_line: the reply is asked to reword it). Pure.""" + if not entry: + return False + return len(material_use._words(reply) & material_use._words(entry.get("line", ""))) >= MIN_USED_WORDS diff --git a/backend/utils/support_choice.py b/backend/utils/support_choice.py index 2717efa..c9afaa6 100644 --- a/backend/utils/support_choice.py +++ b/backend/utils/support_choice.py @@ -19,12 +19,14 @@ from datetime import datetime, timedelta, timezone from typing import Any, Dict, Iterable, List, Optional +from backend.utils import view_check from backend.utils.emotion_utils import NEGATIVE_VALENCES from backend.utils.time_utils import sent_at MODE_MARK = "support_mode" # on their message: the option they picked ("listen", "advice", "fix") CARD_MARK = "support_card" # on Sonic's reply: a card was shown with it MODE_HOURS = 6 +LISTEN_TURNS = 10 # how many of their messages "just listen" holds for after the tap OFFER_MIN_INTENSITY = 0.35 QUESTION = "What would help most right now?" OPTIONS = ( @@ -49,12 +51,21 @@ def stated_what_they_want(message: str) -> bool: def current_mode(messages: Iterable[Any], now: Optional[datetime] = None) -> Optional[str]: """The mode they picked in the last MODE_HOURS (the newest pick wins), or None. Pure apart from the clock.""" moment = now or datetime.now(timezone.utc) - for message in reversed(list(messages or [])): + ordered = list(messages or []) + for message in reversed(ordered): mode = (getattr(message, "additional_kwargs", None) or {}).get(MODE_MARK) if getattr(message, "type", "") != "human" or mode not in KEYS: continue when = sent_at(message) - return mode if when is not None and moment - when <= timedelta(hours=MODE_HOURS) else None + if when is None or moment - when > timedelta(hours=MODE_HOURS): + return None + if mode == "listen": + # "Just listen" answers the stretch it was tapped in, not the next six hours of conversation (2026-11-27: 4 taps covered 78 of 313 conversational turns). It ends after + # LISTEN_TURNS of their messages, and it steps aside for a message that asks Sonic what it thinks: that is them saying they want something different. + later = [m for m in ordered[ordered.index(message) + 1:] if getattr(m, "type", "") == "human"] + if len(later) > LISTEN_TURNS or (later and view_check.asks_for_view(str(getattr(later[-1], "content", "") or ""))): + return None + return mode return None @@ -101,8 +112,9 @@ def card() -> Dict[str, Any]: _MODE_TEXT = { "listen": ( - "they asked you to JUST LISTEN. Stay with what they say and how it feels for them. No advice, suggestions, fixes, plans or silver linings. Short is fine. At most one gentle question, " - "and often none." + "they asked you to JUST LISTEN. Stay with what they say and how it feels for them. No advice, suggestions, fixes, plans or silver linings. Listening is not saying nothing, though: " + "you may name exactly what is hard about it (not a summary of it), bring in something they told you before that bears on it, or thank them for telling you something hard. Short is " + "fine. At most one gentle question, and often none." ), "advice": ( "they asked for ADVICE. Give your honest take: what you see in what they described and what you would consider, with one or two concrete suggestions grounded in what they told you " diff --git a/backend/utils/top_tier.py b/backend/utils/top_tier.py new file mode 100644 index 0000000..45a7df5 --- /dev/null +++ b/backend/utils/top_tier.py @@ -0,0 +1,60 @@ +"""A stronger voice for the few turns that matter most. OFF unless REPLY_TOP_TIER=on. + +WHY (2026-11-27). Three quarters of turns are read as emotional stakes and every one is written by the cheapest voice. A stronger one costs about twenty times as much a reply, so it cannot +write them all; it can write the handful a day where the person is hurting most. Whether it writes those better is NOT yet measured (one three-question comparison exists), which is why this +ships switched off: turn it on for a comparison, not by default. + +WHEN (`wanted`). The switch is on, the turn's stakes are in TOP_STAKES, the feeling in force is at least MIN_INTENSITY, the person is not a guest, and fewer than the daily cap of their +replies in the last 24 hours were written by it (read from the reply stamps saved on the conversation: backend/utils/reply_stamp.py). NEVER inside a safety context: those replies stay on +the standard voice the safety layer was built and tested on. + +The person's own daily spend limit still applies, because the model's price is in LLM_PRICES (the caller only gets a voice when it is: backend/models/models.py get_top_stream_llm). + +Pure apart from the environment and the clock; nothing is logged. +""" +import os +from datetime import datetime, timedelta, timezone +from typing import Any, Iterable, Optional + +from backend.utils.time_utils import sent_at + +TIER = "sonnet" +TOP_STAKES = ("emotional", "checkin") +MIN_INTENSITY = float(os.getenv("REPLY_TOP_TIER_MIN_INTENSITY", "0.6")) +DEFAULT_DAILY = 8 +WINDOW_HOURS = 24 + + +def enabled() -> bool: + return os.getenv("REPLY_TOP_TIER", "off").strip().lower() in ("1", "true", "yes", "on") + + +def daily_cap() -> int: + try: + return max(int(os.getenv("REPLY_TOP_TIER_DAILY", str(DEFAULT_DAILY))), 0) + except ValueError: + return DEFAULT_DAILY + + +def used_today(messages: Iterable[Any], now: Optional[datetime] = None) -> int: + """How many of Sonic's replies in the last WINDOW_HOURS were written by the top voice, by their saved stamps. A stamped reply with no time on it is counted (an unknown time is never + guessed to be old). Pure apart from the clock.""" + moment = now or datetime.now(timezone.utc) + count = 0 + for message in messages or []: + stamp = (getattr(message, "additional_kwargs", None) or {}).get("voice") + if getattr(message, "type", "") != "ai" or not isinstance(stamp, dict) or stamp.get("tier") != TIER: + continue + when = sent_at(message) + if when is None or moment - when < timedelta(hours=WINDOW_HOURS): + count += 1 + return count + + +def wanted(stakes: str, intensity: float, *, risk_active: bool, used: int, guest: bool, on: Optional[bool] = None, cap: Optional[int] = None) -> bool: + """Whether the top voice should write this reply. Pure apart from the environment.""" + if not (enabled() if on is None else on) or risk_active or guest: + return False + if stakes not in TOP_STAKES or float(intensity or 0.0) < MIN_INTENSITY: + return False + return used < (daily_cap() if cap is None else cap) diff --git a/backend/utils/view_check.py b/backend/utils/view_check.py new file mode 100644 index 0000000..6f61882 --- /dev/null +++ b/backend/utils/view_check.py @@ -0,0 +1,93 @@ +"""When someone asks Sonic what it thinks, the reply says what it thinks. + +WHY (2026-11-27, measured on 200 recent non-code replies): a reply stated a view of its own ("I think", "I'd", "my take") in about 1 in 100, and disagreed in none. Its profile says it prefers +direct feedback and names a real flaw once; in personal talk the emotional guidance outranked that, so a question like "am I overreacting?" was answered with how the person feels and a question +back. A view is not a feeling and not advice, so nothing in the feelings policy is in its way. + +WHAT. `asks_for_view(message)` reads the person's own words. On such a turn the prompt gets VIEW_BLOCK (answer first, then the reason; never hand it back), and the finished reply is checked: +`issue(message, reply)` is "no_view" when its opening holds no stated view, or it hands the question back, and the reply is written once more (emotion_checks' revision note, tag "no_view"). +A reply that states a view carries VIEW_MARK and the sentence can be kept for that person (backend/utils/own_views.py). Never under a safety plan: the caller decides that. + +Pure, no model call, nothing logged. +""" +import re +from typing import Optional + +VIEW_MARK = "view_stated" +OPENING_SENTENCES = 3 +MAX_VIEW_CHARS = 220 + +_ASKS_RE = re.compile( + r"\bwhat do you (?:think|make of|reckon)\b|\bwhat(?:'|’)?s your (?:take|opinion|view|read|honest|gut)\b|\byour (?:honest )?(?:take|opinion|thoughts|view|read)\b" + r"|\bdo you think\b|\bwhat would you (?:do|say|pick|choose)\b|\bwould you (?:do|say|go|pick|choose|have)\b|\bshould i\b|\bbe honest\b|\bhonestly,? (?:am|is|was|do|did|should)\b" + r"|\bam i (?:wrong|right|overreacting|over-reacting|being|crazy|the problem|too)\b|\bwas i (?:wrong|right|out of line|too)\b" + r"|\bis (?:it|that|this) (?:weird|bad|wrong|ok|okay|normal|fair|too much|stupid|dumb|crazy|a bad idea|a good idea)\b|\bwdyt\b|\bthoughts\?", + re.IGNORECASE, +) +# Asking it about itself ("do you think you'll remember", "what do you think about being an AI") is the self-report path's business, not a view on the person's situation. +_ABOUT_ITSELF_RE = re.compile(r"\b(?:do|what do) you think (?:about )?(?:you|yourself|you(?:'|’)?ll|you(?:'|’)?re|your own)\b|\babout being an ai\b", re.IGNORECASE) +_STATES_RE = re.compile( + r"\bi (?:think|don(?:'|’)?t think|reckon|suspect|doubt|disagree|agree|would(?:n(?:'|’)?t)?|wouldn(?:'|’)?t)\b" + r"|\bi(?:'|’)?d (?:say|argue|go|pick|choose|do|start|try|push back|bet|wait|send|tell|ask|leave|keep|rather|call)\b" + r"|\bmy (?:take|guess|read|bet|view|honest (?:take|read|answer|view))\b|\bif it were me\b|\bto me,? (?:it|that|this)\b|\bwhat stands out to me\b" + r"|^(?:yes|no|honestly|not really|a little|somewhat|probably(?: not)?)\b[,.: ]", + re.IGNORECASE, +) +_HANDS_BACK_RE = re.compile( + r"\bonly you can\b|\b(?:it(?:'|’)?s|that(?:'|’)?s) (?:really |ultimately |entirely )?(?:up to you|your call|your decision)\b|\bthere(?:'|’)?s no (?:right|wrong)\b" + r"|\bi can(?:'|’)?t (?:tell you|answer that for you|decide (?:that|this) for you)\b|\bwhat (?:do you think|feels right(?: to you)?|does your gut (?:say|tell you))\?", + re.IGNORECASE, +) +_SENTENCE_RE = re.compile(r"(?<=[.!?])\s+") + +VIEW_BLOCK = ( + "\nTHEY ASKED WHAT YOU THINK. Answer that first: your view in one plain sentence (\"I think...\", \"I'd...\", \"No, I don't think...\"), then your reason, drawn from what they told you. " + "After it you may say what you are unsure of, or what would change your mind. Do not hand the question back (\"only you can decide\", \"what does your gut say?\") and do not open with how " + "they feel. A view is what you think, never what you feel, and never a claim to have lived it.{disagree}\n" +) +_DISAGREE = { + "low": " If you see it differently from how they put it, say so once, gently.", + "default": " If you see it differently from how they put it, say so once, plainly, with the reason, then help with whichever way they go.", + "more": " If you see it differently from how they put it, say so once, plainly, with the reason, then help with whichever way they go.", +} + + +def asks_for_view(message: Optional[str]) -> bool: + """True when the person's message asks Sonic for its view of their situation. Pure.""" + text = str(message or "") + return bool(_ASKS_RE.search(text)) and not _ABOUT_ITSELF_RE.search(text) + + +def sentences(reply: Optional[str]) -> list: + return [part.strip() for part in _SENTENCE_RE.split(str(reply or "").strip()) if part.strip()] + + +def view_sentence(reply: Optional[str], within: Optional[int] = None) -> Optional[str]: + """The first sentence of the reply that states a view (among its first `within` sentences when given), cut to MAX_VIEW_CHARS, or None. Pure.""" + parts = sentences(reply) + for part in parts if within is None else parts[:within]: + if _STATES_RE.search(part): + return part[:MAX_VIEW_CHARS] + return None + + +def states_view(reply: Optional[str]) -> bool: + return view_sentence(reply) is not None + + +def hands_back(reply: Optional[str]) -> bool: + return bool(_HANDS_BACK_RE.search(str(reply or ""))) + + +def issue(message: Optional[str], reply: Optional[str]) -> Optional[str]: + """"no_view" when they asked for a view and the reply's opening states none, or the reply hands the question back; else None. Pure.""" + if not asks_for_view(message) or not str(reply or "").strip(): + return None + if view_sentence(reply, OPENING_SENTENCES) is None or hands_back(reply): + return "no_view" + return None + + +def build_block(reach: str = "default") -> str: + """The prompt section for a turn where a view was asked for. The reach dial decides how plainly a disagreement is put; with it at "none" they still get the view they asked for. Pure.""" + return VIEW_BLOCK.format(disagree=_DISAGREE.get(reach, "")) diff --git a/backend/utils/volunteer.py b/backend/utils/volunteer.py new file mode 100644 index 0000000..ed05dc8 --- /dev/null +++ b/backend/utils/volunteer.py @@ -0,0 +1,62 @@ +"""Once in a while Sonic brings up something of its own without being asked. + +WHY (2026-11-27). Everything of its own was matched against what the person had just said, so material about its own interests never surfaced in conversations about anything else: its 11 +approved takes on things it read were all live, and were offered 0 times in 35 days. An entity with a reading shelf mentions what it read now and then, unprompted, and then lets it go. + +WHAT. At most one a day per conversation, at an open moment, the reply ends with one take from its reading shelf (backend/utils/takes.py: approved by a person, and its piece still live on +the shelf), placed by code after a short lead-in, word for word. A take is Sonic's own and shared by everyone: it comes from a public page it read, never from anyone's conversation. A take +this conversation has already heard is not said again. + +WHEN (`may`). A conversational turn with the turn's slot free, no safety context, an open mood, not a closing message, the person's offers switch on and the reach dial not at "none", and a +short message that asks for nothing (no question, at most MAX_MESSAGE_WORDS words): never on top of a request, an answer they are waiting for, or anything heavy. The last one must be at +least GAP_HOURS old (read from the saved marks on Sonic's replies). + +The mark on the reply (MARK) holds the take's id. Pure, no model call, nothing logged. +""" +from datetime import datetime, timedelta, timezone +from typing import Any, Dict, Iterable, List, Optional + +from backend.utils.time_utils import sent_at + +MARK = "volunteered" +GAP_HOURS = 20 +MAX_MESSAGE_WORDS = 30 +LEAD_IN = "Something from my own reading, apart from all this:" + + +def said_ids(messages: Iterable[Any]) -> List[str]: + """The ids of the takes this conversation has already heard, oldest first. Pure.""" + return [str((getattr(m, "additional_kwargs", None) or {}).get(MARK)) for m in messages or [] + if getattr(m, "type", "") == "ai" and (getattr(m, "additional_kwargs", None) or {}).get(MARK)] + + +def recently(messages: Iterable[Any], now: Optional[datetime] = None, gap_hours: float = GAP_HOURS) -> bool: + """True when one of Sonic's replies in the last `gap_hours` volunteered something. A marked reply with no time on it counts as recent (an unknown time is never guessed). Pure apart from the clock.""" + moment = now or datetime.now(timezone.utc) + for message in reversed(list(messages or [])): + if getattr(message, "type", "") == "ai" and (getattr(message, "additional_kwargs", None) or {}).get(MARK): + when = sent_at(message) + return when is None or moment - when < timedelta(hours=gap_hours) + return False + + +def may(message: str, messages: Iterable[Any], *, source_type: str, risk_active: bool, energy_tier: str, closing: bool, proactive_taken: bool, offers_allowed: bool, reach: str, + now: Optional[datetime] = None) -> bool: + """Whether this turn is an open moment for it. Pure apart from the clock.""" + text = str(message or "").strip() + if source_type != "conversational" or risk_active or closing or proactive_taken or energy_tier != "open" or not offers_allowed or reach == "none": + return False + if not text or "?" in text or len(text.split()) > MAX_MESSAGE_WORDS: + return False + return not recently(messages, now) + + +def pick(takes: List[Dict[str, Any]], messages: Iterable[Any]) -> Optional[Dict[str, Any]]: + """The first live take this conversation has not heard, or None when it has heard them all. Pure.""" + heard = set(said_ids(messages)) + return next((take for take in takes or [] if take.get("id") and take.get("line") and take["id"] not in heard), None) + + +def spoken(take: Dict[str, Any]) -> str: + """The words placed at the end of the reply: the lead-in and the take's own approved line. Pure.""" + return f"{LEAD_IN} {str(take.get('line') or '').strip()}" diff --git a/backend/utils/what_lands.py b/backend/utils/what_lands.py new file mode 100644 index 0000000..0a3d252 --- /dev/null +++ b/backend/utils/what_lands.py @@ -0,0 +1,114 @@ +"""What tends to land with a person: each kind of thing a reply did is counted against how their next message read, so the next choice can lean on it. + +WHY (2026-11-27). Sonic chose its moves for a low moment in a fixed order and never learned from what followed. The app already reads, on every message, whether the mood lifted +(`lift_this_turn`), and nothing connected that back to what the reply before it had done. + +WHAT. A reply carries MARK: the kinds of things it did (KINDS: a low move by its kind, a stated view, a stance, a placed story or record line, a question at the end). When the person's next +message arrives, each kind gets one try and, when that message showed a lift, one lift; a message of some length that is not a closing counts as engaged. Stored per person in `what_lands` +as numbers only, one document a person with flat fields (`read_tries`, `read_lifts`, `read_engaged`, ...). No message, topic or word is kept. + +USE. `order(stats, kinds)` puts the kinds this person has lifted after most often first, once a kind has MIN_TRIES tries; with too little to go on the caller's own order stands. The low +moves use it (backend/utils/low_moves.py `prefer`). It is one person's numbers used for that person only, erased with everything else of theirs, and never for a guest. + +No model call; nothing logged. +""" +import logging +from typing import Any, Dict, Iterable, List, Optional + +logger = logging.getLogger("SASS Logger") + +COLLECTION = "what_lands" +MARK = "move_kinds" +KINDS = ("push_back", "pattern", "read", "company", "view", "stance", "story", "record", "question") +MIN_TRIES = 4 +ENGAGED_WORDS = 8 +OUTCOMES = ("lift", "engaged", "flat") +FIELDS = ("tries", "lifts", "engaged") + + +def kinds_of(*, low_move: Optional[str] = None, view: bool = False, stance: bool = False, story: bool = False, record: bool = False, question: bool = False) -> List[str]: + """The kinds a reply did, for its mark. Pure.""" + found = [low_move] if low_move in KINDS else [] + for present, kind in ((view, "view"), (stance, "stance"), (story, "story"), (record, "record"), (question, "question")): + if present and kind not in found: + found.append(kind) + return found + + +def marked(message: Any) -> List[str]: + """The kinds on a reply's mark, cleaned. Pure.""" + raw = (getattr(message, "additional_kwargs", None) or {}).get(MARK) + return [kind for kind in (raw if isinstance(raw, (list, tuple)) else []) if kind in KINDS] + + +def last_reply_kinds(messages: Iterable[Any]) -> List[str]: + """The kinds on Sonic's most recent reply before the person's latest message, or []. Pure.""" + for message in reversed(list(messages or [])): + if getattr(message, "type", "") == "ai": + return marked(message) + return [] + + +def outcome(state: Optional[Dict[str, Any]], message: str, closing: bool) -> str: + """How the person's next message read: "lift" (the mood read showed one), "engaged" (they wrote on at some length and are not leaving) or "flat". Pure.""" + if (state or {}).get("lift_this_turn"): + return "lift" + if not closing and len(str(message or "").split()) >= ENGAGED_WORDS: + return "engaged" + return "flat" + + +def record(db: Any, username: str, kinds: List[str], result: str) -> bool: + """Adds one try (and a lift or an engaged) to each kind for this person. True when written. Blocking; never raises.""" + kinds = [kind for kind in kinds or [] if kind in KINDS] + if db is None or not username or not kinds or result not in OUTCOMES: + return False + inc: Dict[str, int] = {} + for kind in kinds: + inc[f"{kind}_tries"] = 1 + if result == "lift": + inc[f"{kind}_lifts"] = 1 + if result in ("lift", "engaged"): + inc[f"{kind}_engaged"] = 1 + try: + db[COLLECTION].update_one({"username": username}, {"$inc": inc}, upsert=True) + return True + except Exception: + logger.warning("[what lands] could not record an outcome.", exc_info=True) + return False + + +def load(db: Any, username: str) -> Dict[str, Dict[str, int]]: + """This person's numbers by kind, or {}. Blocking; never raises.""" + if db is None or not username: + return {} + try: + doc = db[COLLECTION].find_one({"username": username}) or {} + except Exception: + logger.warning("[what lands] could not read the numbers.", exc_info=True) + return {} + found: Dict[str, Dict[str, int]] = {} + for kind in KINDS: + stats = {field: int(doc[f"{kind}_{field}"]) for field in FIELDS if isinstance(doc.get(f"{kind}_{field}"), (int, float))} + if stats: + found[kind] = stats + return found + + +def rate(stats: Optional[Dict[str, int]]) -> Optional[float]: + """The share of tries that were followed by a lift, or None with fewer than MIN_TRIES tries. Pure.""" + tries = int((stats or {}).get("tries") or 0) + if tries < MIN_TRIES: + return None + return int((stats or {}).get("lifts") or 0) / tries + + +def order(stats: Optional[Dict[str, Dict[str, int]]], kinds: Iterable[str]) -> List[str]: + """`kinds` with those this person has lifted after most often first. A kind without enough tries keeps its place among the others like it, after every kind that has a rate above + zero, so a new kind is still tried before one that has been tried and never helped. Pure.""" + listed = list(kinds) + rated = {kind: rate((stats or {}).get(kind)) for kind in listed} + helped = sorted((kind for kind in listed if rated[kind]), key=lambda kind: (-rated[kind], listed.index(kind))) + untried = [kind for kind in listed if rated[kind] is None] + never = [kind for kind in listed if rated[kind] == 0] + return helped + untried + never diff --git a/local/src/components/traceFacts.ts b/local/src/components/traceFacts.ts index 46292f0..1e5204d 100644 --- a/local/src/components/traceFacts.ts +++ b/local/src/components/traceFacts.ts @@ -278,6 +278,7 @@ export const REVISION_WORDS: Readonly> = { recycled_point: 'The draft handed back a point already made twice, so it was written again', against_their_goal: 'The draft went against a goal you told me about, so it was written again', stacked_validation: 'The draft opened with stock sympathy lines, so it was written again', + no_view: 'The draft did not say what I think when you asked, so it was written again', }; export const GENERIC_REVISION_WORDS = 'The draft was checked against what you need and written again'; diff --git a/local/src/pages/Privacy.tsx b/local/src/pages/Privacy.tsx index a077a06..bf41fc6 100644 --- a/local/src/pages/Privacy.tsx +++ b/local/src/pages/Privacy.tsx @@ -94,6 +94,7 @@ export const PrivacyPage: React.FC = () => {
  • Conversations: the messages you send the assistant and its replies, so we can keep your history and answer follow-up questions.
  • Photos and files you attach in a chat: the text Sonic reads out of each file, and for photos the image itself, are kept with that conversation for 30 days so you can come back to it, and then removed (the conversation itself stays). A photo of a letter or bill can contain personal details, so only attach what you're comfortable with.
  • What Sonic remembers: short notes drawn from your conversations (for example, a preference or something you're working on). They are listed on the Memory page, where you can remove any of them or all of them.
  • +
  • What Sonic told you it thinks, and what tends to help: when Sonic gives you its view on something, that one sentence is kept so it can stay consistent later. It also keeps counts (numbers only, no text) of which kinds of reply were followed by you sounding better. Both are used only for you and are erased when you erase your memory on the Memory page.
  • What you tell Sonic about yourself: the optional details on your Account page (name, pronouns, what you do, interests, how you like answers, topics to avoid).
  • Documents you add to your knowledge base: if you use Self Service, uploaded files are processed and indexed so the assistant can answer questions about them.
  • A connected folder: if you choose to connect one, its text files are copied to our server so Sonic can read them. The copy is deleted when you disconnect, and expires on its own after about 12 hours. Sonic only changes your files when you press Apply, and you can undo it. A Word document in the folder is turned into a plain-text outline on our server so Sonic can read it, and the file itself is not kept. If you ask Sonic to write or edit a Word document, the text (and, for an edit, the document) passes through our server once to make the new copy; that step does not store it, and your original is never changed.