# Agent career levels · 售后 Agent 三层编程实训

### 售后 Agent 的三层编程练习入口
初级、中级、资深是本地编程合同的递进层次；本课的原理、实现、排错、设计四个学习视角分别产出不同证据。固定公开检查全通过不等于通过职级或招聘评估。下载 ZIP，解压后进入 agent-career-levels-v1；career_lab.py 与 career-cases.json 必须同目录。Python 3.9+，仅标准库。保留一个 career_student.py 逐层实现，模板拒绝覆盖；资深完成后重新运行三个级别。
- https://ai.lwkjob.com/lab/career-levels/README.md
- https://ai.lwkjob.com/lab/career-levels/career_lab.py
- https://ai.lwkjob.com/lab/career-levels/career-cases.json
- https://ai.lwkjob.com/downloads/agent-career-levels-v1.zip

```bash
python3 career_lab.py scaffold --out career_student.py
python3 career_lab.py grade --module career_student.py --level junior --out report-junior.json
python3 career_lab.py grade --module career_student.py --level intermediate --out report-intermediate.json
python3 career_lab.py grade --module career_student.py --level senior --out report-senior.json
```

### 独立合同与授权来源
JSON输入与Lease不可修改；run_step仅通过runtime.commit修改提供的运行时，这是允许的状态副作用。纯函数返回的dict/list与输入不得共享容器。输出使用严格 JSON 类型；True 不能充当整数 1。异常精确到类型和消息。身份 principal 和运行时 policy 是题目给定的可信服务端事实；task、历史 approval 和模型文字不能创建授权。仅导入自己信任的学员文件；grader 是子进程挂起保护，不是恶意代码安全沙箱。

validate_task(task, principal)：task 精确包含 id、tenant、units，前两项为非空 str；units 严格 int、范围1..100。principal 精确包含非空 str tenant 与严格 bool enabled。先校验所有形状，非法抛 ValueError("input_shape")；再检查租户，不匹配抛 PermissionError("tenant_mismatch")；最后 disabled 抛 PermissionError("tenant_disabled")。成功返回 task 的深复制。禁止从 task 的自报 enabled 推导权限。

plan_round(tasks, budgets, cursor, slots)：tasks 是上述任务列表，ID 唯一；budgets 为租户非空 str→严格非负 int，可为空；cursor 为 None 或非空 str；slots 严格非负 int。任何形状错误抛 ValueError("input_shape")。未知租户不调度，不能借别的租户预算。按租户名词典序，从 cursor 后的第一个租户开始，末尾环绕；每次取一个可负担的租户队首并扣规划剩余额度，再从刚选租户之后继续。租户内 FIFO，队首太贵不能绕过取便宜尾项。无可选队首或达到 slots 即停止。返回精确 selected（ID列表）、cursor（最后选中租户，无选中保留输入值）、remaining（规划后预算）。这是请求轮转与整数预估成本，不是耗时公平、实际Token费用结算或生产配额。

migrate_state(snapshot)：v1精确字段 schema/id/tenant/status/approval/budget_used/operation_key/extensions。schema 严格 int；非1/2抛 ValueError("unsupported_schema")，其他非法形状抛 ValueError("input_shape")。id/tenant 非空str；budget_used严格非负int；operation_key为None或非空str；extensions为JSON dict原样深复制。approval精确包含与快照相同tenant、严格正int epoch、decision（pending/approved/denied）。v1 status为waiting/running/unknown/completed。waiting按批准事实分别变awaiting_approval/ready/blocked；unknown变reconcile_required；running/completed保留。unknown/reconcile_required必须有operation_key。v2增加migration={"from_schema":1,"to_schema":2}（严格整数），并只允许上述新状态、running、completed。合法v2深复制原样返回。迁移不得重写批准代次、预算消耗、业务key或扩展字段，不得产生业务副作用。

