Skip to content

Commit 4ab1349

Browse files
fix(install): preserve TOML multiline strings
Track TOML lexical state before recognizing candidate MCP table headers. This prevents owned-looking text inside multiline values from truncating unrelated config while retaining byte-preserving subtree repair. (cherry picked from commit 77f9ab1)
1 parent 76115d3 commit 4ab1349

2 files changed

Lines changed: 201 additions & 1 deletion

File tree

‎packages/studyloop/src/studyloop/installers.py‎

Lines changed: 74 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -433,6 +433,78 @@ def _toml_statement_end(lines: list[str], start: int, stop: int) -> int:
433433
return start + 1
434434

435435

436+
def _toml_normal_line_indexes(lines: list[str]) -> set[int]:
437+
"""Return physical lines that begin outside TOML strings and comments."""
438+
normal_lines: set[int] = set()
439+
state = "normal"
440+
441+
for line_index, line in enumerate(lines):
442+
if state == "normal":
443+
normal_lines.add(line_index)
444+
445+
index = 0
446+
while index < len(line):
447+
char = line[index]
448+
449+
if state == "comment":
450+
if char in "\r\n":
451+
state = "normal"
452+
index += 1
453+
continue
454+
455+
if state == "basic":
456+
if char == "\\":
457+
index += 2
458+
elif char == '"' or char in "\r\n":
459+
state = "normal"
460+
index += 1
461+
else:
462+
index += 1
463+
continue
464+
465+
if state == "literal":
466+
if char == "'" or char in "\r\n":
467+
state = "normal"
468+
index += 1
469+
continue
470+
471+
if state in {"multiline-basic", "multiline-literal"}:
472+
delimiter = '"' if state == "multiline-basic" else "'"
473+
if state == "multiline-basic" and char == "\\":
474+
index += 2
475+
continue
476+
if char == delimiter:
477+
run_end = index
478+
while run_end < len(line) and line[run_end] == delimiter:
479+
run_end += 1
480+
if run_end - index >= 3:
481+
state = "normal"
482+
index = run_end
483+
continue
484+
index += 1
485+
continue
486+
487+
if char == "#":
488+
state = "comment"
489+
index += 1
490+
elif line.startswith('"""', index):
491+
state = "multiline-basic"
492+
index += 3
493+
elif char == '"':
494+
state = "basic"
495+
index += 1
496+
elif line.startswith("'''", index):
497+
state = "multiline-literal"
498+
index += 3
499+
elif char == "'":
500+
state = "literal"
501+
index += 1
502+
else:
503+
index += 1
504+
505+
return normal_lines
506+
507+
436508
def _remove_owned_toml(raw: str, names: set[str]) -> str:
437509
"""Remove owned MCP table headers and assignments while retaining other bytes."""
438510
lines = raw.splitlines(keepends=True)
@@ -442,10 +514,11 @@ def _remove_owned_toml(raw: str, names: set[str]) -> str:
442514
starts.append(offset)
443515
offset += len(line)
444516

517+
normal_lines = _toml_normal_line_indexes(lines)
445518
headers = [
446519
(index, path)
447520
for index, line in enumerate(lines)
448-
if (path := _toml_table_path(line)) is not None
521+
if index in normal_lines and (path := _toml_table_path(line)) is not None
449522
]
450523
removals: list[tuple[int, int]] = []
451524

