refactor: call a heading a title, and its use a placement

`template_field_library` and `template_field` were one word apart and meant
opposite kinds of thing — a catalogue of rows versus one row — and neither name
said what a row actually is. Every row of the library is a **heading**: a piece
of text like 「1. Introduction」 with a level and typography, which is what the
reader sees at the top of a paragraph; and every row of the join table is that
heading *placed* in a template, `sort` included.

    template_field_library  -> template_title
    template_field          -> template_title_placement
    field_id (the column)   -> title_id
    TemplateFieldLibrary    -> TemplateTitle
    TemplateField           -> TemplateTitlePlacement

The join table keeps its own name rather than becoming `_link`, because it is
not a bare link: it carries `sort`, the only place display order is stored, and
it deliberately allows the same title twice in one template. `_link` would
describe two foreign keys and hide the column the ordering rule rests on.

Carried through every level, because a half-renamed layer is how the confusing
pair got there in the first place: HTTP paths (`/template-field-library` ->
`/template-titles`), the template payload (`fields`/`field_id` ->
`placements`/`title_id`, and `field_count` -> `placement_count`), the Pydantic
schemas, the CRUD modules, the seed script, the frontend API module and types,
and `docs/OVERVIEW.md`, which now states the naming rules outright.

Two deliberate exceptions:

* `paper_template_filed_sort` is untouched — it is a column of the paper module
  and is spelled as the feature was specified.
* The MCP tools keep their agent-facing names (`field_list`, `field_ids`, and
  the `fields`/`field_id` keys in their responses). Agents already call them by
  those names; the storage names they read underneath have changed.

The migration renames in place (data preserved: 4 templates, 45 titles, 63
placements) and is written to tolerate a database where part of it already ran,
which is not hypothetical — the first attempt renamed the tables and then failed
on the column, because Alembic's MySQL dialect wants an explicit type for
`alter_column` and will not rename a column without one. TiDB carries the
foreign key along with both the renamed table and the renamed column, rehearsed
against the cluster first, and it stays enforced.

