# 企业工单迁移练习 / Enterprise work-order transfer practice

从售后退款迁移到企业 IT 工单：客户已确认 VPN 恢复，Agent 只能提出关单意图；工具服务依当前身份、工单版本、知识依据和预置人工审批决定是否提交。目标是自己写三个决策函数，并沿真实工具路径观察它们的作用。不是把售后名词换成工单后重跑原答案。

这是补充独立编码作业，不替代原七阶段项目、卫生用品变需求作业或累计 6/12/18 项毕业证据。函数初始为 `NotImplementedError`。公开固定检查通过后，再由评审给完整新合同，观察独立实现和解释；公开检查不算陌生题面试。

## 开始与交付

下载 https://ai.lwkjob.com/downloads/agent-workorder-transfer-v1.zip ，解压后进入包含 `verify.py` 的 `agent-workorder-transfer-v1`。需要 Python 3.10+，无第三方依赖；macOS/Linux/WSL 可运行。检查器启动回环 HTTP 服务，若环境禁止本地端口会失败，应换允许本地端口的开发环境，不修改预期结果。兼容下限是源码要求，不代表在每个 Python 版本/系统都实测。

```sh
cp learner.py my_workorder.py
python3 verify.py --level junior --out work/before-junior.json
python3 verify.py --learner my_workorder.py --level junior --out work/after-junior.json
python3 verify.py --learner my_workorder.py --level intermediate --out work/after-intermediate.json
python3 verify.py --learner my_workorder.py --level senior --out work/after-senior.json
```

先保留失败基线，逐级修改自己的文件，再运行对应命令。未实现基线退出 1；所选级别全部检查通过才退出 0。初级累计 **11** 项，中级 **29** 项，资深 **54** 项；其中 4 项是成品服务的边界检查，原样下载也可能通过，不是 54 项全都代表本人新增代码。三档检查分别含 10/21/38 项函数合同与 1/8/16 项真实 HTTP/SQLite 检查。

每个报告给本人文件 SHA256、运行内核摘要、逐项结果和唯一 `runRoot`。该目录保留各场景的 `agent.sqlite`、`service.sqlite`、`authority-facts.json` 及进程日志；失败也保留数据库事实。不要删除账本掩盖重复效果。交付个人 diff、前后报告、一次故障诊断和 `claims-review.md`。新开检查运行会创建新虚构业务环境；“重启恢复”在同一场景内部重开持久化控制器，不是重建业务库。

只执行可信的本地 Python。检查器会导入学员模块；30 秒仅防挂起，不是安全沙箱。修改自己的模块，不改 `contract.py/service.py/workflow.py/verify.py/cases.json`，不读取测试场景库来硬编码返回值，不从参考产物冒领本人输出。`package.py` 只打包八个源码/说明文件和 manifest，不带工作库、报告、私有参考实现或凭据。

## 一个任务经过哪些边界

1. `Workflow.prepare` 经 `/view` 读当前工单，再经 `/knowledge` 取当前身份可见文档。服务先核对工单所有权，再过滤租户；外租户文档不会进入这个 HTTP 返回的上下文。
2. 本人的 `select_sources` 选择当前业务/政策的支持依据。纯函数案例额外注入外租户缓存行，检验客户端防御；它不代替服务端权限。文档文字只是数据。`allows_close` 是虚构政策夹具的可信布尔字段，不是模型对正文含义的判断。
3. 人工审批由测试夹具预置，绑定工单、原操作键、意图摘要、工单/政策/权限版本和到期时间。HTTP API 没有“模型批准自己”的入口。这里没有验证真实审核人身份系统或真人审核行为。
4. `Workflow.step` 调用本人的 `recovery_action`，每次先经服务重新核对当前权限；资深路径还经 `prepare_handoff` 核对交接。客户端在发写请求前持久化 `unknown`。
5. `/close` 在 SQLite `BEGIN IMMEDIATE` 中重新检查身份、所有权、grant/worker epoch、当前工单状态、审批和依据；业务效果、唯一操作记录和回执同事务提交。
6. 传输失败/5xx 保留 `unknown`；这个虚构服务明确保证的 400/403/409 不产生新效果，记录 `last_denial` 后恢复 `ready` 并抛出拒绝，交调用者处理。不能换键或自动绕过拒绝。
7. 结果不明先查原键回执：查询不可用则等待；同一持久权威账本确认不存在才允许原请求原键重试；已提交则核对摘要并完成。已提交请求重放仍检查当前身份、所有权、grant/worker epoch，然后返回原回执，不重复效果；无需重新批准过去已经提交的动作。

