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
+19
View File
@@ -45,6 +45,16 @@ class SentenceSpec(BaseModel):
"""One sentence, optionally carrying citations."""
content: Annotated[str, Field(description="句子正文;空白会被折叠成一行")]
line_break_before: Annotated[
bool,
Field(
description=(
"这一句前面另起一行(默认 false)。正文被句子拼成一段,所以公式、"
"分条列举、作者行这类不是散文的行要在这里开口;break 会顶掉句间的空格,"
"不会多印一个空格。display 公式($$…$$ 或 \\[…\\])本来就独占一行,不必设这个"
)
),
] = False
citations: Annotated[
list[CitationSpec],
Field(description="这一段引用了哪些文献"),
@@ -59,6 +69,15 @@ class TextSpec(BaseModel):
SplitMode,
Field(description="切句方式:line 一行一句(默认)/ sentence 按句号切 / paragraph 整段一句"),
] = "line"
line_break_before: Annotated[
bool,
Field(
description=(
"这一整块从新的一行开始(默认 false);只作用于切出来的第一句,"
"因为切出来的其余几句是接着它的,不是各自另起一行"
)
),
] = False
citations: Annotated[
list[CitationSpec],
Field(description="整段共用的引用"),
+59 -4
View File
@@ -256,6 +256,10 @@ def sentence_row(sentence: Any, *, separator: str | None = None) -> dict:
"position": sentence.paper_template_filed_sort,
"sort": sentence.sort,
"content": sentence.content,
# Reported so a writer can see where the lines fall before deciding to
# move one: a paragraph read back without this flag looks like prose
# that happens to have no spaces in it.
"line_break_before": sentence.line_break_before,
"citations": [citation_row(item) for item in sentence.citations],
}
if separator is not None:
@@ -277,6 +281,21 @@ def paragraph_row(paragraph: ParagraphRead, *, preview: int = 80) -> dict:
}
#: A formula the paper view sets on a line of its own: ``$$…$$`` or ``\[…\]``.
#:
#: This is the same rule as ``hasDisplayMath`` in ``frontend/src/utils/math.ts``,
#: written twice because the view is TypeScript and this is Python. The two must
#: agree, or a tool result and the page a writer is looking at would disagree
#: about where the lines are — which is the one thing this module exists to
#: prevent. Change one, change the other.
_DISPLAY_MATH = re.compile(r"\$\$[\s\S]+?\$\$|\\\[[\s\S]+?\\\]")
def _is_display(sentence: Any) -> bool:
"""Whether this sentence is a display formula — a block, not a run of text."""
return bool(_DISPLAY_MATH.search(sentence.content))
def paragraph_text(
paragraph: ParagraphRead,
*,
@@ -289,6 +308,14 @@ def paragraph_text(
belongs at each seam, so a tool result and the paper view agree on where
the spaces go. Nothing here adds spacing of its own.
A line break is printed where the model asked for one, and around a display
formula — the paper view renders ``$$…$$`` as a block, so the lines on
either side of it are line boundaries there too. A break *replaces* the
separator rather than joining it: the new line already separates the two
sentences, and a space as well would indent the line below by one blank.
The first sentence of a paragraph is never preceded by a break, because
there is nothing above it to break from.
A marker's number comes from ``index_by_citation`` — the citation's *work*
number as the whole document assigned it, not its position in this sentence —
so what is printed in the text matches the 参考文献 list it points at. Read
@@ -296,8 +323,15 @@ def paragraph_text(
falls back to the citation's place in the sentence.
"""
parts: list[str] = []
previous_block = False
for sentence in paragraph.sentences:
parts.append(sentence.separator_before + sentence.content)
block = _is_display(sentence)
if parts and (sentence.line_break_before or block or previous_block):
parts.append("\n")
else:
parts.append(sentence.separator_before)
parts.append(sentence.content)
previous_block = block
if citations and sentence.citations:
numbers = [
str(
@@ -592,6 +626,8 @@ def sentence_inputs(items: Sequence[Any], *, default_split: str = "line") -> lis
* ``"A sentence."`` — the common case;
* ``{"content": "...", "citations": [{"quote": "...", "reference_id": 3}]}``;
* ``{"content": "$$ y = ax + b $$", "line_break_before": true}`` — a block
that starts a line of its own;
* ``{"text": "one\\ntwo", "split": "line"}`` — a block to be cut.
Every path ends in :class:`~app.schemas.paper.SentenceInput`, so the
@@ -621,15 +657,34 @@ def sentence_inputs(items: Sequence[Any], *, default_split: str = "line") -> lis
)
for citation in (item.get("citations") or [])
]
line_break = bool(item.get("line_break_before", False))
if item.get("content") is not None:
out.append(SentenceInput(content=str(item["content"]), citations=citations))
out.append(
SentenceInput(
content=str(item["content"]),
line_break_before=line_break,
citations=citations,
)
)
continue
if item.get("text") is not None:
mode = item.get("split") or default_split
for piece in split_text(str(item["text"]), mode):
out.append(SentenceInput(content=piece, citations=citations))
pieces = split_text(str(item["text"]), mode)
for offset, piece in enumerate(pieces):
# A break asked for on a *block* belongs to its first sentence:
# "this block starts a new line". The pieces after it are
# separated by whatever the split found, and flagging them too
# would turn a paragraph the writer wrapped across three lines
# into three lines of the paper.
out.append(
SentenceInput(
content=piece,
line_break_before=line_break and offset == 0,
citations=citations,
)
)
continue
fail("句子对象需要有 content 或 text 字段")
+24 -2
View File
@@ -248,7 +248,7 @@ def register(server: MCPServer) -> None:
bool, Field(description="是否带上引用标记与参考文献列表")
] = True,
) -> str:
"""读整篇论文:按模板顺序输出全文(含引用编号和参考文献)。"""
"""读整篇论文:按模板顺序输出全文(含引用编号、参考文献表与换行)。"""
with s.session() as db:
paper = s.paper_or_fail(db, paper_id)
document = paper_crud.build_document(db, paper)
@@ -270,6 +270,8 @@ def register(server: MCPServer) -> None:
for paragraph in document.paragraphs
if include_empty or paragraph.sentences
]
# One row per *place* in the text, each carrying the number of
# the work it cites — the number the marker in the text shows.
payload["citations"] = [
{
"index": item.index,
@@ -279,6 +281,24 @@ def register(server: MCPServer) -> None:
}
for item in document.citations
]
# The 参考文献 list as it prints: one entry per work, already
# formatted by the server, so a model quotes the bibliography
# rather than assembling a second one out of the same fields.
# It is reported even when it is empty, because "this paper
# cites nothing yet" is an answer.
payload["references"] = [
{
"index": entry.index,
"reference_id": entry.reference_id,
"text": entry.text,
"missing": entry.missing,
# The ids of the places that cite it; the rows
# themselves are in citations above.
"citations": [row.id for row in entry.citations],
}
for entry in document.references
]
payload["reference_style"] = document.reference_style
if document.warnings:
payload["warnings"] = document.warnings
return s.dumps(payload)
@@ -291,7 +311,8 @@ def register(server: MCPServer) -> None:
Field(
description=(
"要写的段落数组。每段用 heading(如 “1. Introduction”)或 position 指定,"
"正文放 sentences(字符串数组或带 citations 的对象数组),"
"正文放 sentences(字符串数组或带 citations 的对象数组,"
"要另起一行的公式或条目加 line_break_before: true),"
"或放 text + split 让服务端切句"
)
),
@@ -324,6 +345,7 @@ def register(server: MCPServer) -> None:
SentenceCreate(
paper_template_filed_sort=position,
content=item.content,
line_break_before=item.line_break_before,
citations=item.citations,
sort=item.sort,
),
+21 -3
View File
@@ -74,7 +74,7 @@ def register(server: MCPServer) -> None:
str | None, Field(description="段落标题,如 “2. Methods”")
] = None,
) -> str:
"""读一个段落:拼好的正文、逐句内容与 id、引用、段间分隔符。"""
"""读一个段落:拼好的正文、逐句内容与 id、引用、段间分隔符与换行。"""
with s.session() as db:
paper = s.paper_or_fail(db, paper_id)
field_sort = s.resolve_position(paper, position=position, heading=heading)
@@ -109,7 +109,13 @@ def register(server: MCPServer) -> None:
] = None,
sentences: Annotated[
list[SentenceItem] | None,
Field(description="句子数组:字符串、{content, citations} 或 {text, split}"),
Field(
description=(
"句子数组:字符串、{content, citations} 或 {text, split}。"
"要某一句另起一行(公式、分条列举、作者行),用对象形式加上 "
"line_break_before: true"
)
),
] = None,
text: Annotated[
str | None, Field(description="整段文本;与 sentences 二选一")
@@ -199,7 +205,18 @@ def register(server: MCPServer) -> None:
s.fail(f"第 {source} 段没有内容可以搬")
inputs = [
SentenceInput(content=row.content, sort=row.sort, citations=list(row.citations))
SentenceInput(
content=row.content,
# ``sort`` is deliberately left unset so that
# :func:`app.crud.paper.replace_paragraph` numbers the block
# from the *target's* current maximum. Carrying the old
# numbers over instead would interleave the two paragraphs —
# the moved sentence with ``sort=1`` would sort against the
# target's own sentence with ``sort=1`` — and the merge would
# read in an order neither writer wrote.
line_break_before=row.line_break_before,
citations=list(row.citations),
)
for row in rows
]
paper_crud.replace_paragraph(
@@ -258,6 +275,7 @@ def _write(
SentenceCreate(
paper_template_filed_sort=field_sort,
content=item.content,
line_break_before=item.line_break_before,
citations=item.citations,
sort=item.sort,
),
+23 -2
View File
@@ -85,6 +85,15 @@ def register(server: MCPServer) -> None:
citations: Annotated[
list[CitationSpec] | None, Field(description="这句引用了哪些文献")
] = None,
line_break_before: Annotated[
bool,
Field(
description=(
"这一句前面另起一行(默认 false):公式、分条列举、作者行用得上。"
"break 会顶掉句间的空格"
)
),
] = False,
sort: Annotated[
int | None, Field(description="段内位置;不传则排在段尾")
] = None,
@@ -99,6 +108,7 @@ def register(server: MCPServer) -> None:
SentenceCreate(
paper_template_filed_sort=field_sort,
content=content,
line_break_before=line_break_before,
citations=_citations(citations or []),
sort=sort,
),
@@ -123,13 +133,23 @@ def register(server: MCPServer) -> None:
sort: Annotated[
int | None, Field(description="段内排序值;不传则不动")
] = None,
line_break_before: Annotated[
bool | None,
Field(description="这一句是否另起一行;不传则不动,false 表示取消换行"),
] = None,
citations: Annotated[
list[CitationSpec] | None,
Field(description="引用整组替换;传 [] 表示清空引用"),
] = None,
) -> str:
"""修改一句话的正文、所属段落、排序或引用(引用是整体替换)。"""
if content is None and position is None and sort is None and citations is None:
"""修改一句话的正文、所属段落、排序、换行或引用(引用是整体替换)。"""
if (
content is None
and position is None
and sort is None
and line_break_before is None
and citations is None
):
s.fail("没有给出任何要修改的内容")
with s.session() as db:
@@ -143,6 +163,7 @@ def register(server: MCPServer) -> None:
content=content,
paper_template_filed_sort=position,
sort=sort,
line_break_before=line_break_before,
citations=None if citations is None else _citations(citations),
),
)