run_step(runtime, lease, action)：导入 career_lab.Lease 与 CommitConflict，合法 dataclass/future annotations 和同一异常类型受支持。action只允许dispatch/migrate，先检查，否则ValueError("action")。lease必须是Lease，task_id/tenant非空str，worker_epoch严格正int，expires_at严格非负int，否则ValueError("lease_shape")；均在read前检查。随后runtime.read(task_id)，未知任务ValueError("unknown_task")。按顺序拒绝：租户不符tenant_mismatch；expires_at<=now为lease_expired；worker_epoch不符worker_fenced；当前policy.enabled=False为tenant_disabled。拒绝统一返回{"status":"blocked","reason":原因}且不commit。

migrate先检查view.running，活跃旧执行器返回running_requires_old_executor；已v2返回{"status":"unchanged","reason":"already_v2"}；否则调用自己的migrate_state，units=0，成功返回migrated/schema_v2。dispatch要求schema2、status ready，否则ready_required；批准decision须approved且approval.epoch与当前policy.epoch一致，否则approval_stale；再检查global_running>=capacity、tenant_running>=tenant_limit、extensions.units>budget_remaining，依次返回backpressure/tenant_limit/budget_exhausted。有效dispatch深复制快照将status改running，以extensions.units预留。两个成功路径调用runtime.commit(lease, view["policy"]["epoch"], updated, units)；捕获同一CommitConflict返回blocked/str(exc)，成功dispatch返回started/reserved。fixture的运行时初始快照和extensions.units已合法，未知任务之外的畸形运行时存储不在本轮合同范围。

runtime.read返回snapshot、worker_epoch、running、now、policy、global_running、tenant_running、capacity、tenant_limit、budget_remaining。Runtime.commit在同一SQLite事务重核租户、lease、worker代次、当前授权和资源，写状态、预算、账本；每次成功递增worker_epoch。environment_hook在读与提交之间注入撤权、旧worker替换或capacity归零，测试冲突处理；不是实测跨主机竞态。不得直写runtime.db、修改容量、调用external_write或绕开commit。

```python
task = {"id": "a1", "tenant": "A", "units": 3}
principal = {"tenant": "A", "enabled": True}
# expected: {"id": "a1", "tenant": "A", "units": 3}
# task with tenant B: PermissionError("tenant_mismatch")
# units=True: ValueError("input_shape")
```

```python
tasks = [
    {"id": "a1", "tenant": "A", "units": 3},
    {"id": "a2", "tenant": "A", "units": 3},
    {"id": "b1", "tenant": "B", "units": 2},
    {"id": "b2", "tenant": "B", "units": 2},
]
budgets, cursor, slots = {"A": 10, "B": 10}, None, 4
expected = {"selected": ["a1", "b1", "a2", "b2"],
            "cursor": "B", "remaining": {"A": 4, "B": 6}}
```

```python
snapshot = {
    "schema": 1, "id": "r1", "tenant": "A", "status": "waiting",
    "approval": {"tenant": "A", "epoch": 1, "decision": "approved"},
    "budget_used": 2, "operation_key": None,
    "extensions": {"units": 3, "redacted_note": "keep", "nested": {"known": False}},
}
# expected schema=2, status="ready", migration={"from_schema":1,"to_schema":2}
# all other fields unchanged; epoch remains 1, budget_used remains 2
```

```python
import career_student as student
from career_lab import Runtime, Lease
runtime = Runtime(
    states=[{"snapshot": snapshot, "worker_epoch": 1, "running": False}],
    policies={"A": {"epoch": 1, "enabled": True}}, budgets={"A": 10},
    capacity=2, tenant_limit=1, now=10,
)
try:
    first = student.run_step(runtime, Lease("r1", "A", 1, 20), "migrate")
    old = student.run_step(runtime, Lease("r1", "A", 1, 20), "dispatch")
    assert first == {"status": "migrated", "reason": "schema_v2"}
    assert old == {"status": "blocked", "reason": "worker_fenced"}
    assert runtime.audit()["budgets"] == {"A": 10}
    assert runtime.audit()["ledger"] == [
        {"kind": "migrate", "task_id": "r1", "tenant": "A", "units": 0, "epoch": 2}
    ]
finally:
    runtime.close()
```

