From c3d47ec2a504db78e3020abdbbe7a4e5306cae85 Mon Sep 17 00:00:00 2001 From: jack Date: Sat, 28 Nov 2026 13:41:07 -0600 Subject: [PATCH] feat: update after-edit checks, native loop, own views and runner settings Co-authored-by: Sonic Assistant --- app.py | 4 +- backend/components/sonic_changelog.py | 4 +- backend/services/agent_workflow.py | 5 + backend/services/native_loop.py | 8 +- backend/tests/test_after_edit_check.py | 209 ++++++++++++++++++++ backend/tests/test_edit_corrections.py | 72 +++++++ backend/tests/test_native_loop.py | 7 +- backend/tests/test_own_voice.py | 87 +++++++- backend/utils/after_edit_check.py | 104 ++++++++-- backend/utils/agent_utils.py | 35 +++- backend/utils/claim_check.py | 8 +- backend/utils/combo.py | 6 + backend/utils/handback_check.py | 9 +- backend/utils/loop_rhythm.py | 8 +- backend/utils/message_doing.py | 55 +++++- backend/utils/own_views.py | 30 ++- backend/utils/self_counters.py | 2 +- docs/review-fable-opus-2026-11-27.md | 108 ++++++++++ local/src/components/RunnerSettingsCard.tsx | 2 +- local/src/components/helpTips.ts | 2 +- 20 files changed, 695 insertions(+), 70 deletions(-) create mode 100644 docs/review-fable-opus-2026-11-27.md diff --git a/app.py b/app.py index 5d4f4106..0fee286e 100644 --- a/app.py +++ b/app.py @@ -1890,7 +1890,7 @@ def _read_progress_notes(): 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 + _doing = message_doing.kind(_their_words, effective_intensity(final_state.get("emotional_state"), datetime.now(timezone.utc))) 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) @@ -2283,7 +2283,7 @@ def _read_progress_notes(): 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))) + spawn_background_task(asyncio.to_thread(own_views.note, get_db(), username, 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") diff --git a/backend/components/sonic_changelog.py b/backend/components/sonic_changelog.py index 2cba932e..a5815193 100644 --- a/backend/components/sonic_changelog.py +++ b/backend/components/sonic_changelog.py @@ -1692,7 +1692,7 @@ "month": "2026-11", "title": "I check a change right after you apply it", "line": ( - "Right after you apply a change I made, I run the one check of yours that fits it (its own tests, or the type check) and fix what it finds in the same turn. Turn on \"Check my changes right after I apply them\" for your runner and it runs without a click." + "After you apply a change I made, I run your own check that fits it and fix what it finds. Turn on \"Check my changes right after I apply them\" and it runs without a click, unless I read outside text like a web page that turn." ), "keywords": ["check after apply", "run the tests after", "type check after", "verify my change", "check my changes", "after edit check"], "volunteer": [], @@ -2121,7 +2121,7 @@ "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." + "When you're having a rough time, short of something heavy, 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/services/agent_workflow.py b/backend/services/agent_workflow.py index 71836421..e03a83d5 100644 --- a/backend/services/agent_workflow.py +++ b/backend/services/agent_workflow.py @@ -4051,6 +4051,11 @@ async def _after_edit_check(changed: list) -> str: if not runner_jobs.settings_of(runner_for_checks)["after_edit_auto"]: await asyncio.to_thread(record_turn_counts, {"code_after_edit_check_suggested": 1}) return after_edit_check.suggestion(choice) + held = after_edit_check.held_back(choice, changed, runner_jobs.runnable_checks(runner_for_checks), + read_others_text=bool(untrusted_used & _THIRD_PARTY_TEXT_TOOLS)) + if held: + await asyncio.to_thread(record_turn_counts, {"code_after_edit_check_held": 1}) + return after_edit_check.suggestion(choice) + f" It did not run by itself because {held}. Say so in one sentence." db = get_db() try: job = await asyncio.to_thread(runner_jobs.create_job, db, username, runner_for_checks["id"], choice["check"], choice["files"], None, runner_for_checks.get("project_id"), True) diff --git a/backend/services/native_loop.py b/backend/services/native_loop.py index 43373ec0..8dcb60d3 100644 --- a/backend/services/native_loop.py +++ b/backend/services/native_loop.py @@ -38,7 +38,7 @@ from langchain_core.messages import HumanMessage, SystemMessage, ToolMessage -from backend.utils import act_not_suggest, advisor as advisor_module, answer_checks, claim_check, combo as combo_rules, diff_review, draft_checkpoint, handback_check, loop_progress, loop_rhythm, multi_read, reading_waste +from backend.utils import act_not_suggest, advisor as advisor_module, after_edit_check, answer_checks, claim_check, combo as combo_rules, diff_review, draft_checkpoint, handback_check, loop_progress, loop_rhythm, multi_read, reading_waste from backend.utils.log_hygiene import describe_tool_result from backend.utils.prompt_meter import PromptMeter from backend.utils.agent_utils import _UnsafeActionRequested, build_tool_facts, build_trace_subject, new_trace_step_id @@ -666,7 +666,7 @@ def required_done() -> bool: outcome = await run_checkpoint(step - 1) if outcome == "answered" and handback_in_scope() and (handed_back := handback_check.kind( final_text or "", coding_turn=claim_checking, edited=edited_this_turn(), offered=offered, steps_left=budget - step + 1, - checked=any(str(a.get("action_desc", "")).startswith(("run_local_check(", "run_local_command(", "run_sandbox_tests(")) for a in attempts), check_failed=handback_check.last_check_failed(attempts))) and handback_check.may_send_back(answer_sent_back, handed_back): + checked=handback_check.check_ran(attempts), check_failed=handback_check.last_check_failed(attempts))) and handback_check.may_send_back(answer_sent_back, handed_back): # An answer at the checkpoint used to end the turn with no check at all (2026-11-27: after an applied edit, "The morph still isn't wired ... it needs a new request", 13 steps left). It is held to the # same hand-back rule as any answer. messages.append(HumanMessage(content=send_back_handback(handed_back, budget - step + 1))) @@ -749,7 +749,7 @@ def required_done() -> bool: notice = answer_checks.NO_READ_NOTICE elif handback_in_scope() and (handed_back := handback_check.kind( answer, coding_turn=claim_checking, edited=edited_this_turn(), offered=offered, steps_left=budget - step, - checked=any(str(a.get("action_desc", "")).startswith(("run_local_check(", "run_local_command(", "run_sandbox_tests(")) for a in attempts), check_failed=handback_check.last_check_failed(attempts))) and handback_check.may_send_back(answer_sent_back, handed_back): + checked=handback_check.check_ran(attempts), check_failed=handback_check.last_check_failed(attempts))) and handback_check.may_send_back(answer_sent_back, handed_back): # The answer ends by offering to carry on, saying the work is not finished, or telling the person to run it themselves, with steps left and the tools to do it (backend/utils/handback_check.py): # sent back, and an "unfinished" or "offer" one again while it keeps saying so (up to handback_check.MAX_REPEATS: 2026-11-27, one send-back was not enough). notice = send_back_handback(handed_back, budget - step) @@ -826,7 +826,7 @@ def required_done() -> bool: fed = HumanMessage(content=block) messages.append(fed) held.append({"message": fed, "step": step, "text": block, "done": False, "key": f"plan_feed|{step}"}) - if after_apply_hint and applied_now and not more_plan_steps: + if after_apply_hint and applied_now and not more_plan_steps and not any(after_edit_check.finished_in(result) for result in results): # An edit was just applied: say what to do next (check it, or write the test it needs first), from the server, so it is not left to the model to remember. Not while an approved plan still has # steps to go: its tests are usually a later step, and a check run before they exist can only fail or run nothing (Jack, 2026-10-28). It joins the held results and is shortened like any old one. hint = HumanMessage(content=after_apply_hint) diff --git a/backend/tests/test_after_edit_check.py b/backend/tests/test_after_edit_check.py index 3d1cf3d4..e4c32423 100644 --- a/backend/tests/test_after_edit_check.py +++ b/backend/tests/test_after_edit_check.py @@ -246,3 +246,212 @@ async def test_an_unfinished_automatic_run_does_not_count_as_checking(monkeypatc seen = await _drive(monkeypatch, lambda pid: led.decide("jack", pid, "applied"), state_extra={"runner_cards": True}) assert asked["jobs"] and "NOT FINISHED" in seen["observation"] # it did run the check, so the assertion below is not vacuous assert "run_local_check" not in turn.tools + + +# ---- a check is chosen by what it runs, never by a word in its command (2026-11-27 review) ------------------------------------------------------ + +def _named(name, command, ready=True): + return {"name": name, "command": command, "ready": ready} + + +def test_a_deploy_script_is_never_picked_because_its_command_says_npm(): + deploy, e2e = _named("deploy", "npm run deploy"), _named("e2e", "npm run e2e") + assert aec.pick(["src/a.test.js"], [deploy, e2e], []) is None + assert aec.pick(["src/a.test.js"], [deploy, JS], []) == {"check": "js-tests", "files": []} # listed after it, and still the one picked + assert aec.pick(["src/a.test.js"], [_named("unit", "npm run test -- --watch=false")], []) == {"check": "unit", "files": []} + assert aec.pick(["src/a.test.js"], [_named("unit", "C:/nodejs/npm.cmd test")], []) == {"check": "unit", "files": []} + for command in ("npm run testing-deploy", "npm install test", "echo npm test", "cargo test", "make run test"): + assert aec.pick(["src/a.test.js"], [_named("x", command)], []) is None, command + assert aec.pick(["src/a.test.js"], [_named("js-tests", "npx vitest run")], []) == {"check": "js-tests", "files": []} # their own check under the preset's name + + +def test_the_type_check_is_a_command_that_runs_tsc_whatever_it_is_called(): + assert aec.pick(["a.ts"], [_named("release", "python scripts/tscribe_release.py")], []) is None + assert aec.pick(["a.ts"], [_named("release", "echo tsc")], []) is None + assert aec.pick(["a.ts"], [_named("types", "npm run deploy")], []) is None # the name alone is not enough + for command in ("npx tsc -b", "tsc --noEmit", "node_modules/.bin/tsc -b", '"C:\\a b\\node_modules\\.bin\\tsc.cmd" -b'): + assert aec.pick(["a.ts"], [_named("ts", command)], []) == {"check": "ts", "files": []}, command + both = [_named("other-tsc", "tsc -p other"), TYPES] + assert aec.pick(["a.ts"], both, [])["check"] == "types" # the preset first + + +def test_the_python_check_runs_pytest_by_program_or_module_and_prefers_the_preset(): + for command in ("pytest -q {files}", '"C:\\my app\\.venv\\Scripts\\python.exe" -m pytest -q {files}', ".venv/bin/pytest {files}"): + assert aec.pick(["backend/utils/thing.py"], [_named("t", command)], FOLDER)["check"] == "t", command + for command in ("python scripts/pytest_report_upload.py {files}", "echo pytest {files}"): + assert aec.pick(["backend/utils/thing.py"], [_named("t", command)], FOLDER) is None, command + assert aec.pick(["backend/utils/thing.py"], [_named("slow", "pytest --runslow {files}"), PYTEST], FOLDER)["check"] == "tests" + + +# ---- when an automatic run waits for the press --------------------------------------------------------------------------------------------------- + +def test_a_run_waits_for_the_press_after_someone_elses_text_was_read(): + choice = {"check": "tests", "files": ["tests/test_app.py"]} + assert "written by someone else" in aec.held_back(choice, ["src/app.py"], [PYTEST], read_others_text=True) + assert aec.held_back(choice, ["src/app.py"], [PYTEST], read_others_text=False) == "" + + +def test_a_run_waits_when_the_change_edits_the_file_that_defines_an_npm_check(): + js = {"check": "js-tests", "files": []} + assert "package.json" in aec.held_back(js, ["local/package.json", "src/a.test.js"], [JS], read_others_text=False) + assert aec.held_back(js, ["src/a.test.js", "package.json.md"], [JS], read_others_text=False) == "" + assert aec.held_back({"check": "types", "files": []}, ["package.json", "a.ts"], [TYPES], read_others_text=False) == "" # npx tsc is not an npm script + + +def test_every_tool_that_reads_server_logs_or_incidents_counts_as_someone_elses_text(): + assert set(aw.ops_incidents.OPS_ACTIONS) <= aw._THIRD_PARTY_TEXT_TOOLS + assert {"read_url", "web_search", "read_gmail_message", "read_drive_file", "search_library"} <= aw._THIRD_PARTY_TEXT_TOOLS + assert not {"run_local_check", "run_local_command", "read_repo_file"} & aw._THIRD_PARTY_TEXT_TOOLS # their own machine and project do not + + +@run_async +async def test_with_the_setting_on_nothing_runs_by_itself_after_someone_elses_text_was_read(monkeypatch): + _connect_folder() + asked = _runner(monkeypatch, True, PASSED_RUN) + + async def read_others(act, kwargs=None): + return await act({"tool_action": "list_app_incidents", "args": {}}) # refused for a non-admin, but it counts the moment it is asked for + + seen = await _drive(monkeypatch, lambda pid: led.decide("jack", pid, "applied"), before=read_others, state_extra={"runner_cards": True}) + assert asked["jobs"] == [] and 'run_local_check with check "tests"' in seen["observation"] and "did not run by itself" in seen["observation"] + assert "RAN BY ITSELF" not in seen["observation"] and {"code_after_edit_check_held": 1} in asked["counts"] + + +@run_async +async def test_reading_their_own_project_does_not_hold_the_run(monkeypatch): + _connect_folder() + asked = _runner(monkeypatch, True, PASSED_RUN) + + async def read_own(act, kwargs=None): + return await act({"tool_action": "read_repo_file", "args": {"path": "src/app.py"}}) + + await _drive(monkeypatch, lambda pid: led.decide("jack", pid, "applied"), before=read_own, state_extra={"runner_cards": True}) + assert [job["after_edit"] for job in asked["jobs"]] == [True] and not any("code_after_edit_check_held" in c for c in asked["counts"]) + + +@run_async +async def test_output_from_their_own_machine_does_not_hold_the_run(monkeypatch): + _connect_folder() + asked = _runner(monkeypatch, True, PASSED_RUN) + + async def look(act, kwargs=None): + return await act({"tool_action": "look_at_local_page", "args": {}}) # their own app's page: untrusted for a commit, but not someone else's text + + await _drive(monkeypatch, lambda pid: led.decide("jack", pid, "applied"), before=look, state_extra={"runner_cards": True}) + assert [job["after_edit"] for job in asked["jobs"]] == [True] and not any("code_after_edit_check_held" in c for c in asked["counts"]) + + +@run_async +async def test_a_held_check_is_not_held_when_the_setting_is_off_it_is_just_named(monkeypatch): + _connect_folder() + asked = _runner(monkeypatch, False, PASSED_RUN) + + async def read_others(act, kwargs=None): + return await act({"tool_action": "list_app_incidents", "args": {}}) + + seen = await _drive(monkeypatch, lambda pid: led.decide("jack", pid, "applied"), before=read_others, state_extra={"runner_cards": True}) + assert "did not run by itself" not in seen["observation"] and {"code_after_edit_check_suggested": 1} in asked["counts"] and asked["jobs"] == [] + + +# ---- the rest of the loop sees an automatic run ------------------------------------------------------------------------------------------------- + +def _applied(exit_code=0, status=None, name="tests"): + """The propose_local_edits result as the loop gets it when the check ran by itself, built with the real formatter.""" + job = {"id": "j1", "check": name, "status": status or rj.DONE, "exit_code": exit_code, "duration": 2, "output_tail": "1 passed"} + return "Proposed 1 edit. APPLIED: the person applied the edits." + aec.result_note({"check": name, "files": []}, rj.format_result(job), exit_code == 0 and status is None) + + +def _receipt(tool, observation): + return {"purpose": f"Run {tool}", "action_desc": f"{tool}(...)", "observation": observation} + + +def test_an_automatic_run_is_read_only_from_an_applied_result_after_its_mark(): + assert aec.ran_in(_applied(0)).startswith("LOCAL CHECK tests PASSED") and aec.finished_in(_applied(1)) + assert aec.ran_in("DECLINED: no " + aec.AUTO_RAN_MARK + "\nLOCAL CHECK tests PASSED (exit code 0)") == "" # not applied + assert aec.ran_in("Proposed. APPLIED: done. LOCAL CHECK tests PASSED (exit code 0)") == "" # no mark: nothing ran by itself + assert aec.ran_in(aec.AUTO_RAN_MARK + " LOCAL CHECK tests PASSED ... APPLIED: later") == "" # a mark before the APPLIED is not one + assert aec.finished_in(_applied(0, status=rj.RUNNING)) is False and aec.ran_in(_applied(0, status=rj.RUNNING)) != "" + assert aec.finished_in("Proposed. APPLIED: done.") is False and aec.ran_in(None) == "" + + +def test_a_receipt_for_the_run_is_added_after_its_apply_and_nowhere_else(): + plain, applied = _receipt("read_repo_file", _applied(0)), _receipt("propose_local_edits", _applied(0)) + assert aec.with_runs([plain]) == [plain] # only an Apply can hold one + seen = aec.with_runs([plain, applied, _receipt("find_file", "x")]) + assert [r["purpose"] for r in seen] == ["Run read_repo_file", "Run propose_local_edits", "Run run_local_check", "Run find_file"] + assert seen[2]["observation"].startswith("LOCAL CHECK tests PASSED") and aec.with_runs(None) == [] + + +def test_a_pass_that_ran_by_itself_backs_the_claim_and_a_failure_reads_as_failed(): + from backend.utils import claim_check, handback_check + + passed, failed = [_receipt("propose_local_edits", _applied(0))], [_receipt("propose_local_edits", _applied(1))] + assert claim_check.evidence(passed) == {"tests": "passed"} and claim_check.unproven("The tests pass.", claim_check.evidence(passed)) == [] + assert claim_check.evidence(failed) == {"tests": "failed"} and "failed in this turn" in claim_check.note_for(["tests"], claim_check.evidence(failed)) + assert handback_check.check_ran(passed) and handback_check.check_ran(failed) and not handback_check.check_ran([_receipt("propose_local_edits", "APPLIED: x")]) + assert handback_check.last_check_failed(failed) is True and handback_check.last_check_failed(passed) is False + assert handback_check.last_check_failed(failed + [_receipt("read_repo_file", "text")]) is False # it did something about it since + + +def test_a_run_of_the_check_called_types_is_a_type_check(): + from backend.utils import claim_check + + by_hand = rj.format_result({"check": "types", "status": rj.DONE, "exit_code": 0, "duration": 1}) + assert claim_check.evidence([_receipt("run_local_check", by_hand)]) == {"typecheck": "passed"} # it read as no run at all, even by hand + assert claim_check.evidence([_receipt("propose_local_edits", _applied(0, name="types"))]) == {"typecheck": "passed"} + assert claim_check.evidence([_receipt("run_local_check", by_hand.replace("types", "prototypes"))]) == {} + + +def test_the_rhythm_and_the_combo_count_an_automatic_run(): + from backend.utils.combo import Combo + from backend.utils.loop_rhythm import LoopRhythm + + ran, not_ran = LoopRhythm(), LoopRhythm() + ran.after_step([("propose_local_edits", _applied(1))], 1) + ran.after_step([("read_repo_file", "x")], 2) + not_ran.after_step([("propose_local_edits", "Proposed. APPLIED: done.")], 1) + assert (ran.applies, ran.applies_checked) == (1, 1) and (not_ran.applies, not_ran.applies_checked) == (1, 0) + unfinished = LoopRhythm() + unfinished.after_step([("propose_local_edits", _applied(0, status=rj.RUNNING))], 1) + assert unfinished.applies_checked == 0 + tools = {"propose_local_edits", "run_local_check"} + for result, failed_new in ((_applied(1), True), (_applied(0), False), ("Proposed. APPLIED: done.", False)): + combo = Combo(tools) + earned = combo.after_step([{"name": "propose_local_edits"}], [result]) + assert earned["failed_new"] is failed_new and combo.failed_new == int(failed_new) and earned["grant"] == 4, result[:60] + + +# ---- through the native loop --------------------------------------------------------------------------------------------------------------------- + +def _loop(applied_result, answer_texts, **kwargs): + import asyncio + + from backend.services import native_loop + from backend.tests.test_loop_rhythm import Reply, ScriptedLLM, call + + llm = ScriptedLLM([Reply([call("propose_local_edits", 1, summary="s", edits=[])])] + [Reply([], text) for text in answer_texts]) + + async def act(decision): + return applied_result + + out = asyncio.run(native_loop.run(llm=llm, tools=[{"name": n} for n in ("read_repo_file", "propose_local_edits", "run_local_check")], act=act, question="make the greeting friendlier", max_steps=12, + after_apply_hint="NEXT: run the check now.", **kwargs)) + return llm, out + + +def test_after_a_pass_the_loop_neither_asks_for_the_check_again_nor_sends_a_true_claim_back(): + llm, out = _loop(_applied(0), ["I changed the greeting and the tests pass."]) + assert out["final_answer"] == "I changed the greeting and the tests pass." and len(llm.seen) == 2 + assert not any("NEXT:" in text or "CHECK YOUR CLAIM" in text for text in llm.seen[1]) + + +def test_an_unfinished_automatic_run_still_gets_the_hint(): + llm, _ = _loop(_applied(0, status=rj.RUNNING), ["I changed the greeting."]) + assert any(text == "NEXT: run the check now." for text in llm.seen[1]) + + +def test_after_a_failure_a_claim_of_a_pass_is_sent_back_and_so_is_an_answer_that_ignores_it(): + llm, out = _loop(_applied(1), ["Done, the tests pass.", "I changed the greeting.", "The test fails because of an old assertion."]) + assert not any("NEXT:" in text for text in llm.seen[1]) + assert any("CHECK YOUR CLAIM" in text for text in llm.seen[2]) + assert any("Your last check FAILED" in text for text in llm.seen[3]) and out["final_answer"] == "The test fails because of an old assertion." diff --git a/backend/tests/test_edit_corrections.py b/backend/tests/test_edit_corrections.py index 79a54adc..90bee7a4 100644 --- a/backend/tests/test_edit_corrections.py +++ b/backend/tests/test_edit_corrections.py @@ -207,3 +207,75 @@ def test_app_takes_it_out_only_when_an_edit_was_applied_this_turn(): assert 'int((getattr(llm_turn, "rhythm", None) or {}).get("applies", 0) or 0) > 0' in source[at - 400:at] assert 'tally(turn_counts, "claim_denial_dropped")' in source[at:at + 300] assert source.find("'event': 'final_generation'", at) > at # before the final text is sent, so the screen shows it too + + +# ---- a message that asks Sonic to hold off is not an edit request (2026-11-27 review) ----------------------------------------------------------- + +# One message for each way of saying it, so a rule that stops working shows up on its own line. Every one came out as an edit turn (or would have, as an explicit request) before. +HOLDS = ( + "wait, dont change anything yet", # don't + change, opening a clause + "no stop, the loader", # a bare "stop" + "dont change the loader", # ... even when it names code, which read as an explicit request + "no stop, leave the loader alone", # stop + leave it alone + "no. leave the logo as is.", # leave as is + "just leave it how it is", + "i think we should leave the loader as is", # should leave, said inside a sentence + "stop changing the logo", + "hold off on the loader for now", + "hold on, the loader", + "never mind the loader", + "no need to change it, the loader looks right", + "hmm just explain the loader to me instead", + "can you just walk me through the loader", + "no that makes sense, the loader works like that", + "i dont want you to change the animation", + "wait i need to think about the loader", + "let me think about the animation", + "ugh i should have saved the logo file myself", + "just explain the loader and dont change anything", # two holds, nothing else + "dont change the header and footer", +) + + +def test_a_message_that_asks_to_hold_off_is_never_an_edit_turn(): + for text in HOLDS: + assert au.holds_off(text) is True, text + assert edit_turn(text, REQUEST, coding_reply()) is False, text + + +def test_a_hold_off_wins_over_a_yes_to_an_offer(): + asked = AIMessage(content="I can change the loader in thinkingLogoMotion.ts if you like. Should I?") + assert edit_turn("no, dont do it", REQUEST, asked) is False + + +def test_another_clause_that_still_asks_for_a_change_wins_over_the_hold(): + for text in ( + "no dont change the color, change the size instead", # an edit verb elsewhere + "dont touch the header but make the loader bigger", # split on "but" + "can you explain why the loader fails and fix it", # split on "and" + "tell me why the loader fails then update the test", # split on "then" + "never mind the logo, fix the loader header", + "i should have mentioned, the loader needs to be blue", # a "needs to" elsewhere + ): + assert au.holds_off(text) is False, text + assert edit_turn(text, REQUEST, coding_reply()) is True, text + for text in ("yes go ahead, never mind the tests", "go ahead, no need to change the tests", "do it, dont touch the header", "yeah that makes sense, go for it"): + assert au.holds_off(text) is False, text # a go-ahead elsewhere + + +def test_words_that_describe_the_code_are_not_a_hold(): + """The same words in the middle of a request: a bug report, or what the change should do.""" + for text in ( + "change the loader so it does not leave the dots alone at the end", + "the tooltip should just explain the setting in the loader", + "it should stop changing the loader color", + "the loader should have no need to restart, fix it", + "add a hold off delay to the loader button", + "make the loader never mind the hover state", + "the buttons dont change color on hover, fix that", + "wait no, the loader should not stop between stages", + "the helix should leave a trail and it needs to loop", + "no need to rush, the loader still pops in", # "no need to" holds only before a change verb + ): + assert au.holds_off(text) is False, text + assert edit_turn(text, REQUEST, coding_reply()) is True, text diff --git a/backend/tests/test_native_loop.py b/backend/tests/test_native_loop.py index a55e549a..4312aaa0 100644 --- a/backend/tests/test_native_loop.py +++ b/backend/tests/test_native_loop.py @@ -593,11 +593,14 @@ def test_the_untrusted_data_rule_still_protects_a_native_turn(world): def test_mid_run_steering_reaches_the_native_engine_through_the_real_steering_module(world): key = "u::steer1" - steering.open_run(key, []) + run = steering.open_run(key, []) llm = ToolLLM(asks(call("check_deploy_status")), asks(call("list_app_incidents")), answers("Checked both."), on_call=lambda n: steering.submit(key, "also list the incidents") if n == 1 else None) sdk = world.configure(["Global_Admins"], llm) - result = turn("check the deploy", session="steer1") + try: + result = turn("check the deploy", session="steer1") + finally: + steering.close_run(key, run) # an open turn left behind is seen by every later wait in this process (steering.wait_event), which broke another file's waits assert "Checked both." in result["content_to_format"] assert sdk.calls == ["list"] # the first plan (deploy) was discarded when the steer arrived assert any(m.content.startswith("USER STEERING") and "also list the incidents" in m.content for m in llm.calls[1][0] if isinstance(m, HumanMessage)) diff --git a/backend/tests/test_own_voice.py b/backend/tests/test_own_voice.py index 0a52de63..1dcb3d54 100644 --- a/backend/tests/test_own_voice.py +++ b/backend/tests/test_own_voice.py @@ -124,38 +124,61 @@ def test_a_stance_is_offered_as_its_own_view_and_counted_as_used_only_when_the_r 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 + assert own_views.note(db, "sam", 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 + assert set(kept[0]) == {"_id", "id", "username", "text", "at", "expires_at"} # the sentence and when: nothing else about the turn + assert "Thank you" not in str(kept[0]) and "slow before" not in str(kept[0]) # not the rest of the reply either + assert own_views.note(db, "sam", reply, NOW) is False and len(db[own_views.COLLECTION].find({})) == 1 + assert own_views.note(db, "sam", "That sounds like a long day.", NOW) is False # no view, nothing kept + assert own_views.note(db, "sam", "I think so.", NOW) is False # a view no later message could ever find is not kept + assert own_views.note(None, "sam", reply, NOW) is False and own_views.note(db, "", 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)) + own_views.note(db, "sam", 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)) + own_views.note(db, "sam", "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)) + own_views.note(db, "kim", "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_a_view_is_found_by_the_words_of_its_own_sentence_two_of_them_or_more(): + kept = [{"text": "I think waiting until Friday before answering the landlord is reasonable.", "at": NOW - timedelta(days=2)}] + assert own_views.pick(kept, "the landlord is on my mind", NOW) is None # one shared word is not enough + assert own_views.pick(kept, "the landlord again, and it is nearly friday", NOW) is kept[0] and own_views.MIN_SHARED == 2 + + +def test_words_an_older_document_took_from_their_message_are_ignored(): + """The first version stored words from the person's message. Those documents may still be there: the extra field must play no part.""" + old = {"text": "I think waiting until Friday is reasonable here.", "words": ["devin", "drinking", "friday", "layoff", "waiting"], "at": NOW - timedelta(days=2)} + assert own_views.pick([old], "devin and the drinking and the layoff", NOW) is None + assert own_views.pick([old], "still waiting, is friday too long", NOW) is old + + +def test_nothing_of_their_message_can_reach_the_store(): + assert "own_views.note, get_db(), username, plain_quotes(full_response)" in APP # only Sonic's reply is handed over + db = FakeDB() + own_views.note(db, "sam", "I think your sister has a point about the timing, and you can still ask her why.", NOW) + (doc,) = db[own_views.COLLECTION].find({}) + assert "words" not in doc and set(doc) == {"_id", "id", "username", "text", "at", "expires_at"} + + 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 @@ -248,6 +271,51 @@ def test_the_first_reading_that_applies_wins_and_each_gets_one_line(): assert self_counters._GROUPS["doing"] == message_doing.KINDS and "doing_news" in self_counters.KEYS + +@pytest.mark.parametrize("message", [ + "i have to go to my grandpa's funeral tomorrow and i dont know how ill get through it", + "i should go apologize to her but im terrified", + "i have to go back to that job on monday and i cant stand it", + "lol i hate myself", # harsh about themselves + "haha im so worthless", + "my grandma died today", # grief is not "news" to answer without checking on them + "i just got dumped lol", + "haha is it bad that i dont want to be here anymore", + "ok going to bed, i cant do this", + "lol i got the diagnosis today", + "the funeral is today lol", # one word each, so each rule is shown on its own + "i cant stand mondays lol", + "ugh i hate this lol", + "haha i dont even bother anymore", +]) +def test_nothing_is_said_about_what_a_heavy_message_is_doing(message): + assert message_doing.heavy(message) is True and message_doing.kind(message) is None + + +@pytest.mark.parametrize("message", [ + "i should go talk to her", "i have to go to work tomorrow", "i have to go see my dad", "gotta run a test first", "i should head out to the shop later", + "i cant go to sleep", "ive been going to sleep late", "im not going to bed until she answers", "every night before i go to bed i check", "i keep trying to sleep", + "going to sleep like this every night", "i need to sleep on it", "gonna sleep over at her place", "gonna crash out on the couch with him", "going to bed with the window open", +]) +def test_leaving_for_the_night_has_to_mean_leaving_now(message): + assert message_doing.kind(message) != "winding_down", message + + +@pytest.mark.parametrize("message", [ + "ok I'm going to bed, long day", "im gonna crash, night", "gotta go", "i should go, talk later", "i have to go now", "heading to sleep", "i should sleep.", "i should get to bed", + "i need to get some sleep", "calling it a night", "trying to get some sleep", "gotta sleep", "alright i should run for tonight", +]) +def test_a_real_goodnight_is_still_read(message): + assert message_doing.kind(message) == "winding_down", message + + +def test_a_strong_feeling_silences_it_and_the_line_points_at_the_rest_of_the_guidance(): + strong = message_doing.HEAVY_INTENSITY + assert message_doing.kind("ok going to bed", strong) is None and message_doing.kind("ok going to bed", strong - 0.01) == "winding_down" + assert message_doing.kind("ok going to bed", None) == "winding_down" and message_doing.kind("lol of course she cancelled again", 0.9) is None + assert "and the rest of your guidance still holds" in message_doing.build_block("asking") + + # ---- the capped stronger voice --------------------------------------------------------------------------------------------------------------- def test_the_stronger_voice_is_off_unless_switched_on(monkeypatch): @@ -345,7 +413,8 @@ def test_every_new_counter_is_registered_and_counted_in_the_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 ("message_doing.kind(_their_words, effective_intensity(final_state.get(\"emotional_state\"), datetime.now(timezone.utc))) " + "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 diff --git a/backend/utils/after_edit_check.py b/backend/utils/after_edit_check.py index 6bba897e..170c66fc 100644 --- a/backend/utils/after_edit_check.py +++ b/backend/utils/after_edit_check.py @@ -9,18 +9,28 @@ - A JavaScript/TypeScript test file changed (`.test.mjs`, `.test.ts`, ...) and there is no type check: the project's JS test script. It runs without a press only when the person turned that on for this runner (runner_jobs settings `after_edit_auto`, off until they do); otherwise the Apply result names the check so the model runs it -(the person then presses Run on the usual card). Pure: no I/O, no clock. +(the person then presses Run on the usual card). EVEN WITH IT ON, it waits for the press (`held_back`) when the message read text someone else wrote (the Run button is what stands between a +hidden instruction and code running on their machine), or when the change edits package.json and the check is an npm script, which package.json defines. + +A CHECK IS CHOSEN BY WHAT IT RUNS, never by a word somewhere in its command (2026-11-27: "npm" anywhere picked a deploy script, "tsc" inside "tscribe_release.py" picked a release). + +THE REST OF THE LOOP MUST SEE THE RUN (`with_runs`): its result is folded into the propose_local_edits result, and what asks "did a check run, and did it pass?" reads run_local_check results. +Pure: no I/O, no clock. """ from __future__ import annotations import posixpath -from typing import Any, Dict, Iterable, List, Optional +import re +from typing import Any, Callable, Dict, Iterable, List, Optional MAX_TEST_FILES = 6 WAIT_SECONDS = 240 # how long an automatic run may hold the turn; a slower check is reported as not finished and the model can carry on _JS_TEST_SUFFIXES = (".test.mjs", ".test.js", ".test.ts", ".test.tsx", ".spec.ts", ".spec.js") _TS_SUFFIXES = (".ts", ".tsx") +AUTO_RAN_MARK = "THEIR CHECK RAN BY ITSELF AFTER THE APPLY" +_FINISHED_RE = re.compile(r"^LOCAL CHECK \S+ (?:PASSED|FAILED)\b") +_WORD_RE = re.compile(r"'[^']*'|\"[^\"]*\"|\S+") def _is_python_test(path: str) -> bool: @@ -28,18 +38,37 @@ def _is_python_test(path: str) -> bool: return name.endswith(".py") and (name.startswith("test_") or name.endswith("_test.py")) -def _check(checks: Iterable[Dict[str, Any]], *, takes_files: bool = False, word: str = "", name: str = "") -> Optional[Dict[str, Any]]: - for item in checks: - command = str(item.get("command") or "") - if item.get("ready") is False: - continue - if name and item.get("name") != name: - continue - if word and word not in command: - continue - if takes_files and "{files}" not in command: - continue - return item +def _words(command: Any) -> List[str]: + """A check's command as the words that are run (it is shown quoted where a word has spaces). Pure.""" + return [word.strip("'\"") for word in _WORD_RE.findall(str(command or ""))] + + +def _program(word: str) -> str: + """The program a command word names: "C:\\x\\.venv\\Scripts\\python.exe" is "python", "npm.cmd" is "npm". Pure.""" + name = re.split(r"[\\/]", word)[-1].lower() + return re.sub(r"\.(?:exe|cmd)$", "", name) + + +def runs_pytest(words: List[str]) -> bool: + return bool(words) and (_program(words[0]) == "pytest" or any(first == "-m" and second == "pytest" for first, second in zip(words, words[1:]))) + + +def runs_tsc(words: List[str]) -> bool: + return bool(words) and (_program(words[0]) == "tsc" or (_program(words[0]) == "npx" and words[1:2] == ["tsc"])) + + +def runs_npm_test(words: List[str]) -> bool: + return bool(words) and _program(words[0]) == "npm" and (words[1:2] == ["test"] or words[1:3] == ["run", "test"]) + + +def _check(checks: Iterable[Dict[str, Any]], preset: str, fits: Callable[[List[str]], bool], *, takes_files: bool = False, preset_is_enough: bool = False) -> Optional[Dict[str, Any]]: + """The check to use for one kind of change: one whose command really runs that kind (`fits`), the runner's preset name first. With `preset_is_enough`, a check carrying the preset's name + counts whatever it runs (the person named it so in their own config).""" + usable = [item for item in checks if item.get("ready") is not False and (not takes_files or "{files}" in str(item.get("command") or ""))] + usable.sort(key=lambda item: item.get("name") != preset) # stable: otherwise the runner's own order + for item in usable: + if fits(_words(item.get("command"))) or (preset_is_enough and item.get("name") == preset): + return item return None @@ -63,20 +92,59 @@ def pick(changed: Iterable[str], checks: Iterable[Dict[str, Any]], folder_paths: return None tests = python_tests_for(changed, folder_paths) if tests: - pytest_check = _check(checks, takes_files=True, word="pytest") + pytest_check = _check(checks, "tests", runs_pytest, takes_files=True) if pytest_check: return {"check": pytest_check["name"], "files": tests} if any(path.endswith(_TS_SUFFIXES) for path in changed): - types = _check(checks, word="tsc") + types = _check(checks, "types", runs_tsc) if types: return {"check": types["name"], "files": []} if any(path.endswith(_JS_TEST_SUFFIXES) for path in changed): - js_tests = _check(checks, word="npm") or _check(checks, name="js-tests") + js_tests = _check(checks, "js-tests", runs_npm_test, preset_is_enough=True) if js_tests: return {"check": js_tests["name"], "files": []} return None +def held_back(choice: Dict[str, Any], changed: Iterable[str], checks: Iterable[Dict[str, Any]], *, read_others_text: bool) -> str: + """Why a check that would run by itself waits for the person's press instead, in words for the model, or "". Pure.""" + if read_others_text: + return "this message read text written by someone else (a web page, an email, a shared document or a log), so running it needs their press" + command = next((item.get("command") for item in checks or [] if item.get("name") == choice.get("check")), "") + words = _words(command) + if words and _program(words[0]) == "npm" and any(posixpath.basename(str(path)) == "package.json" for path in changed or []): + return "this change edits package.json, which decides what that npm check runs" + return "" + + +def ran_in(result: Any) -> str: + """The check's own result (from "LOCAL CHECK ..." on) inside an Apply result when the check ran by itself, or "". Read only after the mark in an APPLIED result. Pure.""" + text = str(result or "") + applied = text.find(" APPLIED:") + mark = text.find(AUTO_RAN_MARK, applied) if applied >= 0 else -1 + head = text.find("LOCAL CHECK ", mark) if mark >= 0 else -1 + return text[head:] if head >= 0 else "" + + +def finished_in(result: Any) -> bool: + """Whether an Apply result holds an automatic run that came back with a result, passed or failed. Pure.""" + return bool(_FINISHED_RE.match(ran_in(result))) + + +def with_runs(attempts: Optional[Iterable[Dict[str, Any]]]) -> List[Dict[str, Any]]: + """The turn's receipts ({"purpose", "action_desc", "observation"}) with one run_local_check receipt added after each Apply whose check ran by itself, so that a pass, a failure and "a check + ran" read the same as when the model called the check. Pure.""" + seen: List[Dict[str, Any]] = [] + for attempt in attempts or []: + seen.append(attempt) + if str(attempt.get("purpose") or "") != "Run propose_local_edits": + continue + ran = ran_in(attempt.get("observation")) + if ran: + seen.append({"purpose": "Run run_local_check", "action_desc": "run_local_check(automatic, after the Apply)", "observation": ran}) + return seen + + def describe(choice: Dict[str, Any]) -> str: files = choice.get("files") or [] return f"{choice['check']}" + (f" on {', '.join(files)}" if files else "") @@ -91,7 +159,7 @@ def suggestion(choice: Dict[str, Any]) -> str: def result_note(choice: Dict[str, Any], formatted: str, passed: bool) -> str: """The Apply result's line after the check ran by itself: its real result, and what to do with it.""" - head = f"\n\nTHEIR CHECK RAN BY ITSELF AFTER THE APPLY ({describe(choice)}):\n{formatted}" + head = f"\n\n{AUTO_RAN_MARK} ({describe(choice)}):\n{formatted}" if passed: return head + "\nIt passed: do not run the same check again for this change." return head + "\nIf it failed because of this change, fix that now with propose_local_edits before you answer. If the failure is not from this change, say so plainly in your answer." diff --git a/backend/utils/agent_utils.py b/backend/utils/agent_utils.py index 48172fb4..e4358928 100644 --- a/backend/utils/agent_utils.py +++ b/backend/utils/agent_utils.py @@ -1262,6 +1262,9 @@ def continues_unfinished_edit(last: str, previous_ai: str, humans: list) -> bool r"|\b(?:still|just) (?:pops?|jumps?|flickers?|fades?|shows?|breaks?|fails?|bounces?)\b", re.IGNORECASE, ) +# The part of _CORRECTION_RE that asks for something (without the "no / ugh / wait" openers, which open a hold-off as often as a correction): what another clause needs to keep a held message a request. +_CORRECTION_ASK_RE = re.compile(r"\b(?:should(?:n'?t| not)?(?! have)|needs? to|has to|have to|must(?:n'?t)?|supposed to)\b", re.IGNORECASE) +_GO_AHEAD_RE = re.compile(r"\b(?:go ahead|go for it|do it|please do|send it|let'?s do (?:it|this|that))\b", re.IGNORECASE) # a yes in another clause wins: "go ahead, never mind the tests" _WORK_FILE_RE = re.compile(r"\b[\w./-]+\.(?:py|tsx?|jsx?|mjs|css|json|md|html|ya?ml|toml)\b", re.IGNORECASE) _WORK_REPLY_RE = re.compile(r"\b(?:applied|the edit|edits|proposed|propose|changed|diff|tests? (?:pass|fail)|passed|tsc|npm test|exits? 0|line \d+|lines \d+)\b", re.IGNORECASE) _PERSONAL_RE = re.compile( @@ -1299,6 +1302,36 @@ def _coding_reply(message, requests: list) -> bool: return bool(requests) and bool(_WORK_FILE_RE.search(text)) and bool(_WORK_REPLY_RE.search(text)) +# A message that asks Sonic to HOLD OFF (2026-11-27): "wait, dont change anything yet", "no stop, leave the loader alone", "hmm just explain it to me instead", "no need to change it" each came +# out as an edit turn, which sends a plain answer back with "call propose_local_edits... do not ask permission". Read clause by clause: it holds off when a clause says so and no OTHER clause +# still asks for a change ("don't change the colour, change the size instead" is a request). "Don't" and "explain" count only where they open a clause, so a bug report ("the buttons dont change +# colour on hover") and a correction ("the tooltip should just explain the setting") are not holds. +_CLAUSE_SPLIT_RE = re.compile(r"(?:[.!?;\n]+(?=\s|$))|,|\b(?:but|and|then)\b", re.IGNORECASE) # "explain why it fails and fix it" is a request: its second half is its own clause +_HOLD_LEAD = r"^\W*(?:(?:no|nah|nope|yes|yeah|yep|wait|ok|okay|please|pls|just|also|and|so|oh|um+|hmm+|ugh+|actually|hey|can you|could you|lets|let'?s)\W+)*" +_HOLD_RE = re.compile( + # said at the start of a clause, after nothing but openers: an instruction about what to do now + _HOLD_LEAD + r"(?:(?:don'?t|dont|do not)\s+(?:you\s+)?(?:change|edit|touch|modify|update|apply|propose|write|do (?:it|that|this|anything))\b" + r"|stop\W*$|stop (?:changing|editing|touching|proposing)\b|hold on\W*$|hold off\b|never ?mind\b|(?:there'?s |theres )?no need to (?:change|edit|touch|modify|update|propose|do (?:it|that|this|anything))\b" + r"|leave\b[^.!?,;]{0,40}\b(?:alone|as(?: it)? is|how it is|the way it is)\b" + r"|(?:just\s+)?(?:explain|walk me through|describe|tell me (?:about|how|why|what))\b|(?:that |it )?makes sense\b)" + # said anywhere: about the person's own next step, so never a description of the code + r"|\b(?:should|can) (?:just )?leave\b[^.!?,;]{0,40}\b(?:alone|as(?: it)? is|how it is|the way it is)\b" + r"|\bi (?:don'?t|dont|do not) want (?:you )?to (?:change|edit|touch|modify)\b" + r"|\b(?:i (?:need|want|have) (?:a (?:sec|second|minute) )?to think|let me think)\b" + r"|\bi (?:should'?ve|should have|shoulda)\b", + re.IGNORECASE, +) + + +def holds_off(text: str) -> bool: + """Whether the message asks for nothing to be changed now: a clause of it says to hold off, explain or leave it, and no other clause asks for a change. Pure.""" + clauses = [clause.strip() for clause in _CLAUSE_SPLIT_RE.split(str(text or "")) if clause and clause.strip()] + held = [clause for clause in clauses if _HOLD_RE.search(clause)] + if not held: + return False + return not any(_EDIT_VERB_RE.search(clause) or _CORRECTION_ASK_RE.search(clause) or _GO_AHEAD_RE.search(clause) for clause in clauses if clause not in held) + + def corrects_recent_change(last: str, replies: list, humans: list) -> bool: """Whether `last` corrects or directs coding work one of Sonic's last replies (`replies`, the messages themselves so their marks can be read, oldest first) was doing. See the comment above. Pure.""" if not replies or "?" in last or len(last.split()) > CORRECTION_MAX_WORDS or _COPING_ASK_RE.search(last) or _PERSONAL_RE.search(last) or _NOT_A_REQUEST_RE.search(last): @@ -1339,7 +1372,7 @@ def looks_like_edit_request(messages) -> bool: if not humans: return False last = _message_text(humans[-1]).strip() - if not last: + if not last or holds_off(last): return False def explicit(text: str) -> bool: diff --git a/backend/utils/claim_check.py b/backend/utils/claim_check.py index 63aff1f3..0f584e9f 100644 --- a/backend/utils/claim_check.py +++ b/backend/utils/claim_check.py @@ -15,6 +15,8 @@ import re from typing import Any, Dict, Iterable, List, Set +from backend.utils import after_edit_check + KINDS = ("typecheck", "tests", "lint", "build") LABEL = {"typecheck": "the type-check", "tests": "the tests", "lint": "the lint check", "build": "the build"} _PLURAL = {"tests"} @@ -46,6 +48,7 @@ "build": re.compile(r"\b(?:vite\s+build|npm\s+run\s+build|cargo\s+build|go\s+build|make\s+build|webpack)\b", re.I), } _TESTS_BY_NAME = re.compile(r"(?:^|[-_ ])tests?(?:$|[-_ ])", re.I) # a check NAMED "tests" or "backend-tests" (a command line that only mentions a tests folder is not a test run) +_TYPES_BY_NAME = re.compile(r"(?:^|[-_ ])types?(?:$|[-_ ])", re.I) # the runner's own preset is called "types" (npx tsc -b): a run of it was read as no type check at all _COMMAND_HEAD = re.compile(r"LOCAL COMMAND `([^`]*)` FINISHED with exit code (-?\d+)") _CHECK_HEAD = re.compile(r"LOCAL CHECK (\S+) (PASSED|FAILED)\b") _SANDBOX_TOOLS = ("run_sandbox_tests", "run_repo_tests") @@ -71,7 +74,7 @@ def _kinds_run(line: str) -> Set[str]: def evidence(attempts: Iterable[Dict[str, Any]]) -> Dict[str, str]: """{kind: "passed" | "failed"} for the checks this turn ran, the last run of each kind winning. `attempts` are the loop's receipts: {"purpose": "Run ", "observation": }. Pure.""" status: Dict[str, str] = {} - for attempt in attempts or []: + for attempt in after_edit_check.with_runs(attempts): tool = str(attempt.get("purpose") or "").removeprefix("Run ").strip() result = str(attempt.get("observation") or "") if result.startswith("ERROR"): @@ -84,7 +87,8 @@ def evidence(attempts: Iterable[Dict[str, Any]]) -> Dict[str, str]: elif tool == "run_local_check": head = _CHECK_HEAD.search(result) if head: - for kind in _kinds_run(head.group(1)) | ({"tests"} if _TESTS_BY_NAME.search(head.group(1)) else set()): + by_name = ({"tests"} if _TESTS_BY_NAME.search(head.group(1)) else set()) | ({"typecheck"} if _TYPES_BY_NAME.search(head.group(1)) else set()) + for kind in _kinds_run(head.group(1)) | by_name: status[kind] = PASSED if head.group(2) == "PASSED" else FAILED elif tool in _SANDBOX_TOOLS: status["tests"] = FAILED if re.search(r"\b(?:fail(?:ed|ures?)?|errors?)\b", result[:3000], re.I) else PASSED diff --git a/backend/utils/combo.py b/backend/utils/combo.py index 92e52725..6b5913f0 100644 --- a/backend/utils/combo.py +++ b/backend/utils/combo.py @@ -19,6 +19,8 @@ import re from typing import Any, Dict, FrozenSet, Iterable, List, Tuple +from backend.utils import after_edit_check + HIT_STEPS = int(os.getenv("TOOL_AGENT_COMBO_HIT_STEPS", "4")) CAP = int(os.getenv("TOOL_AGENT_ACTION_REFUND_CAP", "30")) PLAN_FAIL_DEVIATIONS = int(os.getenv("CODE_PLAN_FAIL_DEVIATIONS", "3")) @@ -99,6 +101,10 @@ def after_step(self, calls: List[Dict[str, Any]], results: List[Any]) -> Dict[st self._seen[key] = repeats + 1 elif name == "propose_local_edits": changed = True + ran = after_edit_check.ran_in(text) + if ran and _failed("run_local_check", ran): # their check ran by itself and failed: the same counter-hit as one the model ran (no extra steps: the Apply has earned them) + failed_new = True + self.failed_new += 1 wanted += steps_for(repeats) hit_here = True self.hits += 1 diff --git a/backend/utils/handback_check.py b/backend/utils/handback_check.py index d0b65351..ac3a2771 100644 --- a/backend/utils/handback_check.py +++ b/backend/utils/handback_check.py @@ -17,6 +17,8 @@ import re from typing import Iterable, Optional, Tuple +from backend.utils import after_edit_check + TAIL_CHARS = 700 _FOLLOW_UP_TAG_RE = re.compile(r"<<<.*?>>>", re.DOTALL) _CODE_FENCE_RE = re.compile(r"```.*?```", re.DOTALL) @@ -83,10 +85,15 @@ def repeat_note(times_before: int) -> str: _FAILED_RE = re.compile(r"^LOCAL (?:CHECK|COMMAND)\b[^\n]*\bFAILED \(exit code", re.IGNORECASE) +def check_ran(attempts) -> bool: + """Whether the turn ran a check at all, by the model's own call or by itself after an Apply (backend/utils/after_edit_check.py with_runs). Pure.""" + return any(str(attempt.get("action_desc", "")).startswith(_CHECK_CALL_PREFIXES) for attempt in after_edit_check.with_runs(attempts)) + + def last_check_failed(attempts) -> bool: """Whether the most recent thing the turn did was a check that FAILED (a check, a command or sandbox tests whose result says "FAILED (exit code ..."). If it did anything else after the check (read, edited) the check has been dealt with. Pure.""" - for attempt in reversed(list(attempts or [])): + for attempt in reversed(after_edit_check.with_runs(attempts)): if not str(attempt.get("action_desc", "")).startswith(_CHECK_CALL_PREFIXES): return False return bool(_FAILED_RE.match(str(attempt.get("observation", "")).strip())) diff --git a/backend/utils/loop_rhythm.py b/backend/utils/loop_rhythm.py index 43dffa54..a657f0d3 100644 --- a/backend/utils/loop_rhythm.py +++ b/backend/utils/loop_rhythm.py @@ -12,6 +12,8 @@ import os from typing import Any, Dict, List, Optional, Sequence, Tuple +from backend.utils import after_edit_check + READS_IN_A_ROW = max(int(os.getenv("LOOP_READS_IN_A_ROW", "3")), 2) # What counts as reading: looking at the repository or the folder. Everything else a loop can do (an edit, a check, a command) is acting. @@ -74,7 +76,11 @@ def after_step(self, calls: Sequence[Tuple[str, Any]], step: Optional[int] = Non self._noticed_at.clear() if any(name in EDIT_TOOLS and " APPLIED:" in str(result) for name, result in calls): self.applies += 1 - self._awaiting_check = True + if any(name in EDIT_TOOLS and after_edit_check.finished_in(result) for name, result in calls): + self.applies_checked += 1 # their own check ran by itself in the Apply: there is nothing left to be told to run + self._awaiting_check = False + else: + self._awaiting_check = True elif any(name in READ_TOOLS for name in names): self._reads += 1 self.streak += 1 diff --git a/backend/utils/message_doing.py b/backend/utils/message_doing.py index 37685ee2..16c7d7e6 100644 --- a/backend/utils/message_doing.py +++ b/backend/utils/message_doing.py @@ -4,21 +4,52 @@ 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. +`build_block(kind)` is one line for the reply prompt saying what to do FIRST. It never overrides the rest of the emotional guidance 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. + +NOTHING IS SAID ABOUT A HEAVY MESSAGE (2026-11-27). The block only runs on low turns, and its first version read "i have to go to my grandpa's funeral tomorrow..." as winding down ("ask nothing +and open nothing new: let them go") and "lol i hate myself" as joking ("meet the joke first"). A message with grief, fear, despair or something harsh about themselves in it, or a feeling read as +strong (HEAVY_INTENSITY or more), gets no line at all: a wrong instruction there costs far more than a missing one. And "leaving" has to mean leaving now: "i should go apologize to her" is not. Pure, no model call, nothing logged. """ import re from typing import Optional +from backend.utils.low_moves import harsh_about_self + KINDS = ("joking", "winding_down", "asking", "news") WINDING_DOWN_MAX_WORDS = 30 +HEAVY_INTENSITY = 0.6 + +_HEAVY_RE = re.compile( + r"\b(?:funeral|died|dies|dying|death|passed away|miscarriage|cancer|diagnos\w*|hospital|relapse\w*|suicid\w*|self[- ]harm)\b" + r"|\b(?:terrified|scared|afraid|panic\w*|hopeless|worthless|lonely|crying|cried|sobbing|heartbroken|devastated|dumped|broke up|left me|breaking down|falling apart|all alone|so alone)\b" + r"|\bhate (?:my life|it|this|that|going)\b|\bcan(?:'|โ€™)?t stand\b" + r"|\bcan(?:'|โ€™)?t (?:do this|take (?:it|this)|cope|breathe|go on|stop (?:crying|thinking))\b" + r"|\bget through (?:it|this|tomorrow|tonight|the (?:day|night|week))\b|\bdon(?:'|โ€™)?t (?:want to be here|know how i(?:'|โ€™)?(?:ll|m))\b|\bany ?more\b|\bwant (?:it|this|everything) to (?:stop|end)\b", + re.IGNORECASE, +) _JOKING_RE = re.compile(r"\b(?:lol|lmao|lmfao|rofl|haha+|hehe+|jk|just kidding|kidding)\b|๐Ÿ˜‚|๐Ÿคฃ|๐Ÿ˜…|๐Ÿ’€", re.IGNORECASE) +# "sleep on it", "sleep over at hers", "crash out on her" are not goodnights. +_NOT_THAT_SLEEP = r"(?!\s+(?:on|over|with|out|it off|in)\b)" +# A bare "gotta go" / "i should go" is leaving only when the clause ends there or says it is now: "i have to go back to that job" is not. +_CLAUSE_ENDS = r"(?=\s*(?:$|[.!,;:)]|now\b|for (?:now|tonight)\b|soon\b))" _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", + r"\b(?:going|heading|off|headed) to (?:bed|sleep)\b" + _NOT_THAT_SLEEP + + r"|\bgonna (?:sleep|crash|head to bed|go to bed|try (?:to|and) sleep)\b" + _NOT_THAT_SLEEP + + r"|\bneed to (?:sleep|get some sleep|go to bed)\b" + _NOT_THAT_SLEEP + + r"|\bcalling it (?:a night|for tonight)\b|\bi should (?:sleep|get to bed|go to bed|go to sleep|head to bed)\b" + _NOT_THAT_SLEEP + + r"|\b(?:i should|gotta|got to|have to) (?:go|run|head out)\b" + _CLAUSE_ENDS + + r"|\b(?:gotta|got to|have to) (?:sleep|go to bed|go to sleep)\b" + _NOT_THAT_SLEEP + + r"|\btry(?:ing)? to (?:get some )?sleep\b" + _NOT_THAT_SLEEP, + re.IGNORECASE, +) +# Talking ABOUT sleep, not leaving for it: "i can't go to sleep", "ive been going to sleep crying", "every night before i go to bed". +_NOT_LEAVING_RE = re.compile( + r"\b(?:not|never|can(?:'|โ€™)?t|cannot|couldn(?:'|โ€™)?t|won(?:'|โ€™)?t|been|keep|kept|before|when|trouble|hard|for hours|every night)\b[^.!?,;]{0,30}\b(?:sleep(?:ing)?|bed)\b" + r"|\b(?:sleep(?:ing)?|bed)\b[^.!?,;]{0,30}\b(?:every night|for hours)\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) @@ -36,14 +67,20 @@ } -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.""" +def heavy(message: Optional[str], intensity: Optional[float] = None) -> bool: + """Whether the message is too heavy for a one-line instruction about what it is doing: grief, fear, despair or something harsh about themselves, or a feeling read as strong. Pure.""" + text = str(message or "") + return float(intensity or 0.0) >= HEAVY_INTENSITY or bool(_HEAVY_RE.search(text)) or harsh_about_self(text) + + +def kind(message: Optional[str], intensity: Optional[float] = None) -> Optional[str]: + """One of KINDS for what the message is doing, or None when none of the patterns applies or the message is heavy (`intensity` is the feeling in force, when the caller has it). Pure.""" text = str(message or "").strip() - if not text: + if not text or heavy(text, intensity): 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): + if "?" not in text and len(text.split()) <= WINDING_DOWN_MAX_WORDS and _WINDING_DOWN_RE.search(text) and not _NOT_LEAVING_RE.search(text): return "winding_down" if "?" in text: return "asking" @@ -56,4 +93,4 @@ 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" + return f"\nWHAT THIS MESSAGE IS DOING (read from their own words; do this first, and the rest of your guidance still holds): {_BLOCKS[found]}\n" diff --git a/backend/utils/own_views.py b/backend/utils/own_views.py index 39607bd0..e441e3d9 100644 --- a/backend/utils/own_views.py +++ b/backend/utils/own_views.py @@ -4,13 +4,14 @@ 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. +characters), and when. NOTHING FROM THE MESSAGE IT ANSWERED is stored, not even single words (2026-11-28: the first version kept a bag of words from the message, names included, while the Privacy +page said only the sentence was kept). A later message finds a view through the words of that sentence, worked out when it is read; an older document that still carries a `words` field is read the +same way, and that field is ignored. 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 +WHEN IT IS READ. Only on a turn that asks for a view. `recall` returns the kept view whose sentence 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. @@ -27,9 +28,8 @@ COLLECTION = "sonic_said_views" MAX_PER_PERSON = 40 TTL_DAYS = 120 -MIN_SHARED = 3 +MIN_SHARED = 2 # it was 3 while the message's own words were matched too; a sentence alone shares fewer with a later message MIN_AGE_HOURS = 6 -MAX_WORDS_KEPT = 40 _indexed = {"done": False} @@ -50,23 +50,21 @@ def _ensure_indexes(db: Any) -> None: 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.""" +def entry_for(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, or one with too few distinctive words ever to be found again. It takes only Sonic's reply: the + person's message is not an input, so none of it can be stored. Pure.""" sentence = view_check.view_sentence(reply) - if not sentence: + if not sentence or len(material_use._words(sentence)) < MIN_SHARED: 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)} + return {"id": uuid.uuid4().hex, "text": sentence, "at": now, "expires_at": now + timedelta(days=TTL_DAYS)} -def note(db: Any, username: str, message: str, reply: str, now: Optional[datetime] = None) -> bool: +def note(db: Any, username: 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) + entry = entry_for(reply, moment) if entry is None: return False try: @@ -85,14 +83,14 @@ def note(db: Any, username: str, message: str, reply: str, now: Optional[datetim 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.""" + """The kept view whose sentence 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 [])) + shared = len(said & material_use._words(doc["text"])) if shared >= MIN_SHARED and (best_key is None or (shared, at) > best_key): best, best_key = doc, (shared, at) return best diff --git a/backend/utils/self_counters.py b/backend/utils/self_counters.py index 2d327e21..d23a40e8 100644 --- a/backend/utils/self_counters.py +++ b/backend/utils/self_counters.py @@ -101,7 +101,7 @@ # How much each turn mattered, whatever model wrote it (backend/utils/reply_tier.py STAKES, plus "none" for a plain turn): sizes the turns a stronger reply voice would be spent on. Counts only. "reply_stakes": ("safety", "emotional", "checkin", "companion", "identity", "frustration", "none"), } -_PLAIN_KEYS = ("turns_total", "self_model_used", "experience_captured", "experience_capture_merged", "experience_capture_invalid", "experience_offered", "experience_cited", "native_runs", "native_calls", "code_thinking_turns", "native_cache_expired_shrinks", "native_cache_expired_chars", "native_chars_sent", "native_chars_results", "native_chars_instructions", "native_chars_tools", "native_chars_preferences", "native_chars_architecture", "native_chars_memory", "native_chars_history", "native_chars_leanings", "leaning_turns", "native_chars_environment", "native_chars_request", "code_plan_turns", "code_plan_exec_tool_steps", "code_plan_exec_early", "code_plan_fed_next", "code_plan_turn_cap_hit", "code_plan_submitted", "code_plan_invalid", "code_plan_approved", "code_plan_cancelled", "code_plan_stalled", "code_plan_halted", "code_plan_marked_done", "claim_unproven", "claim_sent_back", "claim_edit_unbacked", "claim_denial_dropped", "edit_turn_correction", "code_plan_exec_turns", "code_plan_exec_cap_hit", "code_plan_exec_edited", "code_plan_steps_done", "code_plan_prefetched", "code_plan_deviation", "code_pushback", "code_frustrated", "code_proposals", "code_proposal_rework", "code_edit_calls", "code_edit_errors", "code_test_runs", "code_edit_applied", "code_edit_declined", "code_edit_undone", "code_edit_applied_small", "code_edit_applied_large", "code_edit_declined_small", "code_edit_declined_large", "code_edit_undone_small", "code_edit_undone_large", "working_notes_updated", "working_notes_item_added", "working_notes_item_dropped", "working_notes_injected", "working_notes_chat_read", "reply_fit_checked", "reward_evaluated", "relatable_offered", "self_mention", "observations_injected", "observations_used", "experience_placed", "relatable_placed", "take_offered", "corrections_carried", "goal_guard_shown", "care_pause_shown", "timeline_shown", "vague_fact_skipped", "hear_you_held", "shared_moment_offered", "shared_moment_used", "moment_capture_asked", "moment_capture_proposed", "moment_capture_refused", "code_plan_step_closed", "code_cross_file_refused", "code_cross_file_overridden", "code_after_edit_check_run", "code_after_edit_check_failed", "code_after_edit_check_suggested", "reply_bans_shown", "notes_standout_held", "notes_second_look", "notes_second_look_kept", "low_move_push_back", "low_move_pattern", "low_move_company", "support_choice_offered", "support_choice_listen", "support_choice_advice", "support_choice_fix", "support_mode_applied", "encouragement_offered", "open_loop_captured", "open_loop_offered", "open_loop_resolved", "callback_offered", "self_history_offered", "initiation_offered", "initiation_fallback", "initiation_answered", "initiation_interest_offered", "initiation_interest_answered", "duration_offered", "curiosity_offered", "curiosity_taken", "shelf_offered", "shelf_taken", "shelf_listed", "finding_selected", "lean_offered", "guardrail_applied", "routines_offered", "followups_offered", "task_results_offered", "meeting_turns", "headsup_offered", "clarify_noted", "clarify_asked", "clarify_answered", "memory_note_dropped", "memory_note_trimmed", "status_offered", "offer_made", "offer_taken", "offer_passed", "offer_held_back", "code_turns", "code_cap_hit", "code_edited", "code_verified", "code_followed", "code_redo") +_PLAIN_KEYS = ("turns_total", "self_model_used", "experience_captured", "experience_capture_merged", "experience_capture_invalid", "experience_offered", "experience_cited", "native_runs", "native_calls", "code_thinking_turns", "native_cache_expired_shrinks", "native_cache_expired_chars", "native_chars_sent", "native_chars_results", "native_chars_instructions", "native_chars_tools", "native_chars_preferences", "native_chars_architecture", "native_chars_memory", "native_chars_history", "native_chars_leanings", "leaning_turns", "native_chars_environment", "native_chars_request", "code_plan_turns", "code_plan_exec_tool_steps", "code_plan_exec_early", "code_plan_fed_next", "code_plan_turn_cap_hit", "code_plan_submitted", "code_plan_invalid", "code_plan_approved", "code_plan_cancelled", "code_plan_stalled", "code_plan_halted", "code_plan_marked_done", "claim_unproven", "claim_sent_back", "claim_edit_unbacked", "claim_denial_dropped", "edit_turn_correction", "code_plan_exec_turns", "code_plan_exec_cap_hit", "code_plan_exec_edited", "code_plan_steps_done", "code_plan_prefetched", "code_plan_deviation", "code_pushback", "code_frustrated", "code_proposals", "code_proposal_rework", "code_edit_calls", "code_edit_errors", "code_test_runs", "code_edit_applied", "code_edit_declined", "code_edit_undone", "code_edit_applied_small", "code_edit_applied_large", "code_edit_declined_small", "code_edit_declined_large", "code_edit_undone_small", "code_edit_undone_large", "working_notes_updated", "working_notes_item_added", "working_notes_item_dropped", "working_notes_injected", "working_notes_chat_read", "reply_fit_checked", "reward_evaluated", "relatable_offered", "self_mention", "observations_injected", "observations_used", "experience_placed", "relatable_placed", "take_offered", "corrections_carried", "goal_guard_shown", "care_pause_shown", "timeline_shown", "vague_fact_skipped", "hear_you_held", "shared_moment_offered", "shared_moment_used", "moment_capture_asked", "moment_capture_proposed", "moment_capture_refused", "code_plan_step_closed", "code_cross_file_refused", "code_cross_file_overridden", "code_after_edit_check_run", "code_after_edit_check_failed", "code_after_edit_check_suggested", "code_after_edit_check_held", "reply_bans_shown", "notes_standout_held", "notes_second_look", "notes_second_look_kept", "low_move_push_back", "low_move_pattern", "low_move_company", "support_choice_offered", "support_choice_listen", "support_choice_advice", "support_choice_fix", "support_mode_applied", "encouragement_offered", "open_loop_captured", "open_loop_offered", "open_loop_resolved", "callback_offered", "self_history_offered", "initiation_offered", "initiation_fallback", "initiation_answered", "initiation_interest_offered", "initiation_interest_answered", "duration_offered", "curiosity_offered", "curiosity_taken", "shelf_offered", "shelf_taken", "shelf_listed", "finding_selected", "lean_offered", "guardrail_applied", "routines_offered", "followups_offered", "task_results_offered", "meeting_turns", "headsup_offered", "clarify_noted", "clarify_asked", "clarify_answered", "memory_note_dropped", "memory_note_trimmed", "status_offered", "offer_made", "offer_taken", "offer_passed", "offer_held_back", "code_turns", "code_cap_hit", "code_edited", "code_verified", "code_followed", "code_redo") # The rhythm of a coding turn (backend/utils/loop_rhythm.py): turns it was followed on, turns that acted at all, reads before the first act (summed), edits applied, applied edits checked in the next # step, and reading-streak notices shown. Counts only. RHYTHM_KEYS = ("code_rhythm_turns", "code_rhythm_acted_turns", "code_rhythm_reads_before_first_act", "code_rhythm_applies", "code_rhythm_applies_checked", "code_rhythm_streak_notices") diff --git a/docs/review-fable-opus-2026-11-27.md b/docs/review-fable-opus-2026-11-27.md new file mode 100644 index 00000000..73833d06 --- /dev/null +++ b/docs/review-fable-opus-2026-11-27.md @@ -0,0 +1,108 @@ +# Review of the Fable and Opus changes (2026-11-27) + +Covers today's work by the two other sessions: PR #195 (`9803c7c1`), PR #196 (`8fd4bce3`) and PR #197 (`4f580cef`, Haiku thinking). PR #195 also holds my own waits fix and logo work, which I did not review here (an author cannot review their own change). + +How I checked: read the diffs and the code around them; ran the rules on made-up messages and made-up jobs in scratch scripts (no model, no database, nobody's real text); ran the backend suite and the frontend checks on the reviewed commit. No live model, runner or Render check. "Reproduced" means a script showed it with the real functions; "read" means I traced the code but did not run it. + +## Status (2026-11-28) + +- **3 and 4 are fixed** (uncommitted). 3: a message with grief, fear, despair or self-harsh words, or a feeling read at 0.6 or stronger, now gets no "what this message is doing" line, and a goodnight has to mean leaving now. 4: `agent_utils.holds_off` stops a message that asks Sonic to hold off, explain or leave it from becoming an edit turn, unless another part of it asks for a change or says go ahead. Both are fixed word patterns, so wordings they have not seen can still slip through. +- Found while fixing 4, not changed: "it shouldnt fade, it should reconfigure itself" is not read as an edit turn when the last reply shares no word with it. +- **1 and 2 are fixed** (uncommitted). 1: an automatic run is now read by the claim check, the hand-back check, the after-Apply hint, the reading rhythm and the step budget (`after_edit_check.with_runs`). 2: with the setting on, the run still waits for Run when the message read someone else's text, or when the change edits `package.json` and the check is an npm one; checks are chosen by the program they run, not by a word in the command; the setting's text says it runs the changed code. It still runs tests Sonic wrote in the change, which is what the setting is for. +- Found while fixing 1, also fixed: a passing check named `types` was never recognised as a type check, even when run by hand. +- Found while testing, fixed: a test left a chat turn open, which broke later waits in the same test process (caused by the 11-27 waits fix; the app itself closes each turn). +- **7 is fixed** (uncommitted, 2026-11-28). No word list is stored; a view is found by the words of Sonic's own sentence, worked out when read (2 shared words, was 3), and an old document's `words` field is ignored. Read-only count that day: 4 documents, all Jack's, 48 words, 36 of them from his messages. Those 4 still carry the field until it is removed from the database (needs his yes, and is best done after this is deployed). Still true of the kept sentence: deleting a conversation does not remove it, the Memory page does not list it, and only erasing memory or 120 days does. +- With 7 as well: backend and runner 10,470 passed, 7 skipped, 0 failed. +- 5, 6 and 8 to 10 are open. +- With all four fixes: backend and runner 10,467 passed, 7 skipped, 0 failed; frontend 774 of 774, type check clean. Mutation checks on copies: 38 breakages for 3 and 4, 30 for 1 and 2, all caught after adding tests for the 8 that first survived. No live model or runner run. + +The table and sections below describe the code as reviewed on 2026-11-27. + +## Summary + +| # | Severity | Change | Author | Problem | How verified | +|---|---|---|---|---|---| +| 1 | High | Check after Apply | Opus | The loop never sees the automatic check's result, so a true "tests pass" is marked as not run | Reproduced | +| 2 | High | Check after Apply | Opus | With the setting on, code can run with no Run press after untrusted text; the picker can choose a deploy check | Picker reproduced, gate read | +| 3 | High | "What this message is doing" | Fable | Serious messages are read as winding down ("let them go") or joking ("meet the joke first") | Reproduced | +| 4 | High | Corrections count as edit requests | Opus | "wait, dont change anything yet" forces a turn that must propose an edit | Reproduced and read | +| 5 | Medium | Write-denial remover | Opus | Deletes true sentences and can empty a reply | Reproduced | +| 6 | Medium | View when asked | Fable | "why should i even bother anymore" is read as asking for a view, and ends "just listen" | Reproduced | +| 7 | Medium | Remembered views | Fable | Words from your message are stored; the Privacy page says only Sonic's sentence is | Reproduced | +| 8 | Medium | Shrinking old reads | Opus | Adds a trigger for the thinking-block 400 on turns without drop_block | Read; Opus's own probe showed the trigger | +| 9 | Low | Stronger emotional voice (off) | Fable | The "daily cap" is per conversation | Reproduced | +| 10 | Low, unverified | Coding thinking | Opus | Thinking now shares the 8,192-token and 60-second limits | Not tested | + +## 1. The automatic check is invisible to the loop's own checks (Opus) + +The check's result is appended to the `propose_local_edits` result. `claim_check.evidence` and `handback_check.last_check_failed` only read results of `run_local_check`, `run_local_command` and the sandbox tools. + +- Check passed, reply says "the tests pass": the loop sends it back with "run it now" (against the note "do not run the same check again"), and the reply gets "_Not checked: the tests were not run in this turn._" +- Check failed: the note says "not run" instead of "failed", and the failed-check hand-back never fires. + +Only affects people who tick "Check my changes right after I apply them". Fix: have `_after_edit_check` record the run where the loop reads it (an attempt entry, or have `evidence` read the folded-in header), with a test that goes through the loop. + +## 2. The automatic check skips protections the Run button gave (Opus) + +- After incident data is read, `run_snippet`, `run_repo_tests` and similar are blocked, and `run_local_check` still needs a press. The automatic check consults neither `ops_state["data_seen"]` nor `untrusted_used`. So: untrusted text, then a proposed edit, then Apply, then code runs with no second press. +- What runs includes test files Sonic wrote in that same edit. The diff is shown, but the setting's text does not say Apply also executes it. +- The picker matches substrings. With only config checks `deploy = npm run deploy` and a changed `.test.js`, it picks **deploy**. It also picks deploy when deploy is listed before `js-tests`. A command containing "tsc" anywhere (`python scripts/tscribe_release.py`) is picked for a TypeScript change. + +Off by default. Fix: fall back to the Run card when untrusted or incident text was read this turn; pick only the runner's preset names (`tests`, `types`, `js-tests`); say in the setting that it runs the changed tests. + +## 3. "What this message is doing" misreads serious messages (Fable) + +All rated `none` by the keyword safety check unless noted: + +| Message | Read as | The reply is told | +|---|---|---| +| "i have to go to my grandpa's funeral tomorrow and i dont know how ill get through it" | winding down | "ask nothing and open nothing new: let them go" | +| "i should go apologize to her but im terrified" | winding down | same | +| "i have to go back to that job on monday and i cant stand it" | winding down | same | +| "lol i hate myself" | joking | "Meet the joke first... before anything heavier" | + +It runs only when the emotional guidance is in force, which is exactly the low turns, and it is the last block in the prompt. ("haha is it bad that i dont want to be here anymore" is also read as joking, but the safety check rates it elevated, so the block is withheld.) Fix: require leaving words about tonight or sleep, never apply either label when the mood read is low and intense or the message holds self-harsh words; or drop `winding_down` and `joking` until measured. + +## 4. Messages that say "don't edit" become edit turns (Opus) + +After a coding reply, each of these is an edit turn: "no stop, leave the loader alone", "wait, dont change anything yet", "hmm just explain the loader to me instead", "no need to change it, the loader looks right", "wait i need to think about the loader", "no that makes sense, the loader works like that". On such a turn a text-only answer is sent back up to twice with "call propose_local_edits... do not ask permission". The person still has to press Apply, but Sonic is pushed to do what they just declined. It also switches on Haiku thinking. Fix: a refusal or "explain instead" rule (stop, leave, don't/dont anywhere near change or touch, no need, just explain, think about) before the correction test. + +## 5. The write-denial remover is too wide (Opus) + +On any turn with an applied edit, these true sentences are deleted: "I didn't change any files in the frontend.", "I haven't touched anything else.", "I couldn't edit the files under node_modules." Two one-sentence replies became empty strings, and `app.py` has no guard for that. Fix: drop only an unscoped denial (nothing after "any files"/"anything"), and never leave a reply empty. + +## 6. The view detector catches despair (Fable) + +"why should i even bother anymore", "i should i guess" and "would you say that again" count as asking what Sonic thinks. The first one ends "just listen", tells the reply to open with a view and not with how they feel, and lifts the no-advice-to-someone-venting guard. Fix: require a real question shape for "should i", and never end listen mode on a low message. + +## 7. Remembered views store more than disclosed (Fable) + +`own_views.entry_for` keeps the distinctive words of Sonic's sentence **and of your message**. From a made-up question it stored `devin, drinking, layoff, marisol, sister`. The Privacy page says "that one sentence is kept". It is per person and erased with memory. Fix: store words from Sonic's sentence only, or say so on the Privacy page. + +## 8. Shrinking old reads can trigger the silent Gemini fallback (Opus) + +After a wait over 330 seconds the loop now edits earlier results on Claude. A Claude turn that thinks without `drop_block` is rejected after such an edit (400, then Gemini). Coding turns set `drop_block`; other turns do not, and those are the ones that wait on calendar, doc and choice cards. Locally `CLAUDE_THINKING=off` avoids it for Haiku; Opus found signs production may be thinking. Fix: shrink only when the model drops blocks, or set `drop_block` whenever shrinking is possible. + +## 9 and 10 + +- `top_tier.used_today` counts one conversation's replies, so eight a day is eight per conversation. The person's daily spend limit still applies. Off by default. +- Coding turns now think inside `CLAUDE_MAX_TOKENS=8192` and `CLAUDE_TIMEOUT=60`. A large proposal could be cut off or time out into Gemini. The probe used a tiny task. Watch for fallbacks. + +## Also noticed + +PR #195 makes a knowledge-base approval build graph edges (`knowledge_base.approve` calls `index_graph_for_source`, which calls a Gemini model). Neither session's report mentions it, I could not tell who wrote it, and I did not find a test for it in the knowledge-base tests. + +## What was good + +- Fable's two coding bugs were real: reads cut at 6,000 characters under a header claiming all lines, and plan prefetch showing imports. Both fixes read as sound. +- Saving the reply marks fixes a real reset-on-restart bug. +- Your privacy rule is followed: stances and takes do not come from conversations, and the new per-person stores are erased with memory. +- Opus declined to build read-shrinking as first proposed after checking the cache cost, and probed thinking before turning it on. +- Fable's one database write (approving seven moments) followed an explicit yes. +- Both said plainly that nothing had run inside the app with a real model. + +## Suite results on the reviewed code + +Backend and runner: 10,402 passed, 7 skipped, 0 failed (started on `4f580cef`; `b0c43b8d`, the merge of it, changes no file). A green suite does not contradict the findings above: none of these cases has a test. + +Frontend: `tsc -b` clean, 774 of 774 tests. diff --git a/local/src/components/RunnerSettingsCard.tsx b/local/src/components/RunnerSettingsCard.tsx index 9a241f39..9bb71400 100644 --- a/local/src/components/RunnerSettingsCard.tsx +++ b/local/src/components/RunnerSettingsCard.tsx @@ -335,7 +335,7 @@ export default function RunnerSettingsCard() { void changeAfterEditAuto(runner, event.target.checked)} /> Check my changes right after I apply them - When you apply a change Sonic proposed, the one check of yours that fits it runs without the Run button: the tests that belong to the changed Python files (never the whole suite), or the type check for TypeScript. Sonic reads the result and fixes what it broke in the same turn. Off by default. + When you apply a change Sonic proposed, the one check of yours that fits it runs without the Run button: the tests that belong to the changed Python files (never the whole suite), or the type check for TypeScript. Sonic reads the result and fixes what it broke in the same turn. This runs your code as just changed, including any test Sonic wrote in that change. It waits for Run instead when Sonic read a web page, an email, a shared document or a log in that message, or when the change edits package.json and the check is an npm one. Off by default.