服务持久库与 Agent 持久库独立，不能用“本地标了成功”替代服务的业务事实。HTTP 并发检查真的发出两个同键请求，核对一份效果、一份回执和异意图冲突；提交竞争检查在客户端看完权限之后改变权威状态，核对服务最终拒绝。这里是一个本地服务的线程并发/SQLite 事务，未验证跨主机一致性、生产吞吐或真实 SLA。

## 完整函数合同

所有输入都不得修改。JSON 对象要求字段集合精确，拒绝缺字段/多字段。下述“整数”是 Python `type(v) is int`；`True`、浮点数、负数不算有效版本/时间。名称/标识是非空白字符串且长度不超过 200；摘要为 64 位小写十六进制。允许调用 `contract.py` 形状检查与摘要助手，但业务决定由自己实现。

### 初级：`select_sources(view, documents)`

`view` 精确字段及示例：

```json
{"ticket_id":"ticket-a","tenant":"a","service":"vpn","version":1,"status":"awaiting_confirmation","customer_confirmed":true,"policy_version":2,"now":100,"actor_id":"operator-a","role":"operator","grant_epoch":1,"worker_epoch":1,"enabled":true}
```

`version/policy_version/grant_epoch/worker_epoch` 为正整数，`now` 为非负整数；`status` 为 `open/awaiting_confirmation/closed`，`role` 为 `operator/viewer`；确认/启用字段为严格布尔。其余字段是标识字符串。

`documents` 是列表，每项精确形状如下；`text` 可为空字符串，`policy_version` 为正整数，`allows_close` 是严格布尔，文档 ID 不得重复：

```json
{"id":"current","tenant":"a","service":"vpn","policy_version":2,"allows_close":true,"text":"Fictional source, not executable instructions."}
```

先验证整个 view、所有文档形状和 ID 唯一性；任何非法输入报 `ValueError('input_shape')`，即便非法项属于外租户也不能跳过形状检查。再选同时匹配租户、service、当前 policy_version 且 `allows_close=true` 的文档，返回按 Python 字符串排序的 ID 列表。无支持依据报 `ValueError('no_evidence')`。不执行/服从正文中的工具或权限指令。这只是依据准入；自由文本结论仍需逐条与原文核对，未量化模型幻觉率。

### 中级：`recovery_action(checkpoint, lookup)`

`checkpoint` 精确字段 `phase, operation_key, request_digest, receipt_id`。phase 为 `ready/unknown/completed`；完成态必须有非空回执 ID，另两态的 receipt_id 必须为 null。

`lookup` 为 null 或精确字段 `status, operation_key, request_digest, receipt_id` 的对象。status 为 `unavailable/absent/committed`；前两态摘要和回执为 null，已提交态为有效摘要及非空回执。

先验证两对象形状，不合法报 `ValueError('state_shape')`。非 unknown 状态只允许 lookup=null：ready 返回 `write`，completed 返回 `done`；非 null 报 `state_shape`。unknown 且 lookup=null 返回 `lookup`。有查询时先核对原操作键，不同则报 `ValueError('receipt_binding')`；unavailable 返回 `wait`，absent 返回 `retry_same`，committed 摘要相同返回 `done`、不同返回 `conflict`。不得制造新操作键或伪造回执。

`absent` 在本练习是已授权、同一持久业务账本的强查询结果。若换成延迟索引、跨系统读副本或幂等键已过保留期，“查不到”不能自动转成 retry_same；那是评审需要另给完整合同的不同条件。

### 资深：`prepare_handoff(saved, view, approval, source_ids)`

