The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(read-file): preserve notebook paths in output recovery hints
funky-xamarin88c2adb32f0b
diff --git a/tests/tools/test_notebook_recovery_path.py b/tests/tools/test_notebook_recovery_path.pynew file mode 100644index 00000000000..3af2c249022--- /dev/null+++ b/tests/tools/test_notebook_recovery_path.py@@ -0,0 +1,35 @@+"""Recovery hints must name the user-visible notebook, not its byte-transport copy."""+import json+from pathlib import Path+import shlex++import pytest++from tools.read_extract import extract_document_bytes, extract_document_text++[email protected]('reader', ['bytes', 'text', 'read_file'])+def test_notebook_recovery_hint_opens_original_file(tmp_path, reader):+ path = tmp_path / "training team's notebook.ipynb"+ output = 'epoch progress\n' * 2000+ notebook = {'nbformat': 4, 'nbformat_minor': 5, 'metadata': {}, 'cells': [{+ 'cell_type': 'code', 'id': 'train', 'execution_count': 1, 'metadata': {},+ 'source': ['print(log)'], 'outputs': [{+ 'output_type': 'stream', 'name': 'stdout', 'text': output}]}]}+ path.write_text(json.dumps(notebook), encoding='utf-8')+ if reader == 'bytes':+ text = extract_document_bytes(path.read_bytes(), str(path))+ elif reader == 'text':+ text = extract_document_text(str(path))+ else:+ # Real public entry point, including configured local byte transport.+ from tools.file_tools import read_file_tool+ result = json.loads(read_file_tool(str(path), task_id='notebook-hint-recovery'))+ assert result.get('extracted_document'), result+ text = result['content']+ hint = next(line for line in text.splitlines() if 'full output: jq' in line)+ command = hint.split('full output: ', 1)[1].removesuffix(']')+ argv = shlex.split(command)+ assert argv == ['jq', '-r', '.cells[0].outputs', str(path)]+ recovered = json.loads(Path(argv[-1]).read_text(encoding='utf-8'))+ assert recovered['cells'][0]['outputs'][0]['text'] == outputdiff --git a/tests/tools/test_read_extract.py b/tests/tools/test_read_extract.pyindex eec57f81a81..b100b90318c 100644--- a/tests/tools/test_read_extract.py+++ b/tests/tools/test_read_extract.py@@ -13,6 +13,7 @@ Run with: python -m pytest tests/tools/test_read_extract.py -vimport base64import jsonimport os+import shleximport tempfileimport unittestimport zipfile@@ -443,7 +444,8 @@ class TestNotebookExtraction(unittest.TestCase):])text = extract_document_text(p)self.assertIn("output chars truncated", text)- self.assertIn("— full output: jq -r '.cells[1].outputs' nb_big.ipynb]", text)+ command = text.split("full output: ", 1)[1].splitlines()[0].removesuffix("]")+ self.assertEqual(shlex.split(command), ["jq", "-r", ".cells[1].outputs", p])self.assertLess(len(text), _MAX_OUTPUT_CHARS + 2000)def test_oversized_outputs_truncated_v3_jq_hint(self):@@ -459,10 +461,8 @@ class TestNotebookExtraction(unittest.TestCase):json.dump(nb, fh)text = extract_document_text(p)self.assertIn("output chars truncated", text)- self.assertIn(- "— full output: jq -r '.worksheets[0].cells[1].outputs' nb_v3_big.ipynb]",- text,- )+ command = text.split("full output: ", 1)[1].splitlines()[0].removesuffix("]")+ self.assertEqual(shlex.split(command), ["jq", "-r", ".worksheets[0].cells[1].outputs", p])def test_legacy_v3_pyout_flat_fields(self):p = os.path.join(self.tmp, "nb_v3.ipynb")diff --git a/tools/read_extract.py b/tools/read_extract.pyindex 4fe9fbfe716..92c0f1eb907 100644--- a/tools/read_extract.py+++ b/tools/read_extract.py@@ -13,6 +13,7 @@ import jsonimport osimport posixpathimport re+import shleximport shutilimport subprocessimport tempfile@@ -123,6 +124,8 @@ def extract_document_bytes(data: bytes, path: str) -> str:if ext not in EXTRACTABLE_EXTENSIONS:raise ExtractionError(f"Unsupported document type: {path!r}")with _temp_copy(data, ext) as temp_path: # the stdlib extractors are path-oriented+ if ext == ".ipynb":+ return _extract_notebook(temp_path, display_path=path)return _STDLIB_EXTRACTORS[ext](temp_path)@@ -395,7 +398,7 @@ def _notebook_outputs(cell: dict, jq_pointer: str = "", filename: str = "") -> sjoined = "\n".join(filter(None, map(_notebook_output_text, outputs)))if len(joined) <= _MAX_OUTPUT_CHARS:return joined- hint = f" — full output: jq -r '{jq_pointer}' {filename}" if jq_pointer and filename else ""+ hint = f" — full output: jq -r '{jq_pointer}' {shlex.quote(filename)}" if jq_pointer and filename else ""omitted = len(joined) - _MAX_OUTPUT_CHARSreturn joined[:_MAX_OUTPUT_CHARS] + f"\n… [{omitted:,} output chars truncated{hint}]"@@ -403,7 +406,7 @@ def _notebook_outputs(cell: dict, jq_pointer: str = "", filename: str = "") -> s_CELL_LABELS = {"markdown": "Markdown", "code": "Code", "raw": "Raw"}-def _extract_notebook(path: str) -> str:+def _extract_notebook(path: str, *, display_path: Optional[str] = None) -> str:try:with open(path, encoding="utf-8", errors="replace") as fh:nb = json.load(fh)@@ -421,7 +424,9 @@ def _extract_notebook(path: str) -> str:for ci, cell in enumerate(ws.get("cells", []))]if not cells:raise ExtractionError("Notebook contains no cells")- nb_name = os.path.basename(path)+ # Backend bytes are parsed through a disposable host copy; recovery commands+ # must instead name the original notebook in the user's filesystem.+ nb_name = display_path if display_path is not None else pathcounts = dict.fromkeys(_CELL_LABELS, 0)out: list[str] = []for jq_pointer, cell in cells: