Files
syops/docs/superpowers/plans/2026-08-21-shipping-profile-anchor-frame.md
T

265 lines
17 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Shipping Profile Anchor Frame Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** 让坐标 Profile 能在同一稳定版式因动态内容导致主表纵向平移时,使用冻结的锚点坐标框架完成确定性匹配和取值,而不影响未启用该能力的模板。
**Architecture:** 在现有 `OrderCoordinateProfile` 中增加可选的扁平 `coordinate_model` 声明(`type`、`anchors`、`max_translate_x`、`max_translate_y`)。matcher 从当前 Layout 的唯一锚点和主表结构计算受限的平移变换;同一变换贯穿表头观测、主表定位、订单头字段和值框、订单行坐标重建,禁止建立第二套偏移估算机制。
**Tech Stack:** Flask、Pydantic、SQLAlchemy JSON Profile、pytest、Vue 3、TypeScript、Vue I18n、Vitest。
## Global Constraints
- 原 PDF 是不可变事实;匹配和解析所需的页级坐标必须通过 `ensure_on_demand_coordinate_evidence()` 获取。
- 未声明 `coordinate_model.type = anchor_frame` 的 Profile 必须逐位保持现有 matcher、取值、阈值和候选排序行为。
- 不允许按订单号、客户名、文件名或固定偏移量写代码;不建立按 PDF 的坐标变体。
- 仅允许平移;锚点不存在、不唯一、位移超过模板上限、关键结构冲突或多个 Profile 合格时必须 `review_required`。
- Schema 是唯一业务字段契约;Dify 不参与模板选择、坐标变换或正式值取值。Dify 配置由用户维护,本项目仅在收尾文档说明其边界。
- 不改数据库表结构、不新增依赖、不修改其他 Profile 数据;FOX MX Profile 现版数据在后端能力通过回归后再单独受控更新。
---
### Task 1: 冻结 Profile 契约与变换审计输出
**Files:**
- Modify: `backend/app/services/shipping_notice/document_layout/order_profile.py`
- Modify: `backend/app/services/shipping_notice/document_layout/order_profile_matcher.py`
- Test: `backend/tests/test_shipping_order_profile_matcher.py`
**Interfaces:**
- Produces `CoordinateModel` / `AnchorFrameCoordinateModel`,作为 `OrderCoordinateProfile.coordinate_model`。
- Produces `CoordinateTransform`,包含 `status`、`translate_x`、`translate_y`、`anchor_ids`、`reason_codes`;仅含配置身份与数值,不含正文。
- Extends `ProfileMatchCandidate` with optional `coordinate_transform`.
- [ ] **Step 1: 写入失败用例**
```python
def test_anchor_frame_matches_same_structure_after_bounded_vertical_translation():
profile = _with_signature(_profile('PO_A', coordinate_model={
'type': 'anchor_frame',
'anchors': [{'anchor_id': 'title', 'text': 'PURCHASE ORDER', 'region': {'x0': .1, 'y0': .05, 'x1': .9, 'y1': .15}}],
'max_translate_x': .01, 'max_translate_y': .04,
}), _layout())
result = match_frozen_coordinate_profiles(profiles=[profile], layout=_translated_layout(.03))
assert result.status == 'unique_match'
assert result.candidates[0].coordinate_transform['translate_y'] == .03
```
- [ ] **Step 2: 验证 RED**
Run: `cd backend; .\\venv\\Scripts\\python.exe -m pytest -q tests/test_shipping_order_profile_matcher.py -k anchor_frame`
Expected: FAIL,因为 Profile 契约尚不接受 `coordinate_model`,且 matcher 未输出变换。
- [ ] **Step 3: 最小实现**
```python
class AnchorFrameCoordinateModel(OrderProfileModel):
type: Literal['anchor_frame']
anchors: list[AnchorRule] = Field(min_length=1, max_length=4)
max_translate_x: float = Field(default=.03, ge=0, le=.15)
max_translate_y: float = Field(default=.06, ge=0, le=.20)
class CoordinateModel(OrderProfileModel):
type: Literal['legacy', 'anchor_frame'] = 'legacy'
anchor_frame: AnchorFrameCoordinateModel | None = None
```
在 matcher 中仅当 `anchor_frame` 明确启用时从唯一静态锚点计算一致的 X/Y 平移;超界、缺失、歧义或多个锚点不一致必须为硬失败原因。对当前观察表头和主表 bbox 应用该平移后才评分;`legacy` 路径不改。
- [ ] **Step 4: 验证 GREEN 与旧逻辑回归**
Run: `cd backend; .\\venv\\Scripts\\python.exe -m pytest -q tests/test_shipping_order_profile_matcher.py`
Expected: PASS;新增用例覆盖受限平移、缺锚点、歧义锚点、超界平移和 legacy 不变。
### Task 2: 让已选变换贯穿 Profile 行重建
**Files:**
- Modify: `backend/app/services/shipping_notice/order_extraction_workflow.py`
- Modify: `backend/app/services/shipping_notice/document_layout/coordinate_table_reconstruction.py`
- Test: `backend/tests/test_shipping_coordinate_table_reconstruction.py`
- Test: `backend/tests/test_shipping_generic_order_gate.py`
**Interfaces:**
- Consumes `ProfileMatchResult` 中唯一选中 Profile 的 `coordinate_transform`。
- Extends `reconstruct_coordinate_profile_rows(..., coordinate_transform: dict | None = None)`。
- Produces仅以同一运行时平移投影后的表区/行区重建结果。
- [x] **Step 1: 写入失败用例**
```python
def test_reconstruction_uses_selected_anchor_frame_translation_for_all_subrows():
rows = reconstruct_coordinate_profile_rows(
characters=_translated_rows(.03), table_bbox=_page_bbox(),
table_region=_legacy_region(), line_layouts=_layouts(),
coordinate_transform={'status': 'applied', 'translate_x': 0, 'translate_y': .03},
)
assert rows[0].fields['customer_po_line_no'] == '00010'
```
- [x] **Step 2: 验证 RED**
Run: `cd backend; .\\venv\\Scripts\\python.exe -m pytest -q tests/test_shipping_coordinate_table_reconstruction.py -k anchor_frame`
Expected: FAIL,因为重建函数没有接收或应用运行时变换。
- [x] **Step 3: 最小实现**
为坐标重建增加仅限 `status=applied` 的平移投影;校验平移数字有限且投影框仍在页内,非法变换返回现有的不可重建结果。工作流必须从共同 matcher 的唯一结果传递同一 `coordinate_transform`,不能重新计算、不能按 raw table 猜测偏移。
- [x] **Step 4: 验证 GREEN 与路由门禁**
Run: `cd backend; .\\venv\\Scripts\\python.exe -m pytest -q tests/test_shipping_coordinate_table_reconstruction.py tests/test_shipping_generic_order_gate.py`
Expected: PASS;缺失/非法变换保持 `coordinate_evidence_unavailable → review_required`,其他 Profile 路由不变。
### Task 3: 管理端声明与复核端审计展示
**Files:**
- Modify: `frontend/src/features/admin/types/shipping-order-document-profile.types.ts`
- Modify: `frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileEditorPage.vue`
- Modify: `frontend/src/features/chat/types/shipping.api.types.ts`
- Modify: `frontend/src/features/chat/components/shipping-review/ReviewProfileMatchPanel.vue`
- Modify: `frontend/src/locales/zh-CN/chat.json`
- Modify: `frontend/src/locales/zh-TW/chat.json`
- Modify: `frontend/src/locales/en/chat.json`
- Modify: `frontend/src/locales/th/chat.json`
- Test: `frontend/src/features/chat/components/shipping-review/ReviewProfileMatchPanel.spec.ts`
**Interfaces:**
- Admin payload accepts optional `coordinate_model`,默认 `legacy`,只有管理员显式确认时才提交 `anchor_frame`。
- Review DTO exposes `coordinate_transform` only for the selected/current candidate and reason codes only.
- [x] **Step 1: 写入失败的前端展示用例**
```ts
it('shows anchor-frame translation only in the technical template-match detail', () => {
const wrapper = mount(ReviewProfileMatchPanel, { props: { profileMatch: anchorFrameMatch } })
expect(wrapper.text()).toContain('锚点坐标框架')
expect(wrapper.text()).toContain('纵向平移')
})
```
- [x] **Step 2: 验证 RED**
Run: `cd frontend; npm run test:unit -- ReviewProfileMatchPanel.spec.ts`
Expected: FAIL,因为 DTO 和面板尚未呈现坐标框架诊断。
- [x] **Step 3: 最小实现**
在现有 Profile 编辑器增加受控的“相对锚点坐标框架”选项:默认关闭,启用时要求至少一个唯一静态 AnchorRule 与 X/Y 上限。复核面板只展示模式、是否应用、X/Y 平移和稳定 reason code;不显示原始字符、不显示完整 PDF 坐标、不新增终端用户操作。
- [x] **Step 4: 验证 GREEN、四语一致和构建**
Run: `cd frontend; npm run test:unit -- ReviewProfileMatchPanel.spec.ts; npm run build`
Expected: PASS;所有新增 i18n key 存在于四种语言,构建无 TypeScript 错误。
### Task 4: 当前 FOX MX 现版数据、端到端回归与正式文档
**Files:**
- Modify: `docs/demand.md`
- Modify: `docs/tec.md`
- Modify: `docs/funclist.md`
- Modify: `docs/features/shipping-notice/technical.md`
- Modify: `docs/features/shipping-notice/business.md`
- Modify: current database Profile `61` only after Task 1-3 pass
- Test: `backend/tests/test_shipping_order_profile_matcher.py`
- Test: `backend/tests/test_shipping_coordinate_table_reconstruction.py`
- Test: `frontend/src/features/chat/components/shipping-review/ReviewProfileMatchPanel.spec.ts`
**Interfaces:**
- FOX MX current Profile uses `coordinate_model.type = anchor_frame`; it has no order-number-specific rule and no stored A/B variant.
- Dify document only explains that Dify must not participate in this deterministic path; it contains no credentials or platform mutation.
- [ ] **Step 1: 增加真实 Layout 回归测试**
```python
def test_fox_mx_anchor_frame_matches_baseline_and_dynamic_vertical_shift(app):
assert _match_profile_layout(profile_id=61, layout_id=124).status == 'unique_match'
assert _match_profile_layout(profile_id=61, layout_id=346).status == 'unique_match'
assert _match_profile_layout(profile_id=61, layout_id=344).status == 'unique_match'
```
- [ ] **Step 2: 验证 RED**
Run: `cd backend; .\\venv\\Scripts\\python.exe -m pytest -q tests/test_shipping_order_profile_matcher.py -k fox_mx_anchor_frame`
Expected: FAIL,直到当前 Profile 明确声明 `anchor_frame` 且现版签名/定义一致。
- [ ] **Step 3: 受控更新现版 Profile 数据**
只在 Task 1-3 的全量相关测试通过后,事务更新 Profile 61 的 `definition_json`、结构指纹、checksum、matching signature 及其 validation run;不新建版本。变换锚点仅取固定标题/表头等静态文本,基线为 `4210007483.pdf`,回归样本为 `4210012208.pdf` 和 `4210012210.pdf`。
- [ ] **Step 4: 完成端到端验证和正式文档**
Run: `cd backend; .\\venv\\Scripts\\python.exe -m pytest -q tests/test_shipping_order_profile_matcher.py tests/test_shipping_coordinate_table_reconstruction.py tests/test_shipping_order_field_extraction.py tests/test_shipping_generic_order_gate.py`
Run: `cd frontend; npm run test:unit -- ReviewProfileMatchPanel.spec.ts; npm run build`
Run: `git diff --check`
Expected: 全部 PASS;正式文档包含架构、失败闭环、其他模板隔离、FOX MX 校准规则及 Dify 手动配置边界。
## Phase Review Gates
| 阶段 | 关键节点 | 放行证据 |
| --- | --- | --- |
| 1 | 范围/数据基线/既有能力 | 本计划、Profile 61 回滚校验、2208/2210 差异证据、未影响其他 Profile 的 DB 查询 |
| 2 | 契约/Matcher/行重建 | RED→GREEN 测试、legacy 回归、缺锚/歧义/超界 fail-closed 测试 |
| 3 | 管理端/复核端/i18n | Vitest、四语言 JSON 解析、前端 build、无新增用户端越权动作 |
| 4 | 数据/全链路/文档 | 三份 FOX PDF 真实 Layout 回归、相关后端测试、前端 build、`git diff --check`、文档一致性检查 |
## Phase 1 Review Record
- [x] 原因确认:2026-08-20 将 Profile 61 的表格/表头/行布局整体下移 `0.0124703088`,使 Layout 344 命中但 Layout 346 发生 `profile_header_signature_conflict`。
- [x] 基线恢复:Profile 61 与 validation run #150 已恢复至 `4210007483.pdf` 对应的历史冻结定义;Layout 124 和 346 已复算为 `unique_match`。
- [x] 范围确认:不采用按 PDF 的 A/B 变体,不改变全局 matcher 阈值,不改 Dify,不新增数据库表。
- [x] 影响确认:本阶段仅修改计划文档;已有数据库恢复仅涉及 Profile 61,其他 6 个 Profile 未写入。
- [x] 下一阶段准入:已具备最小契约、测试和隔离边界,可进入后端 TDD。
## Phase 2 Review Record
- [x] 契约/Matcher:`legacy` 默认路径保持 `coordinate_transform=None`;`anchor_frame` 仅由唯一静态锚点计算有限平移,缺失、歧义、不一致、超界均 fail-closed。
- [x] 评分一致性:matcher 对当前观察和七维结构评分均使用不回写冻结签名的平移副本;签名校验仍使用冻结签名原文。
- [x] 行重建:共同 matcher 选中的变换只经 Profile 身份校验后传入工作流;页级裁剪、表区、物理行、字段区、终止/排除区使用同一内存投影。
- [x] Fail-closed:非法/缺失变换不回退旧绝对坐标,保持 `order_profile_coordinate_reconstruction_unavailable -> coordinate_evidence_unavailable`。
- [x] 回归证据:matcher 24 passed;坐标重建 40 passed;通用路由门禁 22 passed。
- [x] 范围 Review:未新增数据库表、依赖、Profile 版本或 Dify 配置;未改变订单头第二套取值机制;其他 legacy Profile 调用点默认行为不变。
- [x] 下一阶段准入:后端变换闭环已完成并通过阶段验收,进入管理端/复核端/i18n 实现。
## Phase 3 Review Record
- [x] DTO 契约:前端与后端统一使用扁平 `coordinate_model`(`type`、`anchors`、`max_translate_x`、`max_translate_y`),不保留嵌套变体。
- [x] 管理端:默认 `legacy`;仅显式选择 `anchor_frame` 才提交配置;锚点为空、无坐标或 X/Y 上限越界时保存门禁阻断;legacy 不写新字段。
- [x] 复核端:仅管理员技术详情展示模式、应用状态、X/Y 平移和 reason code;普通用户不显示坐标框架诊断;不输出原始正文或完整坐标。
- [x] 四语言:zh-CN、zh-TW、en、th 均补齐 `coordinateModel` 与管理端配置文案。
- [x] Header 闭环:订单头字段读取消费 matcher 已选同一 `coordinate_transform`,订单号/日期/币种不再独立使用旧绝对框。
- [x] 自动化证据:后端相关测试 123 passed;复核投影测试 3 passed;前端 ReviewPanel 5 passed;`npm run build` passed。
- [x] 范围 Review:未新增数据库表、依赖、Dify 配置或用户端动作;legacy Profile 和其他模板默认路径保持不变。
- [x] 下一阶段准入:阶段 3 合规 Review 通过,可进入现版 FOX MX Profile 61 受控数据校准。
## Phase 4 Review Record
- [x] 数据基线复核:Profile 61 当前 `definition_json` 与历史 revision 51 逐项一致;附件 `4210007483.pdf` 的表头、订单号标签、订单号值框与现版坐标一致,未发现需要恢复的坐标。
- [x] 订单号根因:PDFium 原生字符将 `ORDER NO.:` 嵌在整行文本中;旧的锚点匹配将整行作为 `exact` 比较对象,导致锚点无法命中,根因不是 Profile 坐标偏移。
- [x] 最小修复:matcher 在视觉行内定位锚点子串并使用锚点自身 bbox;未改变 Profile 61 的定义、字段/表格坐标、版本号或其他 Profile 数据。
- [x] 真实回归:Layout 124 为 `unique_match`(0.985938),Layout 346 为同 Profile `unique_match`(0.889008),Layout 344 为 `evidence_insufficient` 并进入 Review;禁止证据不足时高分自动命中。
- [x] 订单头取值:Layout 124 确定性读出 `customer_po_number=4210007483`,状态 `confirmed`,来源 `pdf_coordinate`;日期、币种、目的地等绑定字段均通过。
- [x] 范围与数据隔离:未新建 Profile 版本、未更新 Profile 61 数据、未修改其他 Profile、未修改 Dify 配置;数据库写入范围为零。
- [x] 下一阶段准入:后端 matcher、订单头/订单行相关回归及前端构建完成后,进入最终阶段验收报告。
## Final Phase Acceptance Report
| 阶段 | 验收结果 | 证据 |
| --- | --- | --- |
| 4A 基线核验 | 通过 | Profile 61 当前定义与 revision 51 一致;PDF 实测坐标未支持坐标回写 |
| 4B matcher 修复 | 通过 | `tests/test_shipping_order_profile_matcher.py`:25 passed;行内 `ORDER NO.:` 锚点可定位自身字符框 |
| 4C 影响 Review | 通过 | Layout 124/346 唯一匹配;Layout 344 `evidence_insufficient`;订单号 `4210007483` confirmed |
| 4D 数据边界 | 通过 | version=1 保持不变;未新建版本、未修改其他 Profile、未写入 Profile 61 数据、未修改 Dify |
| 5 全链路验收 | 通过 | 后端 124 passed;ReviewPanel 5 passed;前端 `npm run build` 通过;`git diff --check` 通过 |
结论:该阶段工作满足“原 PDF 不可变、Schema 唯一契约、证据不足进入 Review、无坐标变体、其他模板隔离”的要求。订单号识别问题由行内锚点匹配修复解决,不通过修改现版 Profile 坐标规避。