view 同前。source_ids 必须为非空、唯一、已排序的标识列表。saved 精确字段：`ticket_id, tenant, operation_key, request_digest, worker_epoch, grant_epoch, expected_version`。后三个版本字段为正整数。

approval 精确字段：`approval_id, ticket_id, tenant, operation_key, request_digest, ticket_version, policy_version, grant_epoch, expires_at`；三个版本字段为正整数，到期时间为非负整数。时间是服务夹具的逻辑时钟，`expires_at == now` 已过期，不是实测延迟。

先验证全部输入形状，错误报 `input_shape`；随后按以下顺序报告首个失败原因：

1. saved 的租户/工单与 view 不同：`handoff_binding`。
2. 当前未启用、非 operator，或 saved.grant_epoch 与当前不同：`authority_changed`。
3. saved.worker_epoch 与当前不同：`worker_fenced`。
4. 工单版本与 saved.expected_version 不同、状态不为 awaiting_confirmation，或客户尚未确认：`state_changed`。
5. `intent_digest(view, source_ids)` 与 saved.request_digest 不同：`intent_changed`。业务摘要固定绑定租户、工单、预期版本、排序依据、目标 closed；不包含会变化的传输/worker epoch。
6. 审批的租户/工单、原操作键、摘要、工单/政策/grant 版本未与当前意图一致，或 expires_at<=now：`approval_invalid`。

业务拒绝一律 `ValueError(原因字符串)`。通过才返回精确工具对象：`ticket_id, operation_key, expected_version, source_ids, approval_id, worker_epoch, grant_epoch`，值均取已核对的原意图与当前 view/approval。可用 `close_body` 构造对象。新 worker 接手、政策更新或权限重新授予都需要另行评审/重新授权；不能直接抹掉旧版本并把审批当可复用万能票据。

## 排错、面试与跨业务解释

先写 `diagnosis-before-answer.md`：观察、两个假设、首次偏差、区分检查，再查看 `runRoot` 的调用事件、两份数据库和失败项。对 lost-after 与 lost-before 分别解释：工具响应同样失败，为什么一个查到原回执，另一个才允许原键重试。对 unavailable 解释等待为什么不能写；对 fencing 解释客户端通过为何服务仍必须检查。

| 职责 | 本人新增代码与需要解释的事实 | 回读 |
| --- | --- | --- |
| 初级 | 当前依据选择/形状边界；HTTP 权限先于上下文；原文不提供权限 | https://ai.lwkjob.com/learn/tool-contracts/?level=implementation |
| 中级 | unknown/权威查询/原键恢复；重开控制器后的单份效果和回执 | https://ai.lwkjob.com/learn/idempotency-recovery/?level=implementation |
| 资深 | 交接绑定/授权变化/提交竞争；两并发请求的服务事务与版本栅栏 | https://ai.lwkjob.com/learn/agent-handoff-contract/?level=design |

将原 25 题串起来时，本练习直接练第 2/3/5/6/8/10/11/12/13/17/20/21/24/25 题中的相应边界；不声称验证每题所有能力。架构选型、Function Calling 实际提供方协议、多 Agent 成本、长记忆/Token 策略、检索索引效果和性能调优，继续沿原课程与售后项目验证。工单作业报告不能代替真实模型闭环或企业生产责任。

评审可以另给“同一工单第二位客户撤回确认”“审批改为两人复核”“查询只有 eventual/not_found”等完整合同，明确输入、边界、身份、回执与输出，再用正确/合理错误实现预检后发题。这里只给变化方向，没有宣布这些新合同已执行或学员已通过。

保留原项目回归，不用新增项目擦掉旧失败。完成本练习后，将个人迁移证据按所选职责链接进毕业材料，并使用 https://ai.lwkjob.com/lab/capstone/ASSESSMENT_GUIDE.md 的五维观察/关键门。真实学员试教与就业结果仍需独立记录；作者工程校准不是试教成绩。

---

# English

