backend: let a model ask for a line break, and read the 参考文献 list back

The paper model gained two things while the MCP layer was not looking, and
both were invisible from a tool call.

`paper_sentence.line_break_before` — the flag a paragraph needs so a formula,
a list of items or an author line can start a line of its own — was not in
`SentenceSpec`, and `sentence_inputs` dropped it on the floor: a model could
write the field, watch the call succeed, and get prose back. It is now part of
every write path (`paragraph_write`, `paper_write`, `sentence_add`,
`sentence_update`) and of every read path (`sentence_row` reports it, so a
model can see the lines before moving one). Two bugs fell out of doing it
properly:

* `paragraph_move` rebuilt its sentences without the flag, so moving a
  paragraph that carried a formula turned it into prose. It also passed the
  *source* sorts through, which interleaved the moved sentences with the
  target's own — the merged paragraph read in an order neither writer wrote.
  Both are fixed; the tool now appends, as its own description promised.
* `document_text` printed a formula run into the sentence before it. The paper
  view renders `$$…$$` as a block, so the seam rules are now the same in both
  places, with a comment on each side naming the other.

`PaperDocumentRead.references` and `reference_style` — the per-work 参考文献
list the backend now assembles and formats — were reachable over REST but not
over MCP: `paper_document(format="json")` returned citations and nothing to
point them at, even though docs/MCP.md already described the list. The json
form now carries the entries (index, reference_id, text, missing, citations)
and the style name, so a model quotes the bibliography instead of assembling a
second one out of the same fields.

