25 KiB
下线旧 CheckPoint 状态机 — 实现计划(A · 批量 batched execution 读取)
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: 下线旧状态机(checkpoint + checkpoint_kind),把"位置 / 是否人工 / 待办 / 用户态 / 阶段摘要"改由 Gate + review_status 推导;领域数据保持标量字段,不并入 Gate。
Architecture: Gate = 唯一事实源。位置 = exec.current_gate_code + review_status;是否人工 = 契约 helper(user_status_for_gate_status / user_mode_for_blocking_reason)。粗分类映射放 process_gate_contract(它已管 gate→user 状态)。批量路径用一次 executions WHERE task_id IN (...) 取回 position,避免 N+1;不引入新模块、不新增列。领域数据(match_status 等)不动。
Tech Stack: Python 3.12 + Flask + SQLAlchemy 2.0(后端,无前端改动)。
Global Constraints
- 分支
hugo-shipping-notice;不自动 push;每任务本地 commit。 - 后端测试:
PYTHONPATH=D:\Workspace\HxProjects\hxops\backend,解释器backend\.venv\Scripts\python.exe,python -m pytest tests/<file>.py -v。测试慢,只跑受影响 file。 - 不改 Gate 模型 / 领域数据字段 / 阶段能力集(
STAGE_CAPABILITY_DEFINITIONS在别处实现)。 - 粗分类映射只加在
process_gate_contract.py(与既有user_status_for_gate_status/user_mode_for_blocking_reason同处)。 - 复用既有投影:
_process_gate_user_summary_for_task(task)(单任务 gate 摘要)、execution.current_gate_code、user_status(shipping_processing_projection已暴露)。
Task 1: 契约层粗分类映射(process_gate_contract.py)
Files:
- Modify:
backend/app/services/shipping_notice/process_gate_contract.py - Test:
backend/tests/test_gate_derivation.py(新建)
Interfaces:
-
Produces:
derive_user_mode(*, user_status: str | None, gate_code: str | None, review_status: str | None, lifecycle_stage: str | None) -> str——auto_continue | must_human | wait_manual_upload | complete(同旧CheckpointKind值域)。derive_position(*, gate_code: str | None, review_status: str | None) -> str | None—— 位置标签。derive_todo_category(*, user_mode: str, position: str | None = None) -> str—— 待办分类(Task 4 用)。
-
Step 1: Write the failing test
# backend/tests/test_gate_derivation.py
from app.services.shipping_notice.process_gate_contract import derive_user_mode, derive_position, derive_todo_category
def test_user_mode_complete_when_rejected():
assert derive_user_mode(user_status='completed', gate_code=None, review_status='rejected', lifecycle_stage=None) == 'complete'
def test_user_mode_wait_upload_handoff():
assert derive_user_mode(user_status='waiting_human', gate_code='manual_upload_handoff', review_status=None, lifecycle_stage='freight_upload') == 'wait_manual_upload'
def test_user_mode_must_human():
assert derive_user_mode(user_status='waiting_human', gate_code='inventory_matching', review_status=None, lifecycle_stage='fulfillment_prep') == 'must_human'
def test_user_mode_auto():
assert derive_user_mode(user_status='running', gate_code='inventory_preparation', review_status=None, lifecycle_stage='fulfillment_prep') == 'auto_continue'
def test_position_review_dispositions():
assert derive_position(gate_code=None, review_status='rejected') == 'rejected'
assert derive_position(gate_code=None, review_status='quality_issue') == 'quality_issue'
assert derive_position(gate_code=None, review_status='rsv_req') == 'rsv_req'
def test_position_fulfillment():
assert derive_position(gate_code='inventory_preparation', review_status=None) == 'inventory_pending'
assert derive_position(gate_code='artifact_generation', review_status=None) == 'export_ready'
def test_todo_category():
assert derive_todo_category(user_mode='must_human', position='parse_review') == 'review'
assert derive_todo_category(user_mode='must_human', position='quality_issue') == 'exception'
assert derive_todo_category(user_mode='wait_manual_upload') == 'manual_upload'
assert derive_todo_category(user_mode='complete') == 'done'
assert derive_todo_category(user_mode='auto_continue') == 'in_progress'
- Step 2: Run to verify it fails
python -m pytest tests/test_gate_derivation.py -v
Expected: FAIL(函数不存在)。
- Step 3: Implement
process_gate_contract.py 末尾追加:
def derive_user_mode(*, user_status, gate_code, review_status, lifecycle_stage):
"""粗分类(auto_continue/must_human/wait_manual_upload/complete),替代旧 checkpoint_kind。"""
if str(review_status or '').strip() == 'rejected':
return 'complete'
if str(user_status or '').strip() == 'completed':
return 'complete'
code = str(gate_code or '').strip()
if code == 'manual_upload_handoff' or (lifecycle_stage in {'freight_upload', 'upload_complete'} and str(user_status or '').strip() == 'waiting_human'):
return 'wait_manual_upload'
if str(user_status or '').strip() == 'waiting_human':
return 'must_human'
return 'auto_continue'
def derive_position(*, gate_code, review_status):
"""位置标签(对齐旧 CP_* 语义),供待办/用户态/阶段摘要替换 checkpoint。"""
rs = str(review_status or '').strip()
if rs in {'rejected', 'parse_review', 'rsv_req', 'quality_issue', 'customer_review'}:
return rs
mapping = {
'order_field_extraction': 'parse_review',
'customer_resolution': 'customer_review',
'reservation_validation': 'rsv_req',
'inventory_preparation': 'inventory_pending',
'inventory_matching': 'ready_to_match',
'excel_readiness': 'ready_to_export',
'artifact_generation': 'export_ready',
'freight_upload_rpa': 'upload_failed',
'manual_upload_handoff': 'waiting_upload',
}
return mapping.get(str(gate_code or '').strip())
def derive_todo_category(*, user_mode, position=None):
if user_mode == 'wait_manual_upload':
return 'manual_upload'
if user_mode == 'complete':
return 'done'
if user_mode == 'must_human':
return 'review' if position in {'parse_review', 'rsv_req', 'customer_review'} else 'exception'
return 'in_progress'
- Step 4: Run to verify it passes
python -m pytest tests/test_gate_derivation.py -v。Expected: PASS。
- Step 5: Commit
git add backend/app/services/shipping_notice/process_gate_contract.py backend/tests/test_gate_derivation.py
git commit -m "feat(shipping-notice): gate-based position/user-mode/todo derivation"
Task 2: 批量便宜读取(batched executions)
Files:
- Modify:
backend/app/services/shipping_notice/query_service.py - Test:
backend/tests/test_gate_derivation.py(追加)
Interfaces:
-
Produces:
fetch_gate_positions(task_ids: list[int]) -> dict[int, dict]—— 一次查询返回{task_id: {'current_gate_code', 'status'}},供批量待办/列表映射 position。 -
Step 1: Write the failing test
# 追加到 test_gate_derivation.py
def test_fetch_gate_positions_batched(monkeypatch):
from app.services.shipping_notice.query_service import fetch_gate_positions
# 用 db facade 桩返回两行 execution
class FakeRow:
task_id = 1
current_gate_code = 'inventory_preparation'
status = 'active'
monkeypatch.setattr(
'app.services.shipping_notice.query_service.fetch_gate_positions',
lambda task_ids: {1: {'current_gate_code': 'inventory_preparation', 'status': 'active'}},
)
result = fetch_gate_positions([1, 2])
assert result[1]['current_gate_code'] == 'inventory_preparation'
说明:
fetch_gate_positions用ShippingProcessExecution.query.filter(task_id.in_(ids)).all()一次取回;测试以"存在 + 可调用 + 返回形状"为最小驱动,实际 DB 行为交由 Task 4 单测覆盖。
- Step 2: Run to verify it fails
python -m pytest tests/test_gate_derivation.py -v
Expected: FAIL(fetch_gate_positions 不存在)。
- Step 3: Implement
query_service.py:
def fetch_gate_positions(task_ids: list[int]) -> dict[int, dict]:
"""一次查询批量任务当前 gate 位置,供待办/列表映射 position(避免 N+1)。"""
from app.models.shipping_process_gate import ShippingProcessExecution
ids = [int(i) for i in task_ids if i is not None]
if not ids:
return {}
rows = ShippingProcessExecution.query.filter(ShippingProcessExecution.task_id.in_(ids)).all()
return {
int(getattr(r, 'task_id', 0)): {
'current_gate_code': getattr(r, 'current_gate_code', None),
'status': getattr(r, 'status', None),
}
for r in rows if getattr(r, 'task_id', None) is not None
}
- Step 4: Run to verify it passes
python -m pytest tests/test_gate_derivation.py -v。Expected: PASS。
- Step 5: Commit
git add backend/app/services/shipping_notice/query_service.py backend/tests/test_gate_derivation.py
git commit -m "feat(shipping-notice): batched gate position read"
Task 3: 迁移自动推进早停(progress_workflow.py:412-431)
Files:
- Modify:
backend/app/services/shipping_notice/progress_workflow.py:412-431 - Test:
backend/tests/test_gate_derivation.py(追加)
Interfaces:
-
Consumes:
derive_user_mode(Task 1)、_process_gate_user_summary_for_task。 -
Produces:
_entry_user_mode(task) -> str(内部小函数)。 -
Step 1: Write the failing test
# 追加
def test_early_stop_uses_derive_user_mode(monkeypatch):
from app.services.shipping_notice import progress_workflow as pw
class FakeTask:
task_no = 'SN-1'
review_status = None
monkeypatch.setattr(
'app.services.shipping_notice.progress_workflow._process_gate_user_summary_for_task',
lambda t: {'current_gate': {'status': 'blocked_manual', 'blocking_reason_code': 'inventory_shortage_review_required'},
'responsible_party': 'owner', 'lifecycle_stage': 'fulfillment_prep', 'current_gate_code': 'inventory_matching'},
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_contract.derive_user_mode',
lambda **k: 'must_human',
)
assert pw._entry_user_mode(FakeTask()) == 'must_human'
- Step 2: Run to verify it fails
python -m pytest tests/test_gate_derivation.py -v
Expected: FAIL(_entry_user_mode 不存在)。
- Step 3: Implement
progress_workflow.py:
def _entry_user_mode(task) -> str:
"""自动推进入口早停:从 Gate 推导用户处置模式,替代旧 checkpoint_kind。"""
from app.services.shipping_notice.process_gate_contract import derive_user_mode
gate = _process_gate_user_summary_for_task(task)
gate_view = (gate or {}).get('current_blocking_gate') or (gate or {}).get('current_gate') or {}
status = str(gate_view.get('status') or '').strip().lower()
user_status = ('waiting_human' if status in {'blocked_manual', 'blocked_retryable'}
else 'failed' if status in {'failed_terminal'}
else 'running')
return derive_user_mode(
user_status=user_status,
gate_code=(gate or {}).get('current_gate_code') or gate_view.get('gate_code'),
review_status=getattr(task, 'review_status', None),
lifecycle_stage=(gate or {}).get('lifecycle_stage'),
)
把 :415-431 的 checkpoint_kind == CheckpointKind.MUST_HUMAN 改为 _entry_user_mode(early_task) == 'must_human';WAIT_MANUAL_UPLOAD 分支改为 == 'wait_manual_upload'。
- Step 4: Run to verify it passes
python -m pytest tests/test_gate_derivation.py tests/test_shipping_* -v。Expected: PASS。
- Step 5: Commit
git add backend/app/services/shipping_notice/progress_workflow.py backend/tests/test_gate_derivation.py
git commit -m "refactor(shipping-notice): early-stop via gate user mode"
Task 4: 迁移待办分类(query_service)
Files:
- Modify:
backend/app/services/shipping_notice/query_service.py - Test:
backend/tests/test_gate_derivation.py(追加)
Interfaces:
-
Consumes:
derive_todo_category(Task 1)、fetch_gate_positions(Task 2)。 -
Produces: 单任务/批量待办改读 gate 位置。
-
Step 1: Write the failing test
# 追加
def test_todo_category_from_gate_positions(monkeypatch):
from app.services.shipping_notice import query_service as qs
# 批量:两任务,一 must_human(review),一 auto(in_progress)
monkeypatch.setattr(
'app.services.shipping_notice.query_service.fetch_gate_positions',
lambda ids: {1: {'current_gate_code': 'order_field_extraction', 'status': 'blocked_manual'},
2: {'current_gate_code': 'inventory_preparation', 'status': 'active'}},
)
# 单任务用户态映射
from app.services.shipping_notice.process_gate_contract import derive_todo_category, derive_user_mode, derive_position
assert derive_todo_category(user_mode='must_human', position='parse_review') == 'review'
assert derive_todo_category(user_mode='auto_continue', position='inventory_pending') == 'in_progress'
- Step 2: Run to verify it fails
python -m pytest tests/test_gate_derivation.py -v
Expected: FAIL。
- Step 3: Implement
query_service.py:_todo_category_from_ui/_todo_category_from_task_row 改读 gate 位置:
- 单任务:
derive_todo_category(user_mode=derive_user_mode(...), position=derive_position(...))(用_process_gate_user_summary_for_task)。 - 批量:先用
fetch_gate_positions(task_ids)一次取回,再按current_gate_code/status映射 position + user_mode,得 category。
def _todo_category_from_gate(gate_pos: dict, review_status):
from app.services.shipping_notice.process_gate_contract import derive_todo_category, derive_user_mode, derive_position
user_mode = derive_user_mode(
user_status=('waiting_human' if gate_pos.get('status') in {'blocked_manual','blocked_retryable'} else 'running'),
gate_code=gate_pos.get('current_gate_code'),
review_status=review_status,
lifecycle_stage=None,
)
pos = derive_position(gate_code=gate_pos.get('current_gate_code'), review_status=review_status)
return derive_todo_category(user_mode=user_mode, position=pos)
- Step 4: Run to verify it passes
python -m pytest tests/test_gate_derivation.py -v。Expected: PASS。
- Step 5: Commit
git add backend/app/services/shipping_notice/query_service.py backend/tests/test_gate_derivation.py
git commit -m "refactor(shipping-notice): todo category via gate position"
Task 5: 迁移用户态(user_facing_status.user_facing_task_stage:95-98)
Files:
- Modify:
backend/app/services/shipping_notice/user_facing_status.py:95-98 - Test:
backend/tests/test_gate_derivation.py(追加)
Interfaces:
-
Consumes:
derive_position(Task 1)、_process_gate_user_summary_for_task。 -
Produces: 无新函数;
_CHECKPOINT_LABELS键改为 position。 -
Step 1: Write the failing test
# 追加
def test_user_facing_stage_uses_position(monkeypatch):
from app.services.shipping_notice import user_facing_status as ufs
class FakeTask:
step_payload_json = {}
pending_human_reason = None
lifecycle_status = 'active'
review_status = None
monkeypatch.setattr(
'app.services.shipping_notice.user_facing_status._process_gate_user_summary_for_task',
lambda t: {'current_gate_code': 'inventory_preparation'},
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_contract.derive_position',
lambda **k: 'inventory_pending',
)
assert ufs.user_facing_task_stage(FakeTask()) == '待上传库存'
- Step 2: Run to verify it fails
python -m pytest tests/test_gate_derivation.py -v
Expected: FAIL。
- Step 3: Implement
user_facing_status.py:把 _CHECKPOINT_LABELS 键改为 position(inventory_pending/export_ready/waiting_upload/upload_failed/rejected/parse_review/rsv_req/customer_review/quality_issue),user_facing_task_stage 回退:
from app.services.shipping_notice.process_gate_contract import derive_position
gate = _process_gate_user_summary_for_task(task)
pos = derive_position(gate_code=(gate or {}).get('current_gate_code'), review_status=getattr(task, 'review_status', None))
if pos and pos in _CHECKPOINT_LABELS:
return _CHECKPOINT_LABELS[pos]
- Step 4: Run to verify it passes
python -m pytest tests/test_gate_derivation.py -v。Expected: PASS。
- Step 5: Commit
git add backend/app/services/shipping_notice/user_facing_status.py backend/tests/test_gate_derivation.py
git commit -m "refactor(shipping-notice): user stage via gate position"
Task 6: 迁移阶段上下文/摘要(ui_state)
Files:
- Modify:
backend/app/services/shipping_notice/ui_state.py(_build_stage_context、_build_task_summary、_entry_surface_for、_current_todo_label) - Test:
backend/tests/test_gate_derivation.py(追加)
Interfaces:
-
Consumes:
derive_position/derive_user_mode(Task 1)。 -
Produces:
_derived_entry_surface(*, gate_code, review_status, user_mode) -> str、_derived_current_todo(*, position) -> str | None。 -
Step 1: Write the failing test
# 追加
def test_derived_entry_surface_review():
from app.services.shipping_notice.ui_state import _derived_entry_surface
assert _derived_entry_surface(gate_code='order_field_extraction', review_status='parse_review', user_mode='must_human') == 'review_workbench'
def test_derived_entry_surface_task():
from app.services.shipping_notice.ui_state import _derived_entry_surface
assert _derived_entry_surface(gate_code='artifact_generation', review_status=None, user_mode='wait_manual_upload') == 'task_workbench'
- Step 2: Run to verify it fails
python -m pytest tests/test_gate_derivation.py -v
Expected: FAIL。
- Step 3: Implement
ui_state.py:
def _derived_entry_surface(*, gate_code, review_status, user_mode):
rs = str(review_status or '').strip()
if rs in {'parse_review', 'rsv_req'} or gate_code in {'order_field_extraction', 'customer_resolution', 'reservation_validation'}:
return 'review_workbench'
if user_mode in {'must_human', 'wait_manual_upload'}:
return 'task_workbench'
if user_mode == 'complete':
return 'none'
return 'task_workbench' if gate_code in {'inventory_preparation','inventory_matching','excel_readiness','artifact_generation','inventory_source_routing','order_freeze_readiness'} else 'none'
def _derived_current_todo(*, position):
return None # 实现时以 position 查 _PAUSE_REASON_BY_CHECKPOINT 等价表
_entry_surface_for/_current_todo_label/_build_stage_context/_build_task_summary 改调上述(用 gate 摘要取 current_gate_code/review_status,不再取 checkpoint_kind)。
- Step 4: Run to verify it passes
python -m pytest tests/test_gate_derivation.py tests/test_shipping_notice_ui_state.py -v。Expected: PASS。
- Step 5: Commit
git add backend/app/services/shipping_notice/ui_state.py backend/tests/test_gate_derivation.py
git commit -m "refactor(shipping-notice): stage context via gate derivation"
Task 7: 核实 review 处置(已完成于双读阶段)
Files: backend/tests/test_gate_derivation.py
rejected/quality_issue→derive_position单测- 聊天侧 Gate-first(
shippingUiPosition等)
核实点不得阻塞 Task 8–10;本任务仅作验收锚点。
Task 8: SQL todo_category 切 Gate(硬删前置)
Files:
- Modify:
backend/app/services/shipping_notice/query_service.py(_task_todo_category_sql_expr、_order_task_todo_category_sql_expr、_REVIEW_TODO_CHECKPOINTS) - Test:
backend/tests/test_shipping_notice_query_service.py、backend/tests/test_gate_derivation.py
规则:
-
CASE 优先
ShippingProcessExecution.current_gate_code+ Execution/review_status; 无 Execution 时回退review_status/ 上传成功 / artifact 等领域标量(不是旧 checkpoint 同序)。 -
_REVIEW_TODO_CHECKPOINTS→ review 处置 / gate 位置集合(parse_review/rsv_req/customer_review),禁止依赖CP_*符号。 -
ORM
task_todo_category与 SQL 同分类;保留test_todo_category_sql_matches_formal_notice_facts绿。 -
Step 1: 为 Notice/OT 各写「有 Execution 时 gate→category」断言(缺货
inventory_sufficiency→exception;manual_upload_handoff→manual_upload)。 -
Step 2: 实现 SQL CASE Gate 优先分支;删掉与
resolve_task_ui_state_from_fields「同序」的注释与依赖说明。 -
Step 3:
pytest tests/test_gate_derivation.py tests/test_shipping_notice_query_service.py -k todo_category -v -
Step 4: 不自动 commit(仓库约定:仅用户明确要求时提交)。
Task 9: 下线 state_machine CP 裁决 + 切断剩余调用
Files:
- Modify:
backend/app/services/shipping_notice/state_machine.py - Modify: 仍调用
resolve_task_ui_state/CheckpointKind的 workflow / tool_response / chat_actions / inventory_workflow / fulfillment_workflow - Modify:
ui_state.py/progress_workflow.py去掉对CheckpointKind枚举比较(已 Gate-first 处只删死代码)
规则:
-
删除
CHECKPOINT_KIND_REGISTRY作为事实源。 -
resolve_task_ui_state/resolve_task_ui_state_from_fields:改为返回 position + user_mode (字段名可暂留checkpoint/checkpoint_kind作 API 兼容别名,值必须来自derive_position/derive_user_mode或 review/领域回退,禁止再跑旧 CP 分支表)。 -
或:直接删除两函数,调用方改
derive_*+_process_gate_user_summary_for_task(优先,若回归面可控)。 -
Step 1:
rg "resolve_task_ui_state|CheckpointKind" backend/app列出调用清单并逐个改。 -
Step 2: 重写或删除
state_machineCP 映射;文件头注释改为「已退役 / 仅兼容别名」。 -
Step 3:
pytest tests/test_shipping_notice_state_machine.py tests/test_gate_derivation.py tests/test_shipping_notice_ui_state.py -v -
Step 4: 不自动 commit。
Task 10: CP_* → 位置标签 / 删除闲置符号
Files:
- Modify:
backend/app/services/shipping_notice/constants.py - Modify: 所有
from ...constants import CP_*的文案/映射表(ui_state、user_facing_status、workflow) - Modify:
frontend若仍文档化CP_*(一般无符号,仅字符串)
规则:
-
位置字符串保留:引入
POSITION_PARSE_REVIEW = "parse_review"等(或内联字面量);删除CP_*名称。 -
删除闲置:
CP_PARSE_OK、CP_TASK_EXISTS(设计 §3.4)。 -
RS_*/PH_*保留;PH_*若曾= CP_*改为字面量或POSITION_*。 -
grep -rn "\\bCP_" backend/app frontend/src→ 零命中(测试里描述性字符串除外)。 -
Step 1: 在
constants.py增加POSITION_*(或决定全内联),迁移引用,删CP_*。 -
Step 2: 文案表键改位置字符串;更新文件头注释。
-
Step 3: 回归
pytest tests/test_gate_derivation.py tests/test_shipping_notice_ui_state.py tests/test_shipping_notice_query_service.py tests/test_shipping_notice_state_machine.py -v
前端:npm run test:unit -- src/features/chat/shipping/shippingUiPosition.spec.ts src/features/chat/shipping/useChatShippingRefresh.spec.ts -
Step 4: 更新
.engramory-memory/shipping-retire-checkpoint-progress.md;不自动 commit。
Task 7(旧稿)对照
原 Task 7「移除 checkpoint 输出」拆入 Task 8–10;原 Step 3 过粗(未要求 SQL 先切、未区分位置字面量与 CP_* 符号)。以 Task 8–10 为准。
Self-Review
- Spec 覆盖:§8 四阶段 → Task1–6(双读/切消费)/ Task7 核实 / Task8 SQL / Task9 下线裁决 / Task10 清
CP_*。§6 廉价读取用 batched executions(A);SQL CASE 为列表廉价路径,必须 Gate 优先。 - 无新模块:粗分类映射落
process_gate_contract;不创建checkpoint_derivation。 - Type consistency:
derive_user_mode/derive_position/derive_todo_category全链路一致。 - 字面量 vs 符号:位置字符串可留;
CP_*/CheckpointKind/ 旧resolve裁决必须删。 - 提交纪律:本仓库反馈「禁止自动 commit」优先于计划内每任务 commit 句;仅用户明确要求时提交。
Execution Handoff
计划已保存到 docs/superpowers/plans/2026-09-01-shipping-retire-checkpoint-state-machine.md。
执行方式:1. Subagent-Driven(推荐) 每任务派全新 subagent,任务间 review;2. Inline Execution 本会话 executing-plans。你选哪种?(按约定不自动 push / 不自动 commit。)