From 52bccd2a04c83aff637e503c5d05729f70b8a330 Mon Sep 17 00:00:00 2001 From: Dennis Palatov Date: Mon, 16 Nov 2026 11:16:10 -0800 Subject: [PATCH 1/2] memory_edit: the receipt names the line it changed, and which copy when a def is pasted twice cbp-being 2026-11-16 19:02Z: old='da1 = dz2 @ W2.T' was meant for line 134, which already held the new text, so the only match was line 313 in a second pasted `def mlp_xor` (line 288) below the __main__ guard at line 219. The receipt said only "replaced 1 occurrence"; the run crashed at line 134 as before and reflect journaled a cause that was already fixed on disk. Text mode now says "on line N"; for .py, when the enclosing top-level def/class is defined more than once, it names the copy and the other lines, and whether the copy sits below the first __main__ guard. Ranged whole-line edits get the same copy note. Located before the 240-char cut reflect sees (RECORD_RESULT_CHARS). Co-Authored-By: Claude Opus 5.5 --- sage/gateway/reference_f1a.py | 55 ++++++++++++- .../tests/test_memory_edit_names_the_copy.py | 80 +++++++++++++++++++ 2 files changed, 133 insertions(+), 2 deletions(-) create mode 100644 sage/gateway/tests/test_memory_edit_names_the_copy.py diff --git a/sage/gateway/reference_f1a.py b/sage/gateway/reference_f1a.py index 12ac164e9..92bc49717 100644 --- a/sage/gateway/reference_f1a.py +++ b/sage/gateway/reference_f1a.py @@ -479,6 +479,50 @@ def _head_and_tail(removed: str, budget: int = 400) -> str: return "".join(head) + f"[... {hidden} more removed lines not shown ...]\n" + "".join(tail) +_DEF_LINE = re.compile(r"^([ \t]*)(?:async[ \t]+)?(?:def|class)[ \t]+(\w+)") + + +def _which_copy(text: str, line: int) -> str: + """For a .py edit on `line`: the def/class it sits in, when the file defines that name more + than once at the same depth. "" otherwise. + + AN EDIT CAN LAND IN A COPY THAT NEVER RUNS. cbp-being, 2026-11-16 19:02Z: its file held three + pasted versions of an XOR program (two `def mlp_xor` at lines 100 and 288). It meant to fix + line 134 with old='da1 = dz2 @ W2.T'; line 134 already read `W2.T @ dz2` from its previous + beat, so the only match was line 313 in the second copy, which main() at line 219 never + reaches. The receipt said "replaced 1 occurrence" and nothing about where, the run crashed + at line 134 as before, and reflect journaled the fix as the cause still to find. The line + number, and which copy it is in, are the two facts that would have shown the miss.""" + # Top level only: two classes that each have `__init__` are not two copies of anything. + lines = text.splitlines() + if not 1 <= line <= len(lines): + return "" + if lines[line - 1][:1] not in (" ", "\t") and not _DEF_LINE.match(lines[line - 1]): + return "" # a top-level statement is in no def + for i in range(line - 1, -1, -1): + m = _DEF_LINE.match(lines[i]) + if m and not m.group(1): + name = m.group(2) + break + if lines[i].strip() and lines[i][:1] not in (" ", "\t", "#") and i != line - 1: + return "" # left the indented block without meeting a def/class + else: + return "" + at = [j for j, ln in enumerate(lines, 1) + if (mm := _DEF_LINE.match(ln)) and not mm.group(1) and mm.group(2) == name] + if len(at) < 2: + return "" + note = (f", inside '{name}' at line {i + 1}; this file defines {name} {len(at)} times (lines " + f"{', '.join(map(str, at))}), and only the one at line {i + 1} changed") + g = _MAIN_GUARD.search(text) + guard = text.count("\n", 0, g.start()) + 1 if g else 0 + if g and guard < i + 1: + # The same fact test_nothing_is_defined_after_the_main_guard checks on SAGE's own code. + note += (f". It is below the `if __name__ == \"__main__\":` at line {guard}, so a run " + f"executes that guard before this copy is defined") + return note + + def _defs_removed(removed: str) -> str: """Name every def/class line a removal took, since a quote can be cut but a name list is short.""" names = [ln.strip().split("(")[0].rstrip(":") for ln in removed.splitlines() @@ -2051,7 +2095,10 @@ def _do_memory_edit(self, intent: BeingIntent) -> ResultEnvelope: if repl and not repl.endswith("\n") and removed.endswith("\n"): repl += "\n" new_text = "".join(lines[:s0 - 1]) + repl + "".join(lines[s1:]) - what = f"replaced lines {s0}-{s1} ({s1 - s0 + 1} lines)" + _indent_changed(removed, new, s0) + what = f"replaced lines {s0}-{s1} ({s1 - s0 + 1} lines)" + if str(p).endswith(".py"): + what += _which_copy(text, s0) + what += _indent_changed(removed, new, s0) gone = f" The lines removed were:\n{_head_and_tail(removed)}" + _defs_removed(removed) if str(p).endswith(".py") and not _parses(new_text): gone = _spaces_verdict(lines, s0, s1, removed, new) + gone @@ -2184,8 +2231,12 @@ def _do_memory_edit(self, intent: BeingIntent) -> ResultEnvelope: f"{at} now reads {line!r}. To set the whole line, call memory_edit with " f"start_line={at} end_line={at}, old set to that line, and new set to the " f"line you want.")) + at = text.count("\n", 0, text.find(old)) + 1 + what = f"replaced 1 occurrence, on line {at}" + if str(p).endswith(".py"): + what += _which_copy(text, at) return self._commit_edit(p, path, text, text.replace(old, new, 1), - "replaced 1 occurrence", "", replacement=new) + what, "", replacement=new) def _commit_edit(self, p, path: str, text: str, new_text: str, what: str, gone: str, replacement: Optional[str] = None) -> ResultEnvelope: diff --git a/sage/gateway/tests/test_memory_edit_names_the_copy.py b/sage/gateway/tests/test_memory_edit_names_the_copy.py new file mode 100644 index 000000000..47865c5eb --- /dev/null +++ b/sage/gateway/tests/test_memory_edit_names_the_copy.py @@ -0,0 +1,80 @@ +"""A text-mode memory_edit says which line it changed, and which copy when a def is pasted twice. + +cbp-being, 2026-11-16 19:02Z: old='da1 = dz2 @ W2.T' matched only in the second of two pasted +`def mlp_xor` blocks (line 313), because the first copy's line 134 already held the new text. The +receipt said "replaced 1 occurrence"; the run crashed at line 134 as before.""" +from sage.gateway.being_gate_client import BeingIntent +from sage.gateway.tests.test_being_self import _ALLOW, _disp + +V1 = ("def mlp(X):\n" + " da1 = W2.T @ dz2\n" + " return da1\n" + "\n" + "if __name__ == '__main__':\n" + " mlp(1)\n") +V2 = ("def mlp(X):\n" + " da1 = dz2 @ W2.T\n" + " return da1\n") + + +def _file(name, body): + d, root = _disp() + (root / "scratch").mkdir(exist_ok=True) + f = root / "scratch" / name + f.write_text(body) + return d, f + + +def _edit(d, name, **args): + return d(BeingIntent("memory_edit", {"path": f"scratch/{name}", **args}), _ALLOW) + + +def test_text_mode_names_the_line_and_the_copy(): + d, f = _file("x.py", V1 + "\n" + V2) + env = _edit(d, "x.py", old="da1 = dz2 @ W2.T", new="da1 = W2.T @ dz2") + assert env.ok, env.error + assert "replaced 1 occurrence, on line 9, inside 'mlp' at line 8" in env.result, env.result + assert "defines mlp 2 times (lines 1, 8)" in env.result, env.result + assert "below the `if __name__ == \"__main__\":` at line 5" in env.result, env.result + # reflect sees the first RECORD_RESULT_CHARS of a result; the location must sit inside that + from sage.gateway.heartbeat import RECORD_RESULT_CHARS + assert "line 8" in env.result[:RECORD_RESULT_CHARS], env.result[:RECORD_RESULT_CHARS] + + +def test_a_single_def_gets_the_line_and_no_copy_note(): + d, f = _file("y.py", V2) + env = _edit(d, "y.py", old="da1 = dz2 @ W2.T", new="da1 = W2.T @ dz2") + assert env.ok, env.error + assert "replaced 1 occurrence, on line 2;" in env.result, env.result + assert "times (lines" not in env.result + + +def test_two_classes_with_init_are_not_copies(): + body = ("class A:\n def __init__(self):\n self.x = 1\n\n" + "class B:\n def __init__(self):\n self.y = 2\n") + d, f = _file("z.py", body) + env = _edit(d, "z.py", old="self.y = 2", new="self.y = 3") + assert env.ok, env.error + assert "times (lines" not in env.result, env.result + + +def test_no_guard_note_when_the_changed_copy_is_above_the_guard(): + d, f = _file("g.py", V2 + "\n" + V1) # copies at lines 1 and 5, guard at line 9 + env = _edit(d, "g.py", old="da1 = dz2 @ W2.T", new="da1 = W2.T @ dz2") + assert env.ok, env.error + assert "inside 'mlp' at line 1" in env.result and "__main__" not in env.result, env.result + + +def test_ranged_edit_names_the_copy_too(): + d, f = _file("r.py", V1 + "\n" + V2) + env = _edit(d, "r.py", old=" da1 = dz2 @ W2.T", new=" da1 = W2.T @ dz2", + start_line=9, end_line=9) + assert env.ok, env.error + assert "replaced lines 9-9 (1 lines), inside 'mlp' at line 8" in env.result, env.result + + +def test_a_markdown_file_gets_no_copy_note(): + d, f = _file("n.md", "def a():\n x\ndef a():\n y\n") + env = _edit(d, "n.md", old=" y", new=" z") + assert env.ok, env.error + assert "on line 4" in env.result and "times (lines" not in env.result, env.result From e1f2a689b2f189dc12f2c32d9023d871f9bd499b Mon Sep 17 00:00:00 2001 From: Dennis Palatov Date: Thu, 19 Nov 2026 13:05:42 -0800 Subject: [PATCH 2/2] memory_edit copy note: negatives after a duplicate def; the in-range path names the copy too NOVA's #744 review asked for a negative showing the backward indentation walk never attributes code after a duplicate definition to the preceding def. Three fixtures: an indented line in a top-level if block, a top-level statement, and an indented continuation line of a top-level call, all right after the second copy. None names a copy. Main's in-range path (old is part of start_line..end_line, once) now appends the same copy note as the whole-range and text-mode paths. Co-Authored-By: Claude Opus 5.5 --- sage/gateway/reference_f1a.py | 2 + .../tests/test_memory_edit_names_the_copy.py | 40 +++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/sage/gateway/reference_f1a.py b/sage/gateway/reference_f1a.py index af4219af5..00dd20f4f 100644 --- a/sage/gateway/reference_f1a.py +++ b/sage/gateway/reference_f1a.py @@ -2211,6 +2211,8 @@ def _do_memory_edit(self, intent: BeingIntent) -> ResultEnvelope: + "".join(lines[s1:])) what = (f"replaced 1 occurrence inside lines {s0}-{s1} (your old was part of the " f"range, and appears there once)") + if str(p).endswith(".py"): + what += _which_copy(text, s0 + removed[:removed.find(old)].count("\n")) return self._commit_edit(p, path, text, new_text, what, "", replacement=new) if old and inner > 1: where = f"line {s0}" if s0 == s1 else f"lines {s0}-{s1}" diff --git a/sage/gateway/tests/test_memory_edit_names_the_copy.py b/sage/gateway/tests/test_memory_edit_names_the_copy.py index 47865c5eb..66e747bda 100644 --- a/sage/gateway/tests/test_memory_edit_names_the_copy.py +++ b/sage/gateway/tests/test_memory_edit_names_the_copy.py @@ -73,6 +73,46 @@ def test_ranged_edit_names_the_copy_too(): assert "replaced lines 9-9 (1 lines), inside 'mlp' at line 8" in env.result, env.result +# NOVA's negative (#744 review): code right after the second copy, at top level or in a top-level +# block, is in neither copy. The backward walk must stop at that block's own header and name no def. +AFTER = V1 + "\n" + V2 + ("\n" + "if True:\n" # line 12 + " da2 = dz2 @ W1.T\n" # line 13: nested block after the copy + "da3 = dz2 @ W0.T\n" # line 14: top-level statement + "y = f(\n" # line 15 + " dz2 @ W9.T,\n" # line 16: continuation of a top-level call + ")\n") + + +def test_a_nested_block_after_a_copy_is_in_no_copy(): + d, f = _file("a.py", AFTER) + env = _edit(d, "a.py", old="da2 = dz2 @ W1.T", new="da2 = W1.T @ dz2") + assert env.ok, env.error + assert "on line 13" in env.result and "inside 'mlp'" not in env.result, env.result + + +def test_a_top_level_statement_after_a_copy_is_in_no_copy(): + d, f = _file("b.py", AFTER) + env = _edit(d, "b.py", old="da3 = dz2 @ W0.T", new="da3 = W0.T @ dz2") + assert env.ok, env.error + assert "on line 14" in env.result and "inside 'mlp'" not in env.result, env.result + + +def test_a_continuation_line_of_a_top_level_call_is_in_no_copy(): + d, f = _file("c.py", AFTER) + env = _edit(d, "c.py", old=" dz2 @ W9.T,", new=" W9.T @ dz2,", start_line=16, end_line=16) + assert env.ok, env.error + assert "replaced lines 16-16" in env.result and "inside 'mlp'" not in env.result, env.result + + +def test_old_inside_a_range_names_the_copy_too(): + # main's "old is part of the range" path (one occurrence inside start_line..end_line) + d, f = _file("i.py", V1 + "\n" + V2) + env = _edit(d, "i.py", old="dz2 @ W2.T", new="W2.T @ dz2", start_line=8, end_line=10) + assert env.ok, env.error + assert "inside lines 8-10" in env.result and "inside 'mlp' at line 8" in env.result, env.result + + def test_a_markdown_file_gets_no_copy_note(): d, f = _file("n.md", "def a():\n x\ndef a():\n y\n") env = _edit(d, "n.md", old=" y", new=" z")