smoke_mcp.py grows from 76 checks to 99 over two new steps — the line-break
step pins the display-formula rule, the marker toggle and the moving case; the
bibliography step cites one work from two sentences and checks that the text,
the entry and both markers agree on one number.
This commit is contained in:
2026-09-23 11:49:39 +08:00
parent 960450f744
commit 9f2bbe50eb
11 changed files with 483 additions and 34 deletions
+274 -7
View File
@@ -152,7 +152,9 @@ async def run(url: str | None = None, token: str | None = None) -> int:
async def _run(url: str | None = None, token: str | None = None) -> int:
template_id, outline = pick_template()
check("a template with fields exists", len(outline) >= 3, f"got {len(outline)}")
# Four headings, because the line-break and bibliography steps below move one
# paragraph onto a fourth; with fewer, they would have nowhere to write.
check("a template with four fields exists", len(outline) >= 4, f"got {len(outline)}")
first = outline[0]["name"]
second = outline[1]["name"]
@@ -592,12 +594,277 @@ async def _run(url: str | None = None, token: str | None = None) -> int:
for row in paragraph["sentences"]
),
)
check(
"it names the citation style the entries are printed in",
structured["reference_style"] == "springer",
str(structured.get("reference_style")),
)
# Step 13 rewrote every paragraph, so the citation step 9 wrote is gone
# and this paper cites nothing: the 参考文献 list is reported as empty
# rather than left out, because "this cites nothing yet" is an answer.
check(
"and reports the 参考文献 list as empty when nothing is cited",
structured["references"] == [],
json.dumps(structured["references"], ensure_ascii=False),
)
print("\n15. search across papers")
found = await call(session, "sentence_search", keyword="正文写在标题下面", paper_id=paper["id"])
check("the search finds what was written", found["total"] >= 1, str(found["total"]))
print("\n16. move a paragraph, then clear the one it moved onto")
print("\n16. the writer asks for a line break")
# A paragraph is its sentences run together, so a formula, a list of
# items or an author line has to say where the lines are. A *display*
# formula does not have to: the paper view sets one on a line of its own
# by definition, and the text a tool hands back has to agree with the
# page the writer is looking at, or the two disagree about the lines.
prose = outline[2]
await call(
session,
"paper_write",
paper_id=paper["id"],
paragraphs=[
{
"heading": prose["name"],
"sentences": [
"本段说明公式的来历。",
{"content": "$$ E = mc^2 $$"},
{"content": "其中 c 为光速。", "line_break_before": True},
],
}
],
)
written = await call(
session, "paragraph_get", paper_id=paper["id"], heading=prose["name"]
)
check(
"the flag is stored per sentence",
[row["line_break_before"] for row in written["sentences"]]
== [False, False, True],
json.dumps(written["sentences"], ensure_ascii=False),
)
check(
"a formula takes its own line unasked, and a flagged sentence too",
written["text"] == "本段说明公式的来历。\n$$ E = mc^2 $$\n其中 c 为光速。",
repr(written["text"]),
)
check(
"and the flag replaces the separator rather than joining it",
"\n " not in written["text"],
repr(written["text"]),
)
whole = await call(session, "paper_document", paper_id=paper["id"])
check(
"the whole document prints it the same way",
"本段说明公式的来历。\n$$ E = mc^2 $$\n其中 c 为光速。" in whole["text"],
repr(whole["text"][-260:]),
)
added = await call(
session,
"sentence_add",
paper_id=paper["id"],
heading=prose["name"],
content="另一条列举。",
line_break_before=True,
)
check(
"sentence_add can ask for one as well",
added["sentence"]["line_break_before"] is True,
json.dumps(added["sentence"], ensure_ascii=False),
)
# Toggled on the sentence that follows the prose, not the one that
# follows the formula: the formula is a block, so the sentence after it
# starts a line whatever its flag says, and a check written on that one
# would pass for the wrong reason.
joined = added["sentence"]["id"]
off = await call(
session,
"sentence_update",
paper_id=paper["id"],
sentence_id=joined,
line_break_before=False,
)
check(
"the break can be taken off again",
off["sentence"]["line_break_before"] is False,
json.dumps(off, ensure_ascii=False),
)
rejoined = await call(
session, "paragraph_get", paper_id=paper["id"], heading=prose["name"]
)
check(
"and the two sentences run on as one line",
"\n另一条列举。" not in rejoined["text"]
and "其中 c 为光速。另一条列举。" in rejoined["text"],
repr(rejoined["text"]),
)
check(
"while the line after the formula stays broken, flag or no flag",
"\n其中 c 为光速。" in rejoined["text"],
repr(rejoined["text"]),
)
await call(
session,
"sentence_update",
paper_id=paper["id"],
sentence_id=joined,
line_break_before=True,
)
relined = await call(
session, "paragraph_get", paper_id=paper["id"], heading=prose["name"]
)
check(
"asking for it again puts the line back",
"\n另一条列举。" in relined["text"],
repr(relined["text"]),
)
moved_texts = [row["content"] for row in written["sentences"]] + [
added["sentence"]["content"]
]
await call(
session,
"paragraph_move",
paper_id=paper["id"],
heading=prose["name"],
target_heading=outline[3]["name"],
)
landed = await call(
session, "paragraph_get", paper_id=paper["id"], heading=outline[3]["name"]
)
# Matched by content rather than by id: a move rewrites the rows, so the
# ids the source paragraph had do not survive it. Citations are rebuilt
# the same way, which is why they come back attached to the new rows.
flag_of = {row["content"]: row["line_break_before"] for row in landed["sentences"]}
check(
"a paragraph carries its line breaks when it moves",
[flag_of.get(text) for text in moved_texts] == [False, False, True, True],
f"moved={moved_texts} reads back as "
f"{[flag_of.get(text) for text in moved_texts]} out of "
f"{json.dumps(landed['sentences'], ensure_ascii=False)}",
)
check(
"and it lands after the target's own sentences, as the tool says",
[row["content"] for row in landed["sentences"]][-len(moved_texts):]
== moved_texts,
json.dumps([row["content"] for row in landed["sentences"]], ensure_ascii=False),
)
print("\n17. the 参考文献 list is printed, not assembled by the client")
# Step 10 deleted the reference this run made, so the bibliography step
# brings its own work to cite. It is cited twice on purpose: one work,
# one entry, one number in both places is the rule being checked.
bibliography = await call(
session,
"reference_create",
reference={
"type": "journal-article",
"title": "SMOKE MCP 参考文献表",
"container_title": "Journal of Smoke Tests",
"publication_year": 2024,
"volume": "12",
"issue": "3",
"pages": "45-67",
"doi": "10.1000/smoke.mcp.002",
"authors": [
{"name": "Smith, John", "family_name": "Smith", "given_name": "John"}
],
},
)
cited_reference = bibliography["id"]
_created_references.append(cited_reference)
first = await call(
session,
"sentence_add",
paper_id=paper["id"],
heading=outline[3]["name"],
content="A cited sentence.",
citations=[{"quote": "引用的原话", "reference_id": cited_reference}],
)
await call(
session,
"sentence_add",
paper_id=paper["id"],
heading=outline[3]["name"],
content="A second sentence, same work.",
line_break_before=True,
citations=[{"quote": "再次引用", "reference_id": cited_reference}],
)
document = await call(
session, "paper_document", paper_id=paper["id"], format="json"
)
check(
"the style the entries are written in is named",
document["reference_style"] == "springer",
str(document.get("reference_style")),
)
check(
"one row per place in the text",
len(document["citations"]) == 2,
json.dumps(document["citations"], ensure_ascii=False),
)
check(
"but one entry for the work, however often it is cited",
len(document["references"]) == 1,
json.dumps(document["references"], ensure_ascii=False),
)
entry = document["references"][0]
check(
"the entry is a bibliography line rather than the quoted words",
entry["text"].startswith("Smith, J.: SMOKE MCP 参考文献表")
and "Journal of Smoke Tests 12(3), 45–67 (2024)" in entry["text"]
and entry["text"].endswith("https://doi.org/10.1000/smoke.mcp.002"),
entry["text"],
)
check(
"a complete entry is reported as complete",
entry["missing"] == [],
str(entry["missing"]),
)
check(
"both places wear the one number the entry has",
{row["index"] for row in document["citations"]} == {entry["index"]},
json.dumps(document["citations"], ensure_ascii=False),
)
check(
"and the entry names both of them",
len(entry["citations"]) == 2
and first["sentence"]["id"]
in {row["sentence_id"] for row in document["citations"]},
json.dumps(entry, ensure_ascii=False),
)
as_text = await call(session, "paper_document", paper_id=paper["id"])
check(
"the text form carries the 参考文献 block with that entry",
f"参考文献\n[{entry['index']}] {entry['text']}" in as_text["text"],
repr(as_text["text"][-300:]),
)
check(
"and marks both places with that same number",
f"A cited sentence.[{entry['index']}]" in as_text["text"]
and f"A second sentence, same work.[{entry['index']}]" in as_text["text"],
repr(as_text["text"][-700:]),
)
check(
"and the bibliography lists the work exactly once",
len(
[
line
for line in as_text["text"].splitlines()
if line.startswith(f"[{entry['index']}] ")
]
)
== 1,
repr(as_text["text"][-300:]),
)
print("\n18. move a paragraph, then clear the one it moved onto")
home = outline[0]
target = outline[1]
relocation = await call(
@@ -629,7 +896,7 @@ async def _run(url: str | None = None, token: str | None = None) -> int:
after_clear = await call(session, "paragraph_get", paper_id=paper["id"], position=target["position"])
check("and the paragraph is empty", after_clear["sentences"] == [], json.dumps(after_clear, ensure_ascii=False))
print("\n17. the field library round-trips")
print("\n19. the field library round-trips")
field = await call(session, "field_create", name="SMOKE MCP 字段", level=2, font_size=9.5)
check("created with its typography", field["level"] == 2 and field["font_size"] == 9.5, json.dumps(field, ensure_ascii=False))
renamed = await call(session, "field_update", field_id=field["id"], name="SMOKE MCP 字段(改)")
@@ -638,7 +905,7 @@ async def _run(url: str | None = None, token: str | None = None) -> int:
check("deleted while no template places it", dropped["deleted"] == 1, json.dumps(dropped, ensure_ascii=False))
check("and it is reported as found, not missing", dropped["missing"] == [], json.dumps(dropped, ensure_ascii=False))
print("\n18. switch the template and keep the content")
print("\n20. switch the template and keep the content")
spare = await call(
session,
"template_create",
@@ -682,15 +949,15 @@ async def _run(url: str | None = None, token: str | None = None) -> int:
json.dumps(switched_document, ensure_ascii=False)[:400],
)
print("\n19. a template in use cannot be deleted")
print("\n21. a template in use cannot be deleted")
message = await expect_error(session, "template_delete", template_ids=spare["id"])
check("the refusal names the blocker", "SMOKE MCP 模板" in message, message)
print("\n20. deleting a paper needs an explicit confirmation")
print("\n22. deleting a paper needs an explicit confirmation")
message = await expect_error(session, "paper_delete", paper_ids=paper["id"])
check("the refusal explains itself", "confirm=true" in message, message)
print("\n21. delete the paper and the template")
print("\n23. delete the paper and the template")
deleted = await call(session, "paper_delete", paper_ids=paper["id"], confirm=True)
check("deleted", deleted["deleted"] == 1, json.dumps(deleted, ensure_ascii=False))
_created_papers.remove(paper["id"])