Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 55 additions & 2 deletions sage/gateway/reference_f1a.py
Original file line number Diff line number Diff line change
Expand Up @@ -592,6 +592,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()
Expand Down Expand Up @@ -2167,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}"
Expand All @@ -2187,7 +2233,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
Expand Down Expand Up @@ -2339,8 +2388,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 _earlier_edit(self, path: str, new: str) -> Optional[str]:
"""When the being's own landed memory_edit of `path` carried `new` (stripped, as all or part
Expand Down
120 changes: 120 additions & 0 deletions sage/gateway/tests/test_memory_edit_names_the_copy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
"""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


# 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")
assert env.ok, env.error
assert "on line 4" in env.result and "times (lines" not in env.result, env.result
Loading