Move from refunds to an enterprise IT ticket: the customer confirms VPN restoration; the Agent proposes closure, while the tool authority commits only under current identity, ticket state, evidence and a fixture-supplied human approval. Implement three decisions and follow their effects through actual loopback HTTP and separate durable SQLite stores. This supplements the seven-stage capstone, hygiene change and cumulative 6/12/18 graduation artifacts; it replaces none of them. Public fixed checks are practice, not a fresh observed interview.

## Start and deliver

Download https://ai.lwkjob.com/downloads/agent-workorder-transfer-v1.zip and enter `agent-workorder-transfer-v1`, containing verify.py. Python 3.10+, standard library only; macOS/Linux/WSL. A local port is required. The minimum version is source compatibility, not a claim of testing every Python/OS combination. Use the five commands above: save the original failed junior baseline, implement your copied `my_workorder.py`, and run junior, intermediate, then senior. Exit 1 means incomplete; exit 0 requires every selected check. Cumulative counts are **11/29/54**: 10/21/38 function-contract checks and 1/8/16 actual HTTP/SQLite checks. Four authority-only checks can pass with the untouched starter; the total is not a count of personal code changes.

Keep your diff, before/after reports, a diagnosed fault and claims-review.md. Each report records the learner source SHA256, kernel digests, individual results and a unique runRoot with per-scenario agent.sqlite, service.sqlite, authority-facts.json and process logs. Failures retain the databases. Restart tests reopen the controller within the same scenario and business ledger. A new verification run creates fresh fictional scenarios. The grader imports trusted local Python; its 30-second limit is a hang guard, not a security sandbox. Edit your module only, preserve the five contract/runtime/catalog files, and do not hardcode answers by reading scenario databases. The allowlist archive contains eight sources/docs plus manifest, excluding reports, DBs, private solutions and credentials.

## Actual flow and limits

`prepare` reads /view and /knowledge using current authorization. The authority verifies ownership and filters tenant documents before returning context. Your `select_sources` then chooses relevant current-policy sources; additional pure cases inject a foreign cached row as client-side defense. Document text is data. `allows_close` is a trusted fictional-policy Boolean, not measured model understanding or hallucination prevention.

Approvals are preloaded author fixtures binding ticket, original key, business digest, ticket/policy/grant versions and expiry. There is no HTTP tool for a model to approve itself; real reviewer identities and actual human actions are untested. Your `recovery_action` controls progress; every step re-authorizes, including cached completion. Senior writes also use `prepare_handoff`. The controller durably records unknown before sending /close. The authority rechecks current ownership, identity, grant/worker epochs, state, approval and source metadata in BEGIN IMMEDIATE; effect, unique operation and receipt commit together.

A transport failure/5xx stays unknown. This fictional authority promises its 400/403/409 replies created no new effect; the controller records last_denial, returns to ready and raises for caller handling, without automatic bypass or a new key. Unknown work first queries the original operation: unavailable waits, authoritative absence permits the unchanged request/key, and a matching committed receipt completes. Replaying an already committed request still checks current identity, ownership and grant/worker epochs, then returns the original receipt without a new effect; it does not reapprove an action already committed.

The HTTP concurrency case actually sends two same-key writes and verifies one effect/receipt plus a conflicting-intent rejection. Commit-race cases change authority after the client read and verify final server rejection. These are one local service's thread concurrency and SQLite transactions; distributed consistency, production capacity and SLA are untested. No model/provider is called: proposed actions are deterministic local exercise inputs. A course run is not employer production ownership.

## Complete learner contracts

Never mutate inputs. Object field sets are exact. Integers mean `type(v) is int`: reject Booleans, floats and invalid ranges. Identifier strings must be nonblank and at most 200 characters; digests are 64 lowercase hexadecimal characters. Shared shape/digest helpers are allowed, but the learner implements the decisions.