‎packages/studyloop/tests/test_mcp_registration.py‎

Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -290,6 +290,133 @@ def test_codex_repair_replaces_owned_values_declared_in_parent_table(
290290
assert path.read_bytes() == first_bytes
291291

292292

293+
def test_codex_repair_preserves_exact_multiline_notes_data_loss_case(
294+
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
295+
) -> None:
296+
home = tmp_path / "home"
297+
home.mkdir()
298+
monkeypatch.setattr(installers, "_HOME", home)
299+
path = home / ".codex/config.toml"
300+
path.parent.mkdir(parents=True)
301+
unrelated_before = '[ui]\nnotes = """\n[mcp_servers.session-db]\ncommand = "fictional"\n"""\n'
302+
owned = '[mcp_servers.session-db]\ncommand = "wrong"\nargs = ["--bad"]\n'
303+
unrelated_after = '[mcp_servers.unrelated]\ncommand = "other"\n'
304+
original = unrelated_before + owned + unrelated_after
305+
original_notes = tomllib.loads(original)["ui"]["notes"]
306+
path.write_text(original, encoding="utf-8")
307+
308+
assert installers.register_mcp_servers(["codex"]) == {"codex": 1}
309+
310+
repaired_bytes = path.read_bytes()
311+
repaired = repaired_bytes.decode()
312+
parsed = tomllib.loads(repaired)
313+
assert parsed["ui"]["notes"] == original_notes
314+
assert repaired_bytes.startswith((unrelated_before + unrelated_after).encode())
315+
assert parsed["mcp_servers"]["session-db"] == {
316+
"command": "session-db-mcp",
317+
"args": [],
318+
}
319+
assert parsed["mcp_servers"]["studyloop"] == {
320+
"command": "studyloop-mcp",
321+
"args": [],
322+
}
323+
assert installers.register_mcp_servers(["codex"]) == {"codex": 0}
324+
assert path.read_bytes() == repaired_bytes
325+
326+
327+
@pytest.mark.parametrize(
328+
("newline", "unrelated_before"),
329+
(
330+
(
331+
"\n",
332+
'[ui]\n# keep outside comment\nnotes = """escaped quote: \\" still open\n'
333+
"escaped backslash: \\\\\n# string comment text\n"
334+
'[mcp_servers.studyloop]\ncommand = "fictional"\n"""\n',
335+
),
336+
(
337+
"\r\n",
338+
"[ui]\r\n# keep outside comment\r\nnotes = '''literal text\r\n"
339+
"# string comment text\r\n[mcp_servers.session-db]\r\n"
340+
"command = 'fictional'\r\n'''\r\n",
341+
),
342+
),
343+
)
344+
def test_codex_repair_preserves_table_text_in_multiline_string_lexical_states(
345+
tmp_path: Path,
346+
monkeypatch: pytest.MonkeyPatch,
347+
newline: str,
348+
unrelated_before: str,
349+
) -> None:
350+
home = tmp_path / "home"
351+
home.mkdir()
352+
monkeypatch.setattr(installers, "_HOME", home)
353+
path = home / ".codex/config.toml"
354+
path.parent.mkdir(parents=True)
355+
owned = f'[mcp_servers.studyloop]{newline}command = "wrong"{newline}args = ["--bad"]{newline}'
356+
unrelated_after = (
357+
f"[mcp_servers.unrelated]{newline}"
358+
f'command = "other"{newline}'
359+
f"# keep trailing comment{newline}"
360+
)
361+
original = unrelated_before + owned + unrelated_after
362+
original_notes = tomllib.loads(original)["ui"]["notes"]
363+
path.write_bytes(original.encode())
364+
365+
assert installers.register_mcp_servers(["codex"]) == {"codex": 1}
366+
367+
repaired_bytes = path.read_bytes()
368+
repaired = repaired_bytes.decode()
369+
parsed = tomllib.loads(repaired)
370+
assert parsed["ui"]["notes"] == original_notes
371+
assert repaired_bytes.startswith((unrelated_before + unrelated_after).encode())
372+
assert b"# keep outside comment" in repaired_bytes
373+
assert b"# keep trailing comment" in repaired_bytes
374+
if newline == "\r\n":
375+
assert b"\n" not in repaired_bytes.replace(b"\r\n", b"")
376+
assert installers.register_mcp_servers(["codex"]) == {"codex": 0}
377+
assert path.read_bytes() == repaired_bytes
378+
379+
380+
def test_codex_repair_removes_owned_multiline_value_without_false_header_boundaries(
381+
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
382+
) -> None:
383+
home = tmp_path / "home"
384+
home.mkdir()
385+
monkeypatch.setattr(installers, "_HOME", home)
386+
path = home / ".codex/config.toml"
387+
path.parent.mkdir(parents=True)
388+
owned = (
389+
'[mcp_servers.session-db]\ncommand = """wrong \\" still open\n'
390+
'[mcp_servers.studyloop]\ncommand = "fictional"\n"""\nargs = ["--bad"]\n'
391+
'[mcp_servers.session-db.env]\nTOKEN = "remove"\n'
392+
)
393+
unrelated = (
394+
"[ui]\nnotes = '''[mcp_servers.session-db]\n"
395+
"command = 'keep as text'\n'''\n# keep final comment\n"
396+
)
397+
original_notes = tomllib.loads(owned + unrelated)["ui"]["notes"]
398+
path.write_text(owned + unrelated, encoding="utf-8")
399+
400+
assert installers.register_mcp_servers(["codex"]) == {"codex": 1}
401+
402+
repaired_bytes = path.read_bytes()
403+
repaired = repaired_bytes.decode()
404+
parsed = tomllib.loads(repaired)
405+
assert repaired_bytes.startswith(unrelated.encode())
406+
assert parsed["ui"]["notes"] == original_notes
407+
assert "TOKEN" not in repaired
408+
assert parsed["mcp_servers"]["session-db"] == {
409+
"command": "session-db-mcp",
410+
"args": [],
411+
}
412+
assert parsed["mcp_servers"]["studyloop"] == {
413+
"command": "studyloop-mcp",
414+
"args": [],
415+
}
416+
assert installers.register_mcp_servers(["codex"]) == {"codex": 0}
417+
assert path.read_bytes() == repaired_bytes
418+
419+
293420
@pytest.mark.parametrize("owned_value", ('"wrong"', '["wrong"]', "null", "42", "false"))
294421
def test_json_repair_replaces_every_valid_owned_value_shape(
295422
tmp_path: Path,

0 commit comments

Comments
 (0)