From af8b56be98bebc3afc6740fab9e95119859f85f8 Mon Sep 17 00:00:00 2001 From: jack Date: Tue, 24 Nov 2026 07:23:24 -0600 Subject: [PATCH] feat: add cross-file symbol references and memory compaction updates Co-authored-by: Sonic Assistant --- backend/components/sonic_changelog.py | 14 + backend/services/agent_workflow.py | 81 +++++- backend/services/memory_compaction.py | 14 +- backend/tests/test_cross_file_and_trace.py | 271 +++++++++++++++++++ backend/tests/test_fact_cleanup.py | 14 + backend/tests/test_local_edits.py | 3 +- backend/tests/test_memory_compaction.py | 37 +++ backend/utils/cross_file.py | 299 +++++++++++++++++++++ backend/utils/memory_maintenance.py | 32 +++ backend/utils/self_counters.py | 2 +- backend/utils/symbol_refs.py | 97 +++++++ 11 files changed, 857 insertions(+), 7 deletions(-) create mode 100644 backend/tests/test_cross_file_and_trace.py create mode 100644 backend/utils/cross_file.py create mode 100644 backend/utils/symbol_refs.py diff --git a/backend/components/sonic_changelog.py b/backend/components/sonic_changelog.py index 8db6ec22..4fcf148b 100644 --- a/backend/components/sonic_changelog.py +++ b/backend/components/sonic_changelog.py @@ -1787,6 +1787,20 @@ "keywords": ["how have you been", "your week", "how are you doing lately"], "volunteer": [], }, + { + "id": "multi_file_changes", + "requires": [ + "backend/utils/symbol_refs.py::def find_references", + "backend/utils/cross_file.py::def check", + ], + "month": "2026-11", + "title": "Changes that span several files", + "line": ( + "I can now find every place a name is defined and used in your connected folder, and before showing you a change I check it won't break another file that imports or calls what I changed." + ), + "keywords": ["multi-file", "several files", "callers", "references", "imports", "break other files", "rename"], + "volunteer": [], + }, { "id": "more_than_reflecting", "requires": [ diff --git a/backend/services/agent_workflow.py b/backend/services/agent_workflow.py index 8e8876ea..487b100c 100644 --- a/backend/services/agent_workflow.py +++ b/backend/services/agent_workflow.py @@ -58,6 +58,7 @@ from backend.services import ci_status, commit_flow, git_commit, pr_read from backend.utils import sonic_notes from backend.utils import read_log +from backend.utils import cross_file, symbol_refs from backend.utils import advisor as advisor_module from backend.utils import demo_project from backend.services.local_workspace import apply_sync as apply_workspace_sync, get_workspace_handle, is_guest_username, snapshot_paths, workspace_status @@ -170,6 +171,13 @@ # Menu entries that query GitHub's hosted index of the committed branch — withheld whenever the user # has a local folder connected, since that index can't see the folder's (often uncommitted) code. _GITHUB_INDEX_ACTIONS_PREFIXES = ("- search_code", "- trace_symbol") +# With a folder connected, trace_symbol comes back in this form, searching the folder itself (backend/utils/symbol_refs.py; 2026-11-24 coding audit: multi-file changes missed callers because +# only search_literal, a case-insensitive substring search, was left to find them). +LOCAL_TRACE_SYMBOL_LINE = ( + "- trace_symbol — args: symbol (an exact name: a function, class, variable, field, prop or CSS class); searches EVERY file of the connected folder for it as a whole word " + "(case-sensitive) and lists where it is DEFINED, every file that USES it with line numbers, and where it is IMPORTED. Use it before you change, rename or remove anything other " + "files might use, so one proposal covers every file that needs an edit. For text inside a longer word, or a phrase, use search_literal; for a file by a loose name, find_file" +) # What only the browser that holds the folder can finish: a diff card's Apply writes through the folder it was connected with. The server's copy of a folder belongs to the person, so a phone (which cannot # connect a folder) or a second browser sees it too, and a diff proposed there has no Apply button: a dead end. Commits are NOT in this list: propose_commit works from the server's copy and the person's # GitHub token, and propose_git_commit runs git on their own machine through the runner, so neither needs this browser to hold the folder (withholding them said "no tool options" on a commit request, 2026-11-06). @@ -2681,6 +2689,16 @@ def _search_code(query: str): return "No matches." return "\n".join(item.get("path", "") for item in items) + def _trace_symbol_local(symbol: str): + # The folder (or a checkout) is on disk: every file is searched for the whole word, and each hit is sorted into defined / imported / used, with line numbers + # (backend/utils/symbol_refs.py). GitHub's index cannot see a connected folder's uncommitted code, which is why trace_symbol used to be withheld there. + items = _fetch_repo_tree_items() + if isinstance(items, str): + return items + paths = [item.get("path", "") for item in items if str(item.get("path", "")).lower().endswith(symbol_refs.SEARCHED_SUFFIXES)] + found = symbol_refs.find_references(((path, _read_for_check(path) or "") for path in paths), symbol) + return symbol_refs.format_references(found, symbol) + def _trace_symbol(symbol: str): # Sorts every real reference search_code would already find into WRITE/DECIDE sites # (an assignment, a state setter, a def/class that IS this symbol, a function @@ -2691,6 +2709,8 @@ def _trace_symbol(symbol: str): # opening every hit by hand to figure that out one at a time. if not symbol: return "ERROR: no symbol given" + if _get_checkout() is not None: + return _trace_symbol_local(symbol) items = _code_search_items(symbol) if isinstance(items, str): return items @@ -3173,6 +3193,7 @@ def _run_snippet(code: str, branch: str = None): # that exists only in the user's folder it answers "No matches" — observed costing four # full model round trips in one turn. search_literal greps the folder itself. menu_lines = [line for line in menu_lines if not line.startswith(_GITHUB_INDEX_ACTIONS_PREFIXES)] + menu_lines.append(LOCAL_TRACE_SYMBOL_LINE) # the folder's own trace_symbol: it reads the folder, not GitHub's index menu_lines.append( "- propose_local_edits — args: summary (one or two sentences on what the edits do and " "why), edits (a list of edit objects: {\"path\", \"old_string\", \"new_string\"} " @@ -3407,6 +3428,40 @@ def _is_unsafe(decision: dict) -> bool: code = ((decision.get("args") or {}).get("code") or "").lower() return any(kw in code for kw in unsafe_keywords) + cross_file_seen: dict = {} + + def _read_for_check(path: str): + """A file's current text for the cross-file check: from this turn's cache when it was read, else straight from the folder on disk (not cached: the check looks at many files).""" + if path in _turn_file_cache: + return _turn_file_cache[path] + checkout = _get_checkout() + if checkout is None: + return None + root = Path(checkout.root).resolve() + local_path = (root / path).resolve() + if not local_path.is_relative_to(root) or not local_path.is_file(): + return None + try: + return local_path.read_text(encoding="utf-8", errors="replace") + except OSError: + return None + + def _cross_file_problems(result: dict) -> list: + """What the validated proposal would break elsewhere in the folder (backend/utils/cross_file.py); [] when nothing, when the folder cannot be read, or if the check itself fails + (it must never stop a sound proposal).""" + try: + if _get_checkout() is None: + return [] + paths = _fetch_repo_paths() + if isinstance(paths, str): + return [] + after = {**{p: None for p in result.get("removed") or []}, **(result.get("texts") or {})} + before = {p: _read_for_check(p) for p in after} + return cross_file.check(before, after, paths, _read_for_check) + except Exception: + logger.warning("[tool_agent_node] the cross-file check failed; the proposal goes ahead without it.", exc_info=True) + return [] + async def _propose_local_edits(args: dict) -> str: if plan_phase == code_plan.EXECUTE_PHASE: # The deviation cap (backend/utils/code_plan.py): the person approved these files. More than a file's worth outside them stops the turn instead of widening the change unseen. @@ -3431,6 +3486,24 @@ async def _propose_local_edits(args: dict) -> str: + "\n- ".join(result["errors"]) + "\nFix them and call propose_local_edits again with the complete corrected list." ) + # The other end of the change (backend/utils/cross_file.py): a name removed or renamed that another file still imports, a call that no longer fits a changed signature, an import + # of something its module does not have. Sent back before the person sees a diff. The same problems twice in one turn let the proposal through with them named, so a wrong + # check can never trap the turn. + cross_note = "" + problems = await asyncio.to_thread(_cross_file_problems, result) + if problems: + from backend.utils.self_counters import record_turn_counts + + if problems != cross_file_seen.get("last"): + cross_file_seen["last"] = problems + await asyncio.to_thread(record_turn_counts, {"code_cross_file_refused": 1}) + return ( + "ERROR: these edits would break other code, so nothing was proposed:\n- " + "\n- ".join(problems) + + "\nAdd the edits that fix each of these to the same proposal (trace_symbol finds every use of a name) and call propose_local_edits again with the complete list. " + "If one of these is wrong, call it again unchanged and it will go through with the warning shown." + ) + await asyncio.to_thread(record_turn_counts, {"code_cross_file_overridden": 1}) + cross_note = " Proposed despite the cross-file check, which still reports: " + "; ".join(problems) + ". Tell the person about these in your answer." proposal_id = uuid.uuid4().hex # Which paths this proposal changes and by how much, so an Apply reported later is noted as work waiting to be committed (backend/utils/applied_changes.py). proposed = {f["path"]: (f.get("additions", 0), f.get("deletions", 0)) for f in result["files"] if f["path"] in (result.get("texts") or {}) or f.get("kind") == "delete"} @@ -3457,7 +3530,7 @@ async def _propose_local_edits(args: dict) -> str: shown = ( f"Proposed {len(result['edits'])} edit(s) across {len(result['files'])} file(s): " + ", ".join(f["path"] for f in result["files"]) - + "." + + "." + cross_note ) if not waiting: return ( @@ -4008,11 +4081,11 @@ async def _act(decision: dict): "final answer and let the user ask for it as a separate request." ) - if local_workspace_handle is not None and tool_action in {"search_code", "trace_symbol"}: + if local_workspace_handle is not None and tool_action == "search_code": return ( f"ERROR: {tool_action} queries GitHub's index of the committed branch and cannot " - f"see the user's connected local folder — use search_literal (exact text or " - f"identifier) or find_file (file names) instead." + f"see the user's connected local folder — use trace_symbol (every use of a name, in the folder itself), " + f"search_literal (exact text) or find_file (file names) instead." ) if tool_action == "ask_choice": return await _ask_choice(args) diff --git a/backend/services/memory_compaction.py b/backend/services/memory_compaction.py index a9e760ca..331234ed 100644 --- a/backend/services/memory_compaction.py +++ b/backend/services/memory_compaction.py @@ -36,6 +36,18 @@ MIN_PATTERN_EXTRACTION_INTERVAL_HOURS = float(os.getenv("MIN_PATTERN_EXTRACTION_INTERVAL_HOURS", "24")) MIN_NEW_FACTS_FOR_PATTERN_EXTRACTION = int(os.getenv("MIN_NEW_FACTS_FOR_PATTERN_EXTRACTION", "5")) +# Only tier 1 turns summaries into facts (2026-11-24, measured on the busiest store). Tier 2 re-summarizes notes tier 1 has already mined, and in November it offered 768 facts +# for 218 that were kept as new (tier 1: 305 offered, 127 new): two thirds of the compaction inflow, about 550 wasted dedupe judgments, and facts drawn from summaries of +# summaries, the least reliable source ("Jack is a professional contact or colleague of the user who communicates with Kelsey"). The tier-2 summaries themselves are kept. +# MEMORY_TIER2_FACTS=on turns tier-2 promotion back on. +TIER2_PROMOTES_FACTS = os.getenv("MEMORY_TIER2_FACTS", "off").strip().lower() in ("1", "true", "on", "yes") + + +def promotes_facts(tier: int) -> bool: + """Whether a compaction run of this tier saves the facts its summaries name. Pure.""" + return tier < 2 or TIER2_PROMOTES_FACTS + + TIER1_SOURCE_TYPE = "compacted_summary" TIER2_SOURCE_TYPE = "compacted_meta_summary" @@ -318,7 +330,7 @@ async def _run_compaction( )) await asyncio.to_thread(lambda: db[USER_MEMORY_COLLECTION].delete_many({"_id": {"$in": [c["_id"] for c in cluster]}})) - for fact in summarized["facts"]: + for fact in summarized["facts"] if promotes_facts(tier) else []: fact_text = fact.get("fact") if isinstance(fact, dict) else None if fact_text and fact_gate.is_passing_status(fact_text, fact.get("category"), fact.get("domain")): facts_skipped_vague += 1 # passing work status naming nothing: the summary above keeps it, with its date (backend/utils/fact_gate.py) diff --git a/backend/tests/test_cross_file_and_trace.py b/backend/tests/test_cross_file_and_trace.py new file mode 100644 index 00000000..cfef3ad2 --- /dev/null +++ b/backend/tests/test_cross_file_and_trace.py @@ -0,0 +1,271 @@ +"""Multi-file changes (2026-11-24 coding audit): trace_symbol on the connected folder (backend/utils/symbol_refs.py) and the cross-file check on every proposal (backend/utils/cross_file.py), pure and +through tool_agent_node's real dispatcher with a connected folder. No model, no database.""" +import asyncio +from unittest.mock import AsyncMock + +import pytest + +from backend.services import agent_workflow as aw +from backend.services import local_workspace as lw +from backend.services import repo_checkout as rc +from backend.tests.legacy_loop import react_style +from backend.utils import cross_file, self_counters, symbol_refs + +# ---------------------------------------------------------------------------------------------- trace_symbol, pure + +REPO = { + "backend/utils/budget.py": "LIMIT = 5\n\ndef notice_level(spent, limit):\n return spent / limit\n\nclass Budget:\n def notice_level(self):\n return 1\n", + "app.py": "from backend.utils.budget import notice_level\n\nlevel = notice_level(3, 4)\nprint(level)\nnotice_levels = []\n", + "local/src/Banner.tsx": "import { noticeLevel } from './api';\nexport function Banner() {\n const x = noticeLevel(1);\n return x;\n}\n", + "local/src/api.ts": "export function noticeLevel(n: number) {\n return n;\n}\nexport const other = 1;\n", + "local/src/a.css": ".notice-level { color: red; }\n.notice-level-big { color: blue; }\n", +} + + +def test_references_are_whole_words_case_sensitive_and_sorted_into_defined_imported_and_used(): + found = symbol_refs.find_references(REPO.items(), "notice_level") + assert [(p, n) for p, n, _t in found["definitions"]] == [("backend/utils/budget.py", 3), ("backend/utils/budget.py", 7)] + assert found["imports"] == {"app.py": [1]} + assert found["uses"] == {"app.py": [(3, "level = notice_level(3, 4)")]} # notice_levels on line 5 is another word + assert found["files"] == 2 + ts = symbol_refs.find_references(REPO.items(), "noticeLevel") + assert [(p, n) for p, n, _t in ts["definitions"]] == [("local/src/api.ts", 1)] + assert ts["imports"] == {"local/src/Banner.tsx": [1]} and list(ts["uses"]) == ["local/src/Banner.tsx"] + css = symbol_refs.find_references(REPO.items(), "notice-level") + assert [(p, n) for p, n, _t in css["definitions"]] == [("local/src/a.css", 1)] # not .notice-level-big + assert symbol_refs.find_references(REPO.items(), "LIMIT")["definitions"][0][:2] == ("backend/utils/budget.py", 1) + assert symbol_refs.find_references(REPO.items(), "Notice_level")["files"] == 0 + + +@pytest.mark.parametrize("line, kind", [ + ("def greet(name):", "define"), (" async def greet(self):", "define"), ("export const greet = () => 1;", "define"), ("export default function greet() {", "define"), + ("interface greet {", "define"), (" greet(a, b) {", "define"), (" self.greet = 1", "define"), ("greet = make()", "define"), + (" greet = make()", "use"), (" greet(a, b);", "use"), ("x = greet(1)", "use"), ("from m import greet", "import"), ("import { greet } from './m';", "import"), + ("const { greet } = props;", "define"), ("if greet == 1:", "use"), +]) +def test_each_line_is_classified(line, kind): + assert symbol_refs.classify("greet", line) == kind + + +def test_the_report_puts_definitions_first_caps_each_file_and_says_plainly_when_nothing_matched(): + many = {"a.py": "def f():\n pass\n" + "f()\n" * 10, **{f"m{i}.py": "f()\n" for i in range(symbol_refs.MAX_FILES_SHOWN + 3)}} + text = symbol_refs.format_references(symbol_refs.find_references(many.items(), "f"), "f") + assert text.index("DEFINED:") < text.index("USED") + assert "a.py:1: def f():" in text and "... 6 more in this file" in text and "... and 4 more file(s)" in text + assert "No whole-word matches" in symbol_refs.format_references(symbol_refs.find_references(many.items(), "nothing"), "nothing") + assert "no definition found" in symbol_refs.format_references(symbol_refs.find_references({"x.py": "print(f)\n"}.items(), "f"), "f") + + +def test_only_code_and_text_files_are_searched(): + assert symbol_refs.find_references({"logo.png": "greet", "notes.md": "greet"}.items(), "greet")["files"] == 1 + + +# ---------------------------------------------------------------------------------------------- cross_file, pure + +FOLDER = { + "pkg/__init__.py": "", + "pkg/greet.py": "def greet(name, punct='!'):\n return 'hi ' + name + punct\n\ndef bye(name):\n return name\n\nVERSION = 1\n", + "pkg/sub/__init__.py": "", + "pkg/sub/tool.py": "def tool():\n return 1\n", + "app.py": "from pkg.greet import greet, VERSION\nimport pkg.greet as g\n\nprint(greet('a'), g.bye('b'))\n", + "other.py": "from pkg import greet as greet_module\n\ngreet_module.greet('x', punct='?')\n", + "rel/__init__.py": "", "rel/a.py": "from .b import helper\n\nhelper()\n", "rel/b.py": "def helper():\n return 1\n", + "web/api.ts": "export function noticeLevel(n: number) { return n; }\nexport const other = 1;\nexport { noticeLevel as nl };\n", + "web/Banner.tsx": "import { noticeLevel, other } from './api';\nexport const B = () => noticeLevel(other);\n", + "web/index.ts": "export * from './api';\n", + "web/User.tsx": "import { nl } from './index';\n", +} + + +def _check(changes, folder=FOLDER): + after = {path: text for path, text in changes.items()} + before = {path: folder.get(path) for path in changes} + return cross_file.check(before, after, sorted(set(folder) | set(after)), lambda p: folder.get(p)) + + +def test_a_removed_python_name_that_another_file_imports_is_named_with_file_and_line(): + problems = _check({"pkg/greet.py": FOLDER["pkg/greet.py"].replace("VERSION = 1\n", "")}) + assert problems == ["app.py:1 imports VERSION from pkg.greet, which this proposal removes from pkg/greet.py. Update that import (and its uses) in the same proposal"] + + +def test_a_rename_is_caught_through_every_way_a_module_is_reached(): + renamed = FOLDER["pkg/greet.py"].replace("def bye(", "def farewell(").replace("def greet(", "def hello(") + problems = _check({"pkg/greet.py": renamed}) + assert any(p.startswith("app.py:1 imports greet from pkg.greet") for p in problems) + assert any(p.startswith("app.py:4 uses g.bye") for p in problems) # import pkg.greet as g; g.bye(...) + assert any(p.startswith("other.py:3 uses greet_module.greet") for p in problems) # from pkg import greet as greet_module + + +def test_a_deleted_module_breaks_its_importers_and_a_relative_import_is_resolved(): + assert any(p.startswith("rel/a.py:1 imports helper from rel.b") for p in _check({"rel/b.py": None})) + + +@pytest.mark.parametrize("new_def, caught, fragment", [ + ("def greet(name, greeting, punct='!'):", True, "app.py:4 calls greet(...) and passes 1 positional argument, the new signature requires 2"), + ("def greet(name):", True, "other.py:3 calls greet_module.greet(...) and passes punct=, which the new signature no longer accepts"), + ("def greet(name, *, loud, punct='!'):", True, "does not pass loud="), + ("def greet(name, punct='!', loud=False):", False, ""), # an optional parameter added: every call still fits + ("def greet(*args, **kwargs):", False, ""), +]) +def test_a_changed_signature_flags_only_the_calls_it_really_breaks(new_def, caught, fragment): + problems = _check({"pkg/greet.py": FOLDER["pkg/greet.py"].replace("def greet(name, punct='!'):", new_def)}) + assert bool(problems) is caught + if caught: + assert any(fragment in p for p in problems), problems + + +def test_calls_in_the_edited_file_itself_are_checked_against_its_new_signature(): + text = FOLDER["pkg/greet.py"].replace("def greet(name, punct='!'):", "def greet(name, greeting):") + "\nX = greet('a')\n" + assert any(p.startswith("pkg/greet.py:9 calls greet(...)") for p in _check({"pkg/greet.py": text})) + + +def test_a_new_import_of_a_name_the_module_lacks_is_caught_but_a_library_or_a_submodule_or_an_old_import_is_not(): + edited = FOLDER["app.py"] + "from pkg.greet import shout\nfrom requests import nothing_checked\nfrom pkg.sub import tool\nfrom pkg import sub\n" + assert _check({"app.py": edited}) == [ + "app.py:5 imports shout from pkg.greet, but pkg.greet does not define shout. Import a name that exists, or add it to that module in the same proposal"] + broken_before = {**FOLDER, "app.py": "from pkg.greet import gone\n"} + assert _check({"app.py": "from pkg.greet import gone\nprint(1)\n"}, broken_before) == [] # it was already there: not this proposal's doing + + +def test_a_name_added_to_the_module_in_the_same_proposal_makes_the_new_import_fine(): + assert _check({"app.py": FOLDER["app.py"] + "from pkg.greet import shout\n", "pkg/greet.py": FOLDER["pkg/greet.py"] + "\ndef shout():\n return 1\n"}) == [] + + +def test_a_removed_ts_export_still_imported_elsewhere_is_caught_and_a_new_import_of_a_missing_export_too(): + problems = _check({"web/api.ts": FOLDER["web/api.ts"].replace("export const other = 1;", "const other = 1;")}) + assert problems == ["web/Banner.tsx:1 imports other from './api', which this proposal removes from web/api.ts. Update that import (and its uses) in the same proposal"] + added = _check({"web/Banner.tsx": "import { noticeLevel, other, missing } from './api';\n"}) + assert added == ["web/Banner.tsx:1 imports missing from './api', but web/api.ts does not export missing. Import a name it exports, or export it in the same proposal"] + assert _check({"web/User.tsx": "import { nl, anything } from './index';\n"}) == [] # export * : cannot tell, so silent + + +def test_an_unchanged_proposal_and_unrelated_files_are_silent_and_results_are_capped(): + assert _check({"pkg/greet.py": FOLDER["pkg/greet.py"]}) == [] + many = {**FOLDER, **{f"m{i}.py": "from pkg.greet import VERSION\n" for i in range(20)}} + assert len(_check({"pkg/greet.py": FOLDER["pkg/greet.py"].replace("VERSION = 1\n", "")}, many)) == cross_file.MAX_PROBLEMS + + +def test_a_module_that_cannot_be_judged_is_left_alone(): + star = {**FOLDER, "pkg/greet.py": "from somewhere import *\n"} + assert _check({"pkg/greet.py": "x = 1\n"}, star) == [] # what it had before is unknown + lazy = FOLDER["pkg/greet.py"] + "\ndef __getattr__(name):\n return 1\n" + assert _check({"app.py": FOLDER["app.py"] + "from pkg.greet import shout\n"}, {**FOLDER, "pkg/greet.py": lazy}) == [] + + +def test_names_defined_under_a_guard_still_count(): + guarded = "try:\n from fast import loads\nexcept ImportError:\n def loads(x):\n return x\n" + folder = {**FOLDER, "pkg/js.py": guarded} + assert _check({"app.py": FOLDER["app.py"] + "from pkg.js import loads\n"}, folder) == [] + + +# ---------------------------------------------------------------------------------------------- through the real dispatcher + +FILES = { + "src/__init__.py": "", + "src/app.py": "def greet(name):\n return 'hi ' + name\n", + "src/main.py": "from src.app import greet\n\nprint(greet('x'))\n", +} + + +def _run(coro): + return asyncio.run(coro) + + +async def _drive(monkeypatch, decisions): + from backend.tests.test_tool_agent_node import _setup_github_repo, _state + + lw.apply_sync("jack", "proj", [{"path": p, "content": c} for p, c in FILES.items()], [], True) + monkeypatch.setattr(aw, "fetch_and_extract_checkout", lambda *a, **k: (_ for _ in ()).throw(rc.RepoCheckoutError("x"))) + _setup_github_repo(monkeypatch) + emit = AsyncMock() + monkeypatch.setattr(aw, "safe_emit_event", emit) + counted = [] + monkeypatch.setattr(self_counters, "record_turn_counts", lambda counts, now=None: counted.append(dict(counts))) + observed = [] + + async def fake_loop(**kwargs): + for decision in decisions: + observed.append(await kwargs["act"](decision)) + return {"final_answer": "done", "attempts": [], "show_work": False} + + monkeypatch.setattr(aw.native_loop, "run", react_style(fake_loop)) + await aw.tool_agent_node(_state("rename greet to hello", username="jack")) + cards = [c for c in emit.call_args_list if c.args[0] == "local_edit_proposal"] + return observed, cards, counted + + +RENAME = {"tool_action": "propose_local_edits", "args": {"summary": "rename", "edits": [{"path": "src/app.py", "old_string": "def greet(name):", "new_string": "def hello(name):"}]}} + + +def test_trace_symbol_searches_the_connected_folder_itself(monkeypatch): + observed, _cards, _ = _run(_drive(monkeypatch, [{"tool_action": "trace_symbol", "args": {"symbol": "greet"}}])) + assert "DEFINED:\n src/app.py:1: def greet(name):" in observed[0] + assert "src/main.py (1 use)" in observed[0] and "IMPORTED IN:\n src/main.py:1" in observed[0] + + +def test_a_proposal_that_breaks_another_file_is_sent_back_with_the_place_and_no_card_is_shown(monkeypatch): + observed, cards, counted = _run(_drive(monkeypatch, [RENAME])) + assert observed[0].startswith("ERROR: these edits would break other code") + assert "src/main.py:1 imports greet from src.app" in observed[0] + assert cards == [] and {"code_cross_file_refused": 1} in counted + + +def test_the_fixed_proposal_goes_through(monkeypatch): + fixed = {"tool_action": "propose_local_edits", "args": {"summary": "rename", "edits": [ + RENAME["args"]["edits"][0], + {"path": "src/main.py", "old_string": "from src.app import greet\n\nprint(greet('x'))", "new_string": "from src.app import hello\n\nprint(hello('x'))"}, + ]}} + observed, cards, counted = _run(_drive(monkeypatch, [RENAME, fixed])) + assert observed[0].startswith("ERROR") and len(cards) == 1 and "Proposed 2 edit(s)" in observed[1] + assert "cross-file" not in observed[1] + + +def test_the_same_problems_twice_let_the_proposal_through_with_them_named(monkeypatch): + observed, cards, counted = _run(_drive(monkeypatch, [RENAME, RENAME])) + assert observed[0].startswith("ERROR") and len(cards) == 1 + assert "Proposed despite the cross-file check, which still reports: src/main.py:1 imports greet" in observed[1] + assert {"code_cross_file_overridden": 1} in counted + + +def test_a_failing_check_never_stops_a_sound_proposal(monkeypatch): + monkeypatch.setattr(cross_file, "check", lambda *a, **k: (_ for _ in ()).throw(RuntimeError("boom"))) + observed, cards, _ = _run(_drive(monkeypatch, [RENAME])) + assert len(cards) == 1 and not observed[0].startswith("ERROR") + + +def test_the_new_counters_are_known_keys(): + assert {"code_cross_file_refused", "code_cross_file_overridden"} <= self_counters.KEYS + + +# ---- what the mutation check found untested ---- + +def test_a_file_with_the_name_only_inside_a_longer_word_is_not_counted(): + assert symbol_refs.find_references({"a.py": "greeting = 1\n", "b.py": "greet()\n"}.items(), "greet")["files"] == 1 + + +def test_a_call_with_star_arguments_is_never_judged(): + folder = {**FOLDER, "app.py": "from pkg.greet import greet\n\nargs = ['a']\ngreet(*args)\n"} + problems = _check({"pkg/greet.py": FOLDER["pkg/greet.py"].replace("def greet(name, punct='!'):", "def greet(name, greeting, punct='!'):")}, folder) + assert not any(p.startswith("app.py") for p in problems) + assert any(p.startswith("other.py:3") for p in problems) # a plain call to it elsewhere is still judged + + +def test_a_module_with_a_star_import_is_not_judged_for_removals(): + folder = {**FOLDER, "pkg/greet.py": "from somewhere import *\nVERSION = 1\n"} + assert _check({"pkg/greet.py": "from somewhere import *\n"}, folder) == [] # VERSION may still come in through the star + + +def test_an_import_a_ts_file_already_had_is_not_blamed_on_the_proposal(): + folder = {**FOLDER, "web/Banner.tsx": "import { gone } from './api';\nexport const B = 1;\n"} + assert _check({"web/Banner.tsx": "import { gone } from './api';\nexport const B = 2;\n"}, folder) == [] + + +def test_problems_are_capped_even_within_one_file(): + big = "".join(f"V{i} = {i}\n" for i in range(12)) + folder = {**FOLDER, "pkg/many.py": big, "app.py": "".join(f"from pkg.many import V{i}\n" for i in range(12))} + assert len(_check({"pkg/many.py": "X = 1\n"}, folder)) == cross_file.MAX_PROBLEMS + + +def test_a_two_dot_relative_import_resolves_from_the_parent_package(): + folder = {**FOLDER, "rel/deep/__init__.py": "", "rel/deep/x.py": "from ..b import helper\n"} + assert any(p.startswith("rel/deep/x.py:1 imports helper from rel.b") for p in _check({"rel/b.py": None}, folder)) diff --git a/backend/tests/test_fact_cleanup.py b/backend/tests/test_fact_cleanup.py index 8e41cb73..d6251405 100644 --- a/backend/tests/test_fact_cleanup.py +++ b/backend/tests/test_fact_cleanup.py @@ -133,3 +133,17 @@ def test_the_maintenance_command_turns_a_stored_note_id_back_into_an_object_id_a from backend.utils.memory_maintenance import note_id assert note_id("6b0425e571fd1f14cb783a0a") == ObjectId("6b0425e571fd1f14cb783a0a") assert note_id("n1") == "n1" + + +def test_reembed_missing_embeds_only_facts_without_one_and_saves_once_or_not_at_all(): + from backend.utils.memory_maintenance import reembed_missing + + store = Store([_fact("a", "Has one."), _fact("b", "Missing."), _fact("c", "Missing too.")]) + store.facts[1].embedding = None + store.facts[2].embedding = None + embedded = [] + result = reembed_missing(USER, load=store.load, save=store.save, embed=lambda text: embedded.append(text) or ([0.5, 0.5] if text == "Missing." else None)) + assert result == {"embedded": 1, "failed": 1} and embedded == ["Missing.", "Missing too."] and store.saves == 1 + assert [(f.id, f.embedding, f.fact) for f in store.facts] == [("a", [0.1, 0.2], "Has one."), ("b", [0.5, 0.5], "Missing."), ("c", None, "Missing too.")] + saves = store.saves + assert reembed_missing(USER, load=store.load, save=store.save, embed=lambda text: None) == {"embedded": 0, "failed": 1} and store.saves == saves diff --git a/backend/tests/test_local_edits.py b/backend/tests/test_local_edits.py index 095d5bf9..1d39d19e 100644 --- a/backend/tests/test_local_edits.py +++ b/backend/tests/test_local_edits.py @@ -246,7 +246,8 @@ async def test_github_index_tools_are_withheld_and_refused_while_a_folder_is_con assert "cannot see the user's connected local folder" in observed[0] assert "- search_code" not in captured["prompt_template"] - assert "- trace_symbol" not in captured["prompt_template"] + assert aw.LOCAL_TRACE_SYMBOL_LINE in captured["prompt_template"] # trace_symbol comes back in its folder form (2026-11-24) + assert "WRITE/DECIDE" not in captured["prompt_template"] # not the GitHub one assert "- search_literal" in captured["prompt_template"] diff --git a/backend/tests/test_memory_compaction.py b/backend/tests/test_memory_compaction.py index ef3a3d87..ceaa7d5f 100644 --- a/backend/tests/test_memory_compaction.py +++ b/backend/tests/test_memory_compaction.py @@ -723,3 +723,40 @@ def test_the_inferred_confidence_default_is_07(): import inspect assert 'MEMORY_COMPACTION_FACT_CONFIDENCE", "0.7"' in inspect.getsource(mc) + + +# ---- only tier 1 promotes facts (2026-11-24): tier 2 re-mines notes tier 1 already mined, and was two thirds of the compaction fact inflow ---- + +def _tier2_run(monkeypatch, facts): + fake_db = FakeDB() + _seed_chunks(fake_db, "jack", [_chunk("Tier-1 summary A", [1.0, 0.0, 0.0], _id="t1-a"), _chunk("Tier-1 summary B", [0.99, 0.01, 0.0], _id="t1-b")]) + for doc in fake_db["user_memory_chunks"].docs: + doc["source_type"] = "compacted_summary" + monkeypatch.setattr(mc.lite_llm, "ainvoke", AsyncMock(return_value=SimpleNamespace(content=json.dumps({"summary": "Meta summary.", "facts": facts})))) + monkeypatch.setattr(mc, "embed_and_store_memory_chunk", _fake_embed_into(fake_db)) + saved = [] + monkeypatch.setattr(mc, "save_user_fact", lambda username, fact, **k: saved.append(fact)) + result = asyncio.run(mc.compact_meta_memory(fake_db, vector_store=object(), username="jack")) + return result, saved, fake_db + + +def test_tier_two_keeps_its_summary_but_saves_none_of_the_facts_it_names(monkeypatch): + monkeypatch.setattr(mc, "TIER2_PROMOTES_FACTS", False) + result, saved, fake_db = _tier2_run(monkeypatch, [{"category": "career", "domain": "work", "fact": "Jack specializes in AWS Lambda migrations."}]) + assert result["status"] == "completed" and result["facts_promoted"] == 0 and saved == [] + assert [d["text"] for d in fake_db["user_memory_chunks"].find({"username": "jack"})] == ["Meta summary."] + assert mc.promotes_facts(1) and not mc.promotes_facts(2) + + +def test_the_switch_turns_tier_two_promotion_back_on(monkeypatch): + monkeypatch.setattr(mc, "TIER2_PROMOTES_FACTS", True) + result, saved, _db = _tier2_run(monkeypatch, [{"category": "career", "domain": "work", "fact": "Jack specializes in AWS Lambda migrations."}]) + assert saved == ["Jack specializes in AWS Lambda migrations."] and result["facts_promoted"] == 1 + + +def test_tier_two_promotion_is_off_unless_asked_for(monkeypatch): + import importlib + + monkeypatch.delenv("MEMORY_TIER2_FACTS", raising=False) + source = importlib.util.find_spec("backend.services.memory_compaction").loader.get_source("backend.services.memory_compaction") + assert 'os.getenv("MEMORY_TIER2_FACTS", "off")' in source diff --git a/backend/utils/cross_file.py b/backend/utils/cross_file.py new file mode 100644 index 00000000..64fc94bf --- /dev/null +++ b/backend/utils/cross_file.py @@ -0,0 +1,299 @@ +"""The other end of a proposed edit: does it break a file it does not touch? (2026-11-24 coding audit.) + +WHY. A proposal is checked file by file (backend/services/local_edits.py: the old text matches, the result parses, every name it uses is defined or imported). Nothing looked ACROSS files, and that is +where multi-file changes went wrong: 35% of proposals in a month were rework of a file applied minutes before. The cases code can decide exactly: + +1. Python: a top-level function, class or name the proposal removes or renames that another file still imports (`from pkg.mod import name`) or reaches as `mod.name`. +2. Python: a function whose new signature its callers no longer fit (a call passes fewer positional arguments than it now requires, or a keyword it no longer accepts), in any file that imports it, + and in the file itself. +3. Python: a new `from pkg.mod import name` (in an edited file) of a name the folder's module does not define after the proposal. +4. JS/TS: a named export the proposal removes that another file still imports from it by a relative path, and a new named import (in an edited file) of something the target file does not export. + +Anything uncertain is left alone (a star import, `__getattr__`, `__all__` tricks, an import from a package outside the folder, a default export, a call with *args or **kwargs). Pure: the caller hands +in the edited files' before/after text and a way to read the rest of the folder. +""" +import ast +import posixpath +import re +from typing import Callable, Dict, Iterable, List, Optional, Set, Tuple + +MAX_PROBLEMS = 8 +MAX_SCANNED_FILES = 3000 +MAX_SCANNED_BYTES = 30_000_000 +PY = (".py",) +JS = (".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs") +_JS_RESOLVE = ("", ".ts", ".tsx", ".js", ".jsx", ".mjs", "/index.ts", "/index.tsx", "/index.js", "/index.jsx") + + +# ---------------------------------------------------------------------------------------------- Python + +def module_name(path: str) -> Optional[str]: + """"backend/utils/x.py" -> "backend.utils.x"; a package's __init__.py -> the package. Pure.""" + if not path.endswith(".py"): + return None + parts = path[:-3].split("/") + if parts[-1] == "__init__": + parts = parts[:-1] + return ".".join(parts) if parts and all(p.isidentifier() for p in parts) else None + + +def _parse(text: Optional[str]) -> Optional[ast.Module]: + try: + return ast.parse(text or "") + except SyntaxError: + return None + + +class _Signature: + def __init__(self, node: ast.AST): + args = node.args + positional = list(args.posonlyargs) + list(args.args) + if positional and positional[0].arg in ("self", "cls"): + positional = positional[1:] + self.max_positional = None if args.vararg else len(positional) + self.required_positional = len(positional) - len(args.defaults) + self.required_names = [a.arg for a in positional[: self.required_positional]] # in order: a call fills them by position first, then by name + self.keywords = {a.arg for a in list(args.args) + list(args.kwonlyargs)} + self.required_keyword_only = {a.arg for a, d in zip(args.kwonlyargs, args.kw_defaults) if d is None} + self.any_keyword = args.kwarg is not None + self.is_class = False + + +def top_level(text: Optional[str]) -> Optional[Dict[str, object]]: + """{name: _Signature | True} for what a Python module defines at top level, or None when it cannot be judged (does not parse, star import, module __getattr__). Pure.""" + tree = _parse(text) + if tree is None: + return None + names: Dict[str, object] = {} + for node in tree.body: + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): + if node.name == "__getattr__": + return None + names[node.name] = _Signature(node) + elif isinstance(node, ast.ClassDef): + names[node.name] = True + elif isinstance(node, (ast.Assign, ast.AnnAssign, ast.AugAssign)): + for target in (node.targets if isinstance(node, ast.Assign) else [node.target]): + for sub in ast.walk(target): + if isinstance(sub, ast.Name): + names[sub.id] = True + elif isinstance(node, (ast.Import, ast.ImportFrom)): + for alias in node.names: + if alias.name == "*": + return None + names[(alias.asname or alias.name).split(".")[0]] = True + elif isinstance(node, (ast.If, ast.Try, ast.With, ast.For, ast.While)): + for sub in ast.walk(node): # names defined under a guard (try/except ImportError, if TYPE_CHECKING) still exist + if isinstance(sub, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): + names.setdefault(sub.name, True) + elif isinstance(sub, ast.Name) and isinstance(sub.ctx, ast.Store): + names.setdefault(sub.id, True) + elif isinstance(sub, (ast.Import, ast.ImportFrom)): + for alias in sub.names: + names.setdefault((alias.asname or alias.name).split(".")[0], True) + return names + + +def _resolve_from(importer: str, node: ast.ImportFrom) -> Optional[str]: + if not node.level: + return node.module + package = importer[:-3].split("/")[:-1] if importer.endswith(".py") else [] + if node.level > 1: + package = package[: len(package) - (node.level - 1)] + return ".".join(package + ([node.module] if node.module else [])) or None + + +def _python_imports(path: str, tree: ast.Module) -> Tuple[List[Tuple[str, str, int, str]], Dict[str, str]]: + """([(module, name, line, local_name)] from `from x import y`), {local alias: module} for `import x.y as z`. Pure.""" + froms, modules = [], {} + for node in ast.walk(tree): + if isinstance(node, ast.ImportFrom): + source = _resolve_from(path, node) + if source: + for alias in node.names: + if alias.name != "*": + froms.append((source, alias.name, node.lineno, alias.asname or alias.name)) + elif isinstance(node, ast.Import): + for alias in node.names: + modules[alias.asname or alias.name] = alias.name + return froms, modules + + +def _call_misfit(call: ast.Call, signature: "_Signature") -> Optional[str]: + if any(isinstance(a, ast.Starred) for a in call.args) or any(k.arg is None for k in call.keywords): + return None # *args / **kwargs at the call: cannot tell + given = len(call.args) + named = {k.arg for k in call.keywords} + if signature.max_positional is not None and given > signature.max_positional: + return f"passes {given} positional arguments, the new signature takes at most {signature.max_positional}" + missing = [name for name in signature.required_names[given:] if name not in named] + if missing: + return f"passes {given} positional argument{'s' if given != 1 else ''}, the new signature requires {signature.required_positional}" + unknown = sorted(named - signature.keywords) if not signature.any_keyword else [] + if unknown: + return f"passes {', '.join(unknown)}=, which the new signature no longer accepts" + absent = sorted(signature.required_keyword_only - named) + if absent: + return f"does not pass {', '.join(absent)}=, which the new signature requires" + return None + + +# ---------------------------------------------------------------------------------------------- JS / TS + +_EXPORT_DECL_RE = re.compile(r"^\s*export\s+(?:declare\s+)?(?:default\s+)?(?:async\s+)?(?:function\*?|class|const|let|var|interface|type|enum|abstract\s+class)\s+([A-Za-z_$][\w$]*)", re.MULTILINE) +_EXPORT_LIST_RE = re.compile(r"^\s*export\s+(?:type\s+)?\{([^}]*)\}", re.MULTILINE) +_EXPORT_STAR_RE = re.compile(r"^\s*export\s+\*", re.MULTILINE) +_NAMED_IMPORT_RE = re.compile(r"^\s*import\s+(?:type\s+)?(?:[A-Za-z_$][\w$]*\s*,\s*)?\{([^}]*)\}\s*from\s*['\"](\.{1,2}/[^'\"]+)['\"]", re.MULTILINE) + + +def js_exports(text: Optional[str]) -> Optional[Set[str]]: + """The named exports of a JS/TS file, or None when they cannot be judged (an `export *`). Pure.""" + if text is None: + return set() + if _EXPORT_STAR_RE.search(text): + return None + names = set(_EXPORT_DECL_RE.findall(text)) + for listed in _EXPORT_LIST_RE.findall(text): + for part in listed.split(","): + part = part.strip() + if part: + names.add(part.split(" as ")[-1].strip().replace("type ", "").strip()) + return names + + +def _named_imports(text: str) -> List[Tuple[str, str, int]]: + """[(imported name, relative specifier, line)] for `import { a, b as c } from './x'`. Pure.""" + found = [] + for match in _NAMED_IMPORT_RE.finditer(text or ""): + line = text.count("\n", 0, match.start()) + 1 + for part in match.group(1).split(","): + part = part.strip().replace("type ", "", 1).strip() + if part: + found.append((part.split(" as ")[0].strip(), match.group(2), line)) + return found + + +def _resolve_js(importer: str, specifier: str, exists: Callable[[str], bool]) -> Optional[str]: + base = posixpath.normpath(posixpath.join(posixpath.dirname(importer), specifier)) + for suffix in _JS_RESOLVE: + if exists(base + suffix): + return base + suffix + return None + + +# ---------------------------------------------------------------------------------------------- the check + +def check(before: Dict[str, Optional[str]], after: Dict[str, Optional[str]], paths: Iterable[str], read: Callable[[str], Optional[str]]) -> List[str]: + """The problems the proposal would cause in other files (and in its own calls), as sentences with file:line, at most MAX_PROBLEMS. `before`/`after`: every file the proposal touches, None for a + file that does not exist (before) or is gone (after). `paths`: every file in the folder. `read(path)`: a file's current text. Pure apart from `read`.""" + paths = [p for p in paths if p.endswith(PY + JS)] + state = lambda path: after[path] if path in after else read(path) # noqa: E731 the folder as it will be + exists = lambda path: (after[path] is not None) if path in after else path in path_set # noqa: E731 + path_set = set(paths) + problems: List[str] = [] + + # what changed, per edited module + py_removed: Dict[str, Dict[str, str]] = {} # module -> {name: path} + py_signature: Dict[str, Dict[str, "_Signature"]] = {} + py_module_names: Dict[str, Optional[Dict[str, object]]] = {} + js_removed: Dict[str, Set[str]] = {} + for path in after: + if path.endswith(PY): + module = module_name(path) + old, new = top_level(before.get(path)), top_level(after[path]) if after[path] is not None else {} + if module and old is not None and new is not None: + gone = {n: path for n in old if n not in new and not n.startswith("__")} + if gone: + py_removed[module] = gone + changed = {n: s for n, s in new.items() if isinstance(s, _Signature) and isinstance(old.get(n), _Signature) and vars(s) != vars(old[n])} + if changed: + py_signature[module] = changed + if module: + py_module_names[module] = new + elif path.endswith(JS): + old, new = js_exports(before.get(path)), js_exports(after[path]) if after[path] is not None else set() + if old is not None and new is not None and old - new: + js_removed[path] = old - new + + # A file the proposal does not touch can only be broken by it if it mentions a name that changed: anything else is skipped without being parsed. + watched = {n for names in py_removed.values() for n in names} | {n for names in py_signature.values() for n in names} | {n for names in js_removed.values() for n in names} + scanned_bytes = 0 + for path in paths[:MAX_SCANNED_FILES]: + if len(problems) >= MAX_PROBLEMS: + break + edited = path in after + text = state(path) + if not text or (not edited and not any(name in text for name in watched)): + continue + scanned_bytes += len(text) + if scanned_bytes > MAX_SCANNED_BYTES: + break + if path.endswith(PY) and (py_removed or py_signature or edited): + tree = _parse(text) + if tree is None: + continue + froms, modules = _python_imports(path, tree) + old_tree = _parse(before.get(path)) if edited else None + already = {(m, n) for m, n, _l, _a in _python_imports(path, old_tree)[0]} if old_tree is not None else set() + for module, name, line, _local in froms: + if name in py_removed.get(module, {}): + problems.append(f"{path}:{line} imports {name} from {module}, which this proposal removes from {py_removed[module][name]}. Update that import (and its uses) in the same proposal") + continue + if not edited or (module, name) in already: + continue # only an import this proposal adds is checked against its module + base = module.replace(".", "/") + module_path = next((p for p in (base + ".py", base + "/__init__.py") if exists(p)), None) + if module_path is None: + continue # a module outside the folder (a library): not ours to judge + names = py_module_names[module] if module in py_module_names else top_level(state(module_path)) + is_submodule = exists(f"{base}/{name}.py") or exists(f"{base}/{name}/__init__.py") + if names is not None and name not in names and not is_submodule: + problems.append(f"{path}:{line} imports {name} from {module}, but {module} does not define {name}. Import a name that exists, or add it to that module in the same proposal") + # calls whose arguments no longer fit a changed signature, and mod.name uses of a removed name + local_sigs: Dict[str, "_Signature"] = {} + for module, name, _line, local in froms: + if name in py_signature.get(module, {}): + local_sigs[local] = py_signature[module][name] + own = module_name(path) + if edited and own in py_signature: + local_sigs.update(py_signature[own]) + module_aliases = {alias: mod for alias, mod in modules.items() if mod in py_removed or mod in py_signature} + for module, name, _line, local in froms: # `from backend.utils import low_moves` then low_moves.choose(...): the name is itself a module + if f"{module}.{name}" in py_removed or f"{module}.{name}" in py_signature: + module_aliases[local] = f"{module}.{name}" + for node in ast.walk(tree): + if isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name) and node.value.id in module_aliases: + mod = module_aliases[node.value.id] + if node.attr in py_removed.get(mod, {}): + problems.append(f"{path}:{node.lineno} uses {node.value.id}.{node.attr}, which this proposal removes from {py_removed[mod][node.attr]}. Update it in the same proposal") + if isinstance(node, ast.Call): + target = None + if isinstance(node.func, ast.Name) and node.func.id in local_sigs: + target, label = local_sigs[node.func.id], node.func.id + elif isinstance(node.func, ast.Attribute) and isinstance(node.func.value, ast.Name) and node.func.value.id in module_aliases: + mod = module_aliases[node.func.value.id] + target, label = py_signature.get(mod, {}).get(node.func.attr), f"{node.func.value.id}.{node.func.attr}" + if target is not None: + misfit = _call_misfit(node, target) + if misfit: + problems.append(f"{path}:{node.lineno} calls {label}(...) and {misfit}. Update the call in the same proposal") + if len(problems) >= MAX_PROBLEMS: + break + elif path.endswith(JS): + already = {(n, s) for n, s, _l in _named_imports(before.get(path) or "")} if edited else set() + for name, specifier, line in _named_imports(text): + target = _resolve_js(path, specifier, exists) + if target is None: + continue + if name in js_removed.get(target, set()): + problems.append(f"{path}:{line} imports {name} from '{specifier}', which this proposal removes from {target}. Update that import (and its uses) in the same proposal") + elif edited and (name, specifier) not in already and target.endswith(JS): + exported = js_exports(state(target)) + if exported is not None and name not in exported: + problems.append(f"{path}:{line} imports {name} from '{specifier}', but {target} does not export {name}. Import a name it exports, or export it in the same proposal") + seen, unique = set(), [] + for problem in problems: + if problem not in seen: + seen.add(problem) + unique.append(problem) + return unique[:MAX_PROBLEMS] diff --git a/backend/utils/memory_maintenance.py b/backend/utils/memory_maintenance.py index ec4fd1e2..48afdf1d 100644 --- a/backend/utils/memory_maintenance.py +++ b/backend/utils/memory_maintenance.py @@ -7,6 +7,7 @@ python -m backend.utils.memory_maintenance restore-pruned-facts --username U [--source explicit] [--show] [--apply] # bring back pruned facts python -m backend.utils.memory_maintenance fix-facts --username U --changes FILE --run ID [--apply] # approved rewrites/removals of facts, notes flagged stale (backend/utils/fact_cleanup.py) python -m backend.utils.memory_maintenance restore-fact-fixes --username U --run ID [--apply] # undo a fix-facts run + python -m backend.utils.memory_maintenance reembed-missing --username U [--apply] # embed facts that have no embedding (never found by relevance) strip-labels: until the label fix, about a third of the saved notes begin with the model's "SUMMARY:" (it copied the last word of the prompt). That word was embedded into the note, which made unrelated notes look alike to the recall search. This removes the label @@ -189,6 +190,9 @@ def main(argv: Optional[List[str]] = None) -> int: unfix.add_argument("--username", required=True) unfix.add_argument("--run", required=True) unfix.add_argument("--apply", action="store_true", help="actually restore (default: only count)") + reembed = sub.add_parser("reembed-missing", help="embed the facts that have no embedding, so recall can find them by relevance") + reembed.add_argument("--username", required=True) + reembed.add_argument("--apply", action="store_true", help="actually embed and save (default: only count)") args = parser.parse_args(argv) from dotenv import load_dotenv @@ -213,6 +217,16 @@ def main(argv: Optional[List[str]] = None) -> int: return _restore_domains_command(db, args.username, args.run, args.apply) if args.command == "fix-facts": return _fix_facts_command(db, args.username, args.changes, args.run, args.apply, embed_text) + if args.command == "reembed-missing": + from backend.utils import memory_utils + + missing = [f for f in memory_utils.load_user_facts(args.username) if not f.embedding] + print(f"{len(missing)} fact(s) have no embedding.") + if not args.apply: + print("Dry run: nothing changed. Add --apply to embed them.") + return 0 + print(reembed_missing(args.username, load=memory_utils.load_user_facts, save=memory_utils.save_user_facts, embed=embed_text)) + return 0 if args.command == "restore-fact-fixes": return _restore_fact_fixes_command(db, args.username, args.run, args.apply) collection = db[USER_MEMORY_COLLECTION] @@ -380,6 +394,24 @@ def _restore_command(db: Any, run: str, apply: bool) -> int: return 0 +def reembed_missing(username: str, *, load: Callable, save: Callable, embed: Callable) -> Dict[str, int]: + """Gives every fact with no embedding one (2026-11-23: 10 of 887 had none, so recall could never find them by relevance). Text, dates and everything else stay as they + were. One save at the end, only when something was embedded. {"embedded", "failed"}.""" + facts = load(username) + done = failed = 0 + for fact in facts: + if fact.embedding: + continue + vector = embed(fact.fact) + if vector: + fact.embedding, done = vector, done + 1 + else: + failed += 1 + if done: + save(username, facts) + return {"embedded": done, "failed": failed} + + def note_id(value: Any) -> Any: """A note id as the database stores it: a 24-hex string becomes an ObjectId, anything else is left as it is. Pure.""" from bson import ObjectId diff --git a/backend/utils/self_counters.py b/backend/utils/self_counters.py index c725f124..cc2e3524 100644 --- a/backend/utils/self_counters.py +++ b/backend/utils/self_counters.py @@ -99,7 +99,7 @@ # How much each turn mattered, whatever model wrote it (backend/utils/reply_tier.py STAKES, plus "none" for a plain turn): sizes the turns a stronger reply voice would be spent on. Counts only. "reply_stakes": ("safety", "emotional", "checkin", "companion", "identity", "frustration", "none"), } -_PLAIN_KEYS = ("turns_total", "self_model_used", "experience_captured", "experience_capture_merged", "experience_capture_invalid", "experience_offered", "experience_cited", "native_runs", "native_calls", "native_chars_sent", "native_chars_results", "native_chars_instructions", "native_chars_tools", "native_chars_preferences", "native_chars_architecture", "native_chars_memory", "native_chars_history", "native_chars_leanings", "leaning_turns", "native_chars_environment", "native_chars_request", "code_plan_turns", "code_plan_exec_tool_steps", "code_plan_exec_early", "code_plan_fed_next", "code_plan_turn_cap_hit", "code_plan_submitted", "code_plan_invalid", "code_plan_approved", "code_plan_cancelled", "code_plan_stalled", "code_plan_halted", "code_plan_marked_done", "claim_unproven", "claim_sent_back", "claim_edit_unbacked", "code_plan_exec_turns", "code_plan_exec_cap_hit", "code_plan_exec_edited", "code_plan_steps_done", "code_plan_prefetched", "code_plan_deviation", "code_pushback", "code_frustrated", "code_proposals", "code_proposal_rework", "code_edit_calls", "code_edit_errors", "code_test_runs", "code_edit_applied", "code_edit_declined", "code_edit_undone", "code_edit_applied_small", "code_edit_applied_large", "code_edit_declined_small", "code_edit_declined_large", "code_edit_undone_small", "code_edit_undone_large", "working_notes_updated", "working_notes_item_added", "working_notes_item_dropped", "working_notes_injected", "working_notes_chat_read", "reply_fit_checked", "reward_evaluated", "relatable_offered", "self_mention", "observations_injected", "observations_used", "experience_placed", "relatable_placed", "take_offered", "corrections_carried", "goal_guard_shown", "care_pause_shown", "timeline_shown", "vague_fact_skipped", "hear_you_held", "reply_bans_shown", "notes_standout_held", "notes_second_look", "notes_second_look_kept", "low_move_push_back", "low_move_pattern", "low_move_company", "support_choice_offered", "support_choice_listen", "support_choice_advice", "support_choice_fix", "support_mode_applied", "encouragement_offered", "open_loop_captured", "open_loop_offered", "open_loop_resolved", "callback_offered", "self_history_offered", "initiation_offered", "initiation_fallback", "initiation_answered", "initiation_interest_offered", "initiation_interest_answered", "duration_offered", "curiosity_offered", "curiosity_taken", "shelf_offered", "shelf_taken", "shelf_listed", "finding_selected", "lean_offered", "guardrail_applied", "routines_offered", "followups_offered", "task_results_offered", "meeting_turns", "headsup_offered", "clarify_noted", "clarify_asked", "clarify_answered", "memory_note_dropped", "memory_note_trimmed", "status_offered", "offer_made", "offer_taken", "offer_passed", "offer_held_back", "code_turns", "code_cap_hit", "code_edited", "code_verified", "code_followed", "code_redo") +_PLAIN_KEYS = ("turns_total", "self_model_used", "experience_captured", "experience_capture_merged", "experience_capture_invalid", "experience_offered", "experience_cited", "native_runs", "native_calls", "native_chars_sent", "native_chars_results", "native_chars_instructions", "native_chars_tools", "native_chars_preferences", "native_chars_architecture", "native_chars_memory", "native_chars_history", "native_chars_leanings", "leaning_turns", "native_chars_environment", "native_chars_request", "code_plan_turns", "code_plan_exec_tool_steps", "code_plan_exec_early", "code_plan_fed_next", "code_plan_turn_cap_hit", "code_plan_submitted", "code_plan_invalid", "code_plan_approved", "code_plan_cancelled", "code_plan_stalled", "code_plan_halted", "code_plan_marked_done", "claim_unproven", "claim_sent_back", "claim_edit_unbacked", "code_plan_exec_turns", "code_plan_exec_cap_hit", "code_plan_exec_edited", "code_plan_steps_done", "code_plan_prefetched", "code_plan_deviation", "code_pushback", "code_frustrated", "code_proposals", "code_proposal_rework", "code_edit_calls", "code_edit_errors", "code_test_runs", "code_edit_applied", "code_edit_declined", "code_edit_undone", "code_edit_applied_small", "code_edit_applied_large", "code_edit_declined_small", "code_edit_declined_large", "code_edit_undone_small", "code_edit_undone_large", "working_notes_updated", "working_notes_item_added", "working_notes_item_dropped", "working_notes_injected", "working_notes_chat_read", "reply_fit_checked", "reward_evaluated", "relatable_offered", "self_mention", "observations_injected", "observations_used", "experience_placed", "relatable_placed", "take_offered", "corrections_carried", "goal_guard_shown", "care_pause_shown", "timeline_shown", "vague_fact_skipped", "hear_you_held", "code_cross_file_refused", "code_cross_file_overridden", "reply_bans_shown", "notes_standout_held", "notes_second_look", "notes_second_look_kept", "low_move_push_back", "low_move_pattern", "low_move_company", "support_choice_offered", "support_choice_listen", "support_choice_advice", "support_choice_fix", "support_mode_applied", "encouragement_offered", "open_loop_captured", "open_loop_offered", "open_loop_resolved", "callback_offered", "self_history_offered", "initiation_offered", "initiation_fallback", "initiation_answered", "initiation_interest_offered", "initiation_interest_answered", "duration_offered", "curiosity_offered", "curiosity_taken", "shelf_offered", "shelf_taken", "shelf_listed", "finding_selected", "lean_offered", "guardrail_applied", "routines_offered", "followups_offered", "task_results_offered", "meeting_turns", "headsup_offered", "clarify_noted", "clarify_asked", "clarify_answered", "memory_note_dropped", "memory_note_trimmed", "status_offered", "offer_made", "offer_taken", "offer_passed", "offer_held_back", "code_turns", "code_cap_hit", "code_edited", "code_verified", "code_followed", "code_redo") # The rhythm of a coding turn (backend/utils/loop_rhythm.py): turns it was followed on, turns that acted at all, reads before the first act (summed), edits applied, applied edits checked in the next # step, and reading-streak notices shown. Counts only. RHYTHM_KEYS = ("code_rhythm_turns", "code_rhythm_acted_turns", "code_rhythm_reads_before_first_act", "code_rhythm_applies", "code_rhythm_applies_checked", "code_rhythm_streak_notices") diff --git a/backend/utils/symbol_refs.py b/backend/utils/symbol_refs.py new file mode 100644 index 00000000..bcc03367 --- /dev/null +++ b/backend/utils/symbol_refs.py @@ -0,0 +1,97 @@ +"""Every place a name appears in a folder, sorted into where it is DEFINED, where it is IMPORTED and where it is USED, with line numbers (trace_symbol on a connected folder). + +WHY (2026-11-24 coding audit). With a folder connected, search_code and trace_symbol were withheld (they ask GitHub's index, which cannot see uncommitted code), leaving only search_literal: a +case-insensitive substring search with no word boundary and no idea which hit is the definition. On a multi-file change Haiku either missed a caller or spent steps opening hits one by one. This greps +the folder's own files, whole words only and case-sensitive (an identifier is), and says which hit is the definition. Pure: the caller hands in (path, text) pairs. +""" +import re +from typing import Dict, Iterable, List, Tuple + +SEARCHED_SUFFIXES = (".py", ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".css", ".scss", ".html", ".json", ".yml", ".yaml", ".toml", ".sql", ".md", ".sh") +MAX_USES_PER_FILE = 4 +MAX_FILES_SHOWN = 25 +MAX_DEFINITIONS = 10 +MAX_LINE_CHARS = 160 + +_IMPORT_RE = re.compile(r"^\s*(?:from\s+\S+\s+import\b|import\b|export\s+(?:\*|\{[^}]*\})\s+from\b)|\brequire\s*\(") + + +def _word(symbol: str) -> "re.Pattern": + """The symbol as a whole word: not part of a longer identifier on either side ($ and - count as part of one, for JS names and CSS classes).""" + return re.compile(r"(? str: + """"define", "import" or "use" for a line that contains the symbol. Pure.""" + s = re.escape(symbol) + if _IMPORT_RE.search(line): + return "import" + stripped = line.strip() + definition = ( + rf"^(?:export\s+(?:default\s+)?)?(?:declare\s+)?(?:async\s+)?(?:def|class|function\*?|interface|type|enum)\s+{s}\b", # def / class / function / interface / type / enum + rf"^(?:export\s+)?(?:const|let|var)\s+{s}\b", # const X = / let X + rf"^(?:export\s+)?(?:const|let|var)\s+\{{[^}}]*\b{s}\b[^}}]*\}}\s*=", # const { X } = ... + rf"^self\.{s}\s*(?::[^=]+)?=(?!=)", # self.X = ... + rf"^(?:public\s+|private\s+|protected\s+|static\s+|readonly\s+|async\s+|get\s+|set\s+)*{s}\s*\([^;]*\)\s*(?::[^;={{]+)?\{{\s*$", # a method: X(a, b) { + rf"^\.{s}\s*\{{", # a CSS rule: .X { + ) + if any(re.search(pattern, stripped) for pattern in definition): + return "define" + if not line[:1].isspace() and re.match(rf"^{s}\s*(?::[^=]+)?=(?!=)", stripped): + return "define" # a module-level X = ... + return "use" + + +def find_references(files: Iterable[Tuple[str, str]], symbol: str) -> Dict[str, object]: + """{"definitions": [(path, line_no, text)], "imports": {path: [line_no]}, "uses": {path: [(line_no, text)]}, "files": n} for a whole-word symbol. Pure.""" + symbol = (symbol or "").strip() + found = {"definitions": [], "imports": {}, "uses": {}, "files": 0} + if not symbol: + return found + pattern = _word(symbol) + for path, text in files: + if not path.lower().endswith(SEARCHED_SUFFIXES) or symbol not in (text or ""): + continue + hit = False + for number, line in enumerate(text.splitlines(), start=1): + if not pattern.search(line): + continue + hit = True + kind = classify(symbol, line) + shown = " ".join(line.split())[:MAX_LINE_CHARS] + if kind == "define": + found["definitions"].append((path, number, shown)) + elif kind == "import": + found["imports"].setdefault(path, []).append(number) + else: + found["uses"].setdefault(path, []).append((number, shown)) + found["files"] += hit + return found + + +def format_references(found: Dict[str, object], symbol: str) -> str: + """What the model reads: definitions first, then each file that uses it with its first lines, then the importers. Pure.""" + definitions: List[Tuple[str, int, str]] = found["definitions"] # type: ignore[assignment] + imports: Dict[str, List[int]] = found["imports"] # type: ignore[assignment] + uses: Dict[str, List[Tuple[int, str]]] = found["uses"] # type: ignore[assignment] + if not definitions and not imports and not uses: + return (f"No whole-word matches for {symbol!r} in the folder (matching is exact and case-sensitive). For a colloquial name use find_file; for text that is part of a longer word, " + "use search_literal.") + parts = [f"{symbol!r} appears in {found['files']} file(s) of the connected folder (whole word, case-sensitive)."] + if definitions: + parts.append("DEFINED:\n" + "\n".join(f" {p}:{n}: {t}" for p, n, t in definitions[:MAX_DEFINITIONS]) + + (f"\n ... and {len(definitions) - MAX_DEFINITIONS} more" if len(definitions) > MAX_DEFINITIONS else "")) + else: + parts.append("DEFINED: no definition found in the folder (it may come from a library, or be built dynamically).") + if uses: + ordered = sorted(uses.items(), key=lambda item: (-len(item[1]), item[0])) + lines = [] + for path, hits in ordered[:MAX_FILES_SHOWN]: + shown = "\n".join(f" {n}: {t}" for n, t in hits[:MAX_USES_PER_FILE]) + more = f"\n ... {len(hits) - MAX_USES_PER_FILE} more in this file" if len(hits) > MAX_USES_PER_FILE else "" + lines.append(f" {path} ({len(hits)} use{'s' if len(hits) != 1 else ''})\n{shown}{more}") + extra = f"\n ... and {len(ordered) - MAX_FILES_SHOWN} more file(s)" if len(ordered) > MAX_FILES_SHOWN else "" + parts.append("USED (every file you change it in, or that calls it, may need an edit):\n" + "\n".join(lines) + extra) + if imports: + parts.append("IMPORTED IN:\n" + "\n".join(f" {p}:{','.join(str(n) for n in ns[:3])}" for p, ns in sorted(imports.items()))) + return "\n\n".join(parts)