Verified: seed re-runs clean, the paper smoke test's 45 checks and the MCP
smoke test's 47 pass, `vue-tsc` and the build are clean, and the UI was driven
in a headless browser through the template list, its preview drawer, the title
library page, the template form (which now posts `placements` with `title_id`)
and the paper document with no console errors.
This commit is contained in:
2026-09-22 16:55:02 +08:00
parent 3732e36e64
commit 199e328b48
40 changed files with 837 additions and 663 deletions
+3 -3
View File
@@ -23,7 +23,7 @@ from sqlalchemy import func, select
from app.core.config import get_settings
from app.db.session import SessionLocal
from app.mcp.server import SERVER_VERSION
from app.models import Paper, PaperSentence, Template, TemplateFieldLibrary
from app.models import Paper, PaperSentence, Template, TemplateTitle
def run_selfcheck(server: MCPServer) -> int:
@@ -38,8 +38,8 @@ def run_selfcheck(server: MCPServer) -> int:
"paper": db.scalar(select(func.count(Paper.id))) or 0,
"template": db.scalar(select(func.count(Template.id))) or 0,
"paper_sentence": db.scalar(select(func.count(PaperSentence.id))) or 0,
"template_field_library": db.scalar(
select(func.count(TemplateFieldLibrary.id))
"template_title": db.scalar(
select(func.count(TemplateTitle.id))
)
or 0,
}
+1 -1
View File
@@ -4,7 +4,7 @@ These are tool-argument models, not domain models: they exist so the JSON
Schema a client receives is precise enough that the model gets the shape right
the first time. Each one is converted into the project's own payload
(:class:`~app.schemas.paper.SentenceInput`,
:class:`~app.schemas.template.TemplateFieldInput`) before it reaches the CRUD
:class:`~app.schemas.template.TemplateTitlePlacementInput`) before it reaches the CRUD
layer, so the validation rules stay in one place — a citation with a blank
quote is refused here for the same reason the REST API refuses it.
+9 -7
View File
@@ -51,7 +51,7 @@ from app.models import (
Paper,
PaperSentence,
Template,
TemplateFieldLibrary,
TemplateTitle,
)
from app.schemas.paper import (
CitationInput,
@@ -169,9 +169,9 @@ def template_or_fail(db: Session, template_id: int) -> Template:
return template
def field_or_fail(db: Session, field_id: int) -> TemplateFieldLibrary:
def field_or_fail(db: Session, field_id: int) -> TemplateTitle:
"""Return one library field, or refuse with the id that was not found."""
from app.crud import template_field_library as field_crud
from app.crud import template_title as field_crud
field = field_crud.get(db, field_id)
if field is None:
@@ -359,14 +359,16 @@ def heading_index(paper: Paper) -> list[dict]:
return []
seen: dict[int, dict] = {}
for placement in paper.template.items:
for placement in paper.template.placements:
if placement.sort in seen:
continue
seen[placement.sort] = {
"position": placement.sort,
"heading": placement.field.name,
"level": placement.field.level,
"field_id": placement.field_id,
"heading": placement.title.name,
"level": placement.title.level,
# Emitted as "field_id" because that is the name this interface
# uses for a library entry; the column behind it is title_id.
"field_id": placement.title_id,
}
return [seen[position] for position in sorted(seen)]
+11 -11
View File
@@ -1,6 +1,6 @@
"""Field-library tools (字段库): the reusable headings templates are built from.
The library is the catalogue, and ``template_field`` is a placement in one
The library is the catalogue, and ``template_title_placement`` is a placement in one
template — one word apart, opposite meanings. A field exists once and may be
placed by any number of templates, which is why editing a field restyles every
outline that uses it and why deleting one is refused while any template still
@@ -20,13 +20,13 @@ from mcp.server.mcpserver import MCPServer
from pydantic import Field
from sqlalchemy.orm import Session
from app.crud import template_field_library as field_crud
from app.crud import template_title as field_crud
from app.mcp import support as s
from app.mcp.tools.registry import mcp_tool
from app.models import TemplateFieldLibrary
from app.schemas.template_field_library import (
TemplateFieldLibraryCreate,
TemplateFieldLibraryUpdate,
from app.models import TemplateTitle
from app.schemas.template_title import (
TemplateTitleCreate,
TemplateTitleUpdate,
)
@@ -45,7 +45,7 @@ def register(server: MCPServer) -> None:
"""列出字段库(模板能用的所有标题)。建模板前先查这里的 id。"""
page, page_size = s.page_args(page, page_size)
with s.session() as db:
rows, total = field_crud.list_fields(
rows, total = field_crud.list_titles(
db, keyword=keyword, level=level, page=page, page_size=page_size
)
return s.dumps(
@@ -87,7 +87,7 @@ def register(server: MCPServer) -> None:
] = "#000000",
) -> str:
"""往字段库加一个标题字段,可带字号颜色。"""
payload = TemplateFieldLibraryCreate(
payload = TemplateTitleCreate(
name=name, level=level, font_size=font_size, font_color=font_color
)
with s.session() as db:
@@ -117,7 +117,7 @@ def register(server: MCPServer) -> None:
if not values:
s.fail("没有给出任何要修改的内容")
payload = TemplateFieldLibraryUpdate(**values)
payload = TemplateTitleUpdate(**values)
with s.session() as db:
field = s.field_or_fail(db, field_id)
@@ -155,7 +155,7 @@ def register(server: MCPServer) -> None:
# --- helpers -----------------------------------------------------------------
def _field_row(field: TemplateFieldLibrary) -> dict:
def _field_row(field: TemplateTitle) -> dict:
"""One library entry as a model reads it."""
return {
"id": field.id,
@@ -166,7 +166,7 @@ def _field_row(field: TemplateFieldLibrary) -> dict:
}
def _assert_unused(db: Session, fields: list[TemplateFieldLibrary]) -> None:
def _assert_unused(db: Session, fields: list[TemplateTitle]) -> None:
"""Refuse the delete while any template still places the field.
Dropping a field that is placed somewhere would silently remove a heading
+21 -17
View File
@@ -28,7 +28,7 @@ from app.mcp import support as s
from app.mcp.specs import FieldSpec
from app.mcp.tools.registry import mcp_tool
from app.models import Template
from app.schemas.template import TemplateCreate, TemplateFieldInput
from app.schemas.template import TemplateCreate, TemplateTitlePlacementInput
#: Spacing between generated sorts. Ties are legal in a template and gaps are
#: expected — the editor numbers a fresh selection 1..N only on request — so
@@ -99,16 +99,16 @@ def register(server: MCPServer) -> None:
) -> str:
"""新建模板:名称 + 说明 + 有序字段选择。用 field_list 先查字段 id。"""
selection = _selection(field_ids, fields)
payload = TemplateCreate(name=name, abstract=abstract, fields=selection)
payload = TemplateCreate(name=name, abstract=abstract, placements=selection)
with s.session() as db:
_assert_name_free(db, payload.name)
_assert_fields_exist(db, payload.fields)
_assert_titles_exist(db, payload.placements)
template = template_crud.create(
db,
name=payload.name,
abstract=payload.abstract,
fields=payload.fields,
placements=payload.placements,
)
return s.dumps(_template_row(template))
@@ -142,7 +142,7 @@ def register(server: MCPServer) -> None:
if name is not None:
_assert_name_free(db, name, exclude_id=template_id)
if selection is not None:
_assert_fields_exist(db, selection)
_assert_titles_exist(db, selection)
updated = template_crud.update(
db,
@@ -150,7 +150,7 @@ def register(server: MCPServer) -> None:
name=name,
abstract=abstract,
abstract_provided=clear_abstract or abstract is not None,
fields=selection,
placements=selection,
)
return s.dumps(_template_row(updated))
@@ -177,16 +177,19 @@ def _template_row(template: Template) -> dict:
"id": template.id,
"name": template.name,
"abstract": template.abstract,
# The keys here are this interface's own vocabulary ("fields",
# "field_id"): agents call these tools with those names, so they stay
# put while the storage layer below calls the same rows titles.
"fields": [
{
"position": item.sort,
"field_id": item.field_id,
"name": item.field.name,
"level": item.field.level,
"font_size": float(item.field.font_size),
"font_color": item.field.font_color,
"field_id": item.title_id,
"name": item.title.name,
"level": item.title.level,
"font_size": float(item.title.font_size),
"font_color": item.title.font_color,
}
for item in template.items
for item in template.placements
],
}
@@ -194,7 +197,7 @@ def _template_row(template: Template) -> dict:
def _selection(
field_ids: list[int] | None,
fields: list[FieldSpec] | None,
) -> list[TemplateFieldInput]:
) -> list[TemplateTitlePlacementInput]:
"""Turn either way of describing a selection into placement rows.
The order of ``field_ids`` is the outline order; the numbering is generated
@@ -203,11 +206,12 @@ def _selection(
"""
if fields:
return [
TemplateFieldInput(field_id=item.field_id, sort=item.sort) for item in fields
TemplateTitlePlacementInput(title_id=item.field_id, sort=item.sort)
for item in fields
]
if field_ids:
return [
TemplateFieldInput(field_id=field_id, sort=(index + 1) * SORT_STEP)
TemplateTitlePlacementInput(title_id=field_id, sort=(index + 1) * SORT_STEP)
for index, field_id in enumerate(field_ids)
]
return []
@@ -218,13 +222,13 @@ def _assert_name_free(db: Session, name: str, *, exclude_id: int | None = None)
s.fail(f"模板名称“{name}”已存在")
def _assert_fields_exist(db: Session, fields: list[Any]) -> None:
def _assert_titles_exist(db: Session, fields: list[Any]) -> None:
"""Reject a selection that points at fields the library does not have.
Checked in Python rather than by a foreign key, exactly as the REST route
does: TiDB parses but does not enforce ``FOREIGN KEY``.
"""
missing = template_crud.missing_field_ids(db, [item.field_id for item in fields])
missing = template_crud.missing_title_ids(db, [item.title_id for item in fields])
if missing:
joined = "、".join(str(field_id) for field_id in missing)
s.fail(f"字段不存在:{joined}(先用 field_list 查可用的字段 id)")