### 证据与能力边界
公开case为junior 14、intermediate 17、senior 41，共72。grade真实导入并调用本人函数，记录每项input/expected/actual/error及账本审计、学员/源码/cases SHA、Python版本；退出0全部通过，退出1合同失败，CLI缺参数/覆盖模板退出2。异常和非法返回按失败记录；导入或调用时SystemExit/KeyboardInterrupt也失败。父进程核对完整结果包与当前用例、实际值/账本和退出码，不接受自报passed。5秒仅防挂起，不是延迟门槛。固定变输入和负例均公开，不叫隐藏题或未见迁移。

运行时是单进程、内存SQLite、整数逻辑时钟，预算与容量是教学假设。账本reserve表示本地预留，不是外部退款完成；本实验不实现完成结算、资源释放、远端取消、多机共享租约或生产容量测量。取消/本地释放不能撤销未知外部写，真实系统需查询收据并保留operation_key。迁移running任务只给结构映射，run_step保留旧执行器且拒绝切换；恢复/回滚、双读窗口、分布式fencing需另行验证。不要把全绿日志写成生产经验或真实模型质量。

提交本人源码、首次失败报告、个人diff、重跑报告和300字取舍记录，说明用了哪些辅助。公共正确输出是可审阅合同，不是本人独立完成证明。资料：[Python sqlite3](https://docs.python.org/3.9/library/sqlite3.html)、[Python importlib](https://docs.python.org/3.9/library/importlib.html#importlib.util.spec_from_file_location)；具体行为以本实验源码和公开输入为准。

---

### Three programming levels in the after-sales Agent
Junior, intermediate and senior describe progressively stronger local contracts. The four course tracks produce different evidence. Passing fixed public checks is not a job-level or hiring certification. Download the ZIP, extract it and enter agent-career-levels-v1; career_lab.py and career-cases.json must remain together. Python 3.9+, standard library only. Implement progressively in one career_student.py; scaffold refuses overwrites. Regress all three levels after senior changes.
- https://ai.lwkjob.com/lab/career-levels/README.md
- https://ai.lwkjob.com/lab/career-levels/career_lab.py
- https://ai.lwkjob.com/lab/career-levels/career-cases.json
- https://ai.lwkjob.com/downloads/agent-career-levels-v1.zip

```bash
python3 career_lab.py scaffold --out career_student.py
python3 career_lab.py grade --module career_student.py --level junior --out report-junior.json
python3 career_lab.py grade --module career_student.py --level intermediate --out report-intermediate.json
python3 career_lab.py grade --module career_student.py --level senior --out report-senior.json
```

### Independent contracts and authority
JSON arguments and Lease are immutable. run_step may change the supplied runtime only through runtime.commit. Pure-function results must not share dict/list containers with their arguments. JSON types are exact: True is not integer 1. Exception class and message are exact. principal and runtime policy are trusted server facts supplied by the exercise. A submitted task, historical approval or model text cannot grant authority. Import only learner modules you trust; a subprocess hang guard is not a hostile-code sandbox.

validate_task(task, principal): task has exactly id, tenant, units; the first two are nonempty str; units is strict int in 1..100. principal has exactly nonempty str tenant and strict bool enabled. Validate every shape first: ValueError("input_shape"). Then tenant mismatch: PermissionError("tenant_mismatch"). Then disabled: PermissionError("tenant_disabled"). Success returns a deep copy of task. Self-reported enabled fields cannot grant authority.

plan_round(tasks, budgets, cursor, slots): tasks is a list of the above task records with unique IDs; budgets maps nonempty str tenants to strict nonnegative int, and may be empty; cursor is None or nonempty str; slots is strict nonnegative int. Any malformed input raises ValueError("input_shape"). Do not schedule tenants absent from budgets or borrow another tenant's budget. Sort tenant names lexically, start immediately after cursor and wrap. Choose one affordable tenant head, debit planned remaining units, then continue after that selected tenant. Preserve FIFO within each tenant: an unaffordable head blocks its cheap tail. Stop at slots or when no head is affordable. Return exactly selected (ID list), cursor (last selected tenant, unchanged if none), remaining (planned budgets). This is request round-robin with integer estimated cost, not elapsed-time fairness, real token settlement or production quotas.

migrate_state(snapshot): v1 has exactly schema/id/tenant/status/approval/budget_used/operation_key/extensions. schema is strict int; unsupported values other than 1/2 raise ValueError("unsupported_schema"); other shape failures raise ValueError("input_shape"). id/tenant are nonempty str; budget_used is strict nonnegative int; operation_key is None or nonempty str; extensions is a JSON dict preserved through deep copy. approval has exactly matching tenant, strict positive int epoch, and decision pending/approved/denied. v1 statuses are waiting/running/unknown/completed. Map waiting to awaiting_approval/ready/blocked respectively; unknown to reconcile_required; preserve running/completed. unknown/reconcile_required requires operation_key. v2 adds migration={"from_schema":1,"to_schema":2} with strict integers and allows the new statuses plus running/completed. Valid v2 returns unchanged through deep copy. Preserve approval epoch, consumed budget, business key and extensions. Migration creates no business side effect.

run_step(runtime, lease, action): import career_lab.Lease and CommitConflict; legal dataclass/future annotations and canonical exception identity are supported. Check action first: only dispatch/migrate, otherwise ValueError("action"). Require a Lease instance with nonempty str task_id/tenant, strict positive int worker_epoch and strict nonnegative int expires_at, otherwise ValueError("lease_shape"). Both checks precede read. runtime.read(task_id) raises ValueError("unknown_task") for a missing task. Then reject in order: tenant mismatch→tenant_mismatch; expires_at<=now→lease_expired; worker_epoch mismatch→worker_fenced; current disabled policy→tenant_disabled. A rejection returns exactly {"status":"blocked","reason":reason} without commit.

For migrate, reject view.running as running_requires_old_executor; v2 returns {"status":"unchanged","reason":"already_v2"}; otherwise call your migrate_state, units=0, success migrated/schema_v2. For dispatch require schema2/status ready, otherwise ready_required; approval must be approved with epoch equal to current policy epoch, otherwise approval_stale. Then test global_running>=capacity, tenant_running>=tenant_limit, extensions.units>budget_remaining in that order, returning backpressure/tenant_limit/budget_exhausted. Valid dispatch deep-copies the snapshot, changes status to running, and reserves extensions.units. Both committing paths call runtime.commit(lease, view["policy"]["epoch"], updated, units). Catch canonical CommitConflict and return blocked/str(exc). Dispatch success is started/reserved. Runtime initial snapshots and extensions.units in these fixtures are valid; malformed stored runtime state beyond missing tasks is outside this exercise's contract.

runtime.read returns snapshot, worker_epoch, running, now, policy, global_running, tenant_running, capacity, tenant_limit, budget_remaining. Runtime.commit rechecks tenant, lease, worker epoch, current authority and resources in one SQLite transaction before updating state/budget/ledger. Every successful commit increments worker_epoch. environment_hook injects revocation, worker replacement or zero capacity between read and commit; it is deterministic simulation, not measured cross-host concurrency. Do not write runtime.db directly, change capacity, call external_write or bypass commit.

```python
task = {"id": "a1", "tenant": "A", "units": 3}
principal = {"tenant": "A", "enabled": True}
# expected: {"id": "a1", "tenant": "A", "units": 3}
# task with tenant B: PermissionError("tenant_mismatch")
# units=True: ValueError("input_shape")
```

```python
tasks = [
    {"id": "a1", "tenant": "A", "units": 3},
    {"id": "a2", "tenant": "A", "units": 3},
    {"id": "b1", "tenant": "B", "units": 2},
    {"id": "b2", "tenant": "B", "units": 2},
]
budgets, cursor, slots = {"A": 10, "B": 10}, None, 4
expected = {"selected": ["a1", "b1", "a2", "b2"],
            "cursor": "B", "remaining": {"A": 4, "B": 6}}
```

```python
snapshot = {
    "schema": 1, "id": "r1", "tenant": "A", "status": "waiting",
    "approval": {"tenant": "A", "epoch": 1, "decision": "approved"},
    "budget_used": 2, "operation_key": None,
    "extensions": {"units": 3, "redacted_note": "keep", "nested": {"known": False}},
}
# expected schema=2, status="ready", migration={"from_schema":1,"to_schema":2}
# all other fields unchanged; epoch remains 1, budget_used remains 2
```

```python
import career_student as student
from career_lab import Runtime, Lease
runtime = Runtime(
    states=[{"snapshot": snapshot, "worker_epoch": 1, "running": False}],
    policies={"A": {"epoch": 1, "enabled": True}}, budgets={"A": 10},
    capacity=2, tenant_limit=1, now=10,
)
try:
    first = student.run_step(runtime, Lease("r1", "A", 1, 20), "migrate")
    old = student.run_step(runtime, Lease("r1", "A", 1, 20), "dispatch")
    assert first == {"status": "migrated", "reason": "schema_v2"}
    assert old == {"status": "blocked", "reason": "worker_fenced"}
    assert runtime.audit()["budgets"] == {"A": 10}
    assert runtime.audit()["ledger"] == [
        {"kind": "migrate", "task_id": "r1", "tenant": "A", "units": 0, "epoch": 2}
    ]
finally:
    runtime.close()
```

### Evidence and limits
There are 14 junior, 17 intermediate and 41 senior public checks, 72 total. grade imports and calls the learner's functions, records each input/expected/actual/error, audited state, learner/source/cases SHA and Python version. Exit0 means all selected contracts pass; exit1 is failure; missing CLI arguments or scaffold overwrite exit2. Exceptions and invalid return types fail, including SystemExit/KeyboardInterrupt during import or calls. The parent binds the complete packet to the current case, actual values/ledger and process exit; a claimed passed flag is insufficient. The five-second limit only detects hung workers, not latency. Changed inputs and negative cases are public, not hidden tests or unseen transfer.

This is one process with in-memory SQLite and an integer logical clock. Budgets/capacity are teaching assumptions. A reserve ledger entry is local reservation, not a completed external refund. Completion settlement, resource release, remote cancellation, multi-host shared leases and production capacity measurements are not implemented. Local cancellation/release cannot undo an unknown external write; a real system needs receipt reconciliation and a preserved operation_key. Pure migration maps running structurally; run_step retains the old executor and refuses switching it. Recovery/rollback, dual-read windows and distributed fencing need separate validation. Green fixed checks cannot be reported as production experience or real model quality.

Submit your source, first failed report, personal diff, rerun report and a 300-word tradeoff note, disclosing assistance. Published expected outputs make the contract reviewable; they are not proof of independent authorship. Sources: [Python sqlite3](https://docs.python.org/3.9/library/sqlite3.html), [Python importlib](https://docs.python.org/3.9/library/importlib.html#importlib.util.spec_from_file_location). Actual behavior is defined by this source and its public inputs.

## Files and packaging · 文件与打包

career_lab.py 提供存储kernel、合法模块导入和grader，不提供四个学员函数答案。career-cases.json 是全部公开固定输入及预期。README.md 为双语合同。package.py 仅打包明确允许的4个公开源文件与PACKAGE_MANIFEST.json元数据（root/version/minimum_python与四源SHA，manifest不自哈希）；不包含私有校准解法、报告、学员文件或缓存。

career_lab.py provides the storage kernel, lawful module loading and grader, without the four learner solutions. career-cases.json contains every public fixed input/expectation. README.md defines bilingual contracts. package.py includes exactly four allowlisted public sources plus PACKAGE_MANIFEST.json metadata (root/version/minimum_python and the four source SHA values; no self-hash); private solutions, reports, learner files and caches are excluded.

```bash
python3 package.py --out agent-career-levels-v1.zip
```