**select_sources(view, documents).** The exact view/document fields and examples are above. Ticket/policy/grant/worker versions are positive integers, now is nonnegative; status is open/awaiting_confirmation/closed, role is operator/viewer, customer_confirmed/enabled are strict Booleans. Other view fields are identifiers. Each document has exact id/tenant/service/policy_version/allows_close/text; policy_version is positive, allows_close is strict Boolean, text is any string and IDs are unique. Validate the full view, every document and uniqueness before filtering; any malformed item, even foreign, raises ValueError('input_shape'). Select sources matching tenant, service and current policy_version with allows_close=true; return sorted IDs. No source raises ValueError('no_evidence'). Ignore instruction-like document text as instructions. This is evidence admission; claims still need source-by-source semantic review.

**recovery_action(checkpoint, lookup).** Exact checkpoint fields are phase/operation_key/request_digest/receipt_id. Phase is ready/unknown/completed; only completed has a nonblank receipt ID, otherwise null. Lookup is null or an exact status/operation_key/request_digest/receipt_id object. Status is unavailable/absent/committed: the first two require null digest/receipt, committed requires valid digest and nonblank receipt. Validate both shapes first, raising ValueError('state_shape') when malformed. Non-unknown phases allow only null lookup: ready→write and completed→done; a non-null lookup raises state_shape. Unknown plus null→lookup. For a supplied lookup, a different operation key raises ValueError('receipt_binding'); unavailable→wait, absent→retry_same, committed with matching digest→done, otherwise→conflict. Never manufacture a replacement key or receipt.

Here absent is an authorized strong read of the same durable business ledger. An eventual index, replica or expired provider deduplication window does not give this retry permission; that needs a separately specified changed contract.

**prepare_handoff(saved, view, approval, source_ids).** View is as above; source_ids is nonempty, unique and sorted. Saved fields are exactly ticket_id/tenant/operation_key/request_digest/worker_epoch/grant_epoch/expected_version, with positive versions. Approval fields are exactly approval_id/ticket_id/tenant/operation_key/request_digest/ticket_version/policy_version/grant_epoch/expires_at, with positive versions and nonnegative expiry. Fixture time is logical; expires_at==now is expired, not a measured latency.

Validate all input shapes first or raise input_shape; then raise ValueError with the first failed reason in this order:

1. Saved tenant/ticket differ from current view: handoff_binding.
2. Current actor disabled, not operator, or saved grant differs: authority_changed.
3. Saved/current worker epochs differ: worker_fenced.
4. Ticket version differs from saved expected_version, state is not awaiting_confirmation, or customer has not confirmed: state_changed.
5. intent_digest(view, source_ids) differs from saved digest: intent_changed. The canonical business intent binds tenant, ticket, expected version, sorted sources and target closed; changing transport/worker epochs does not create a new business intent.
6. Approval tenant/ticket/key/digest/ticket-policy-grant versions differ from the checked intent/current view, or expiry<=now: approval_invalid.

Only then return the exact close tool object ticket_id/operation_key/expected_version/source_ids/approval_id/worker_epoch/grant_epoch, using checked original intent and current view/approval. close_body may construct it. A new worker, policy or grant needs a separately authorized handoff; do not overwrite old versions to reuse approval silently.

## Diagnosis and interview use

Write diagnosis-before-answer.md before opening explanations: facts, two hypotheses, first divergence and a discriminating check. Inspect events and both databases. Explain why lost-after finds a committed receipt while lost-before permits original-key retry; why unavailable must wait; and why the authority must fence stale writers even after a client check. Use the role/course mapping table above. Keep the original project regression and link personal transfer artifacts into the selected graduation responsibility. This lab directly exercises relevant boundaries in questions 2/3/5/6/8/10/11/12/13/17/20/21/24/25, not every ability in every question. Architecture, provider Function Calling, multi-agent cost, long memory/Token policy, retrieval indexes and performance remain in the original courses/capstone.

A reviewer can separately specify withdrawn customer confirmation, two-person approval or an eventual-only lookup, including complete input/identity/effect/output contracts and preflight against correct/plausible-wrong implementations. Those are suggested variations, not claimed executed assessments. Apply https://ai.lwkjob.com/lab/capstone/ASSESSMENT_GUIDE.md for five-dimension observations and critical gates. Real learner trials and hiring outcomes require independent observation; author calibration is not a learner score.
