Review the prerequisites
Suitable for: Backend developers learning Agent applications.
- Transfer responsibility and permissions during task handoff
- The handover conveys the facts and responsibilities needed to complete the work without transferring the authority that was added out of thin air. The previous Agent's statement is still input data, and the identity and approval come from a trusted system; the end of the parent process does not mean that the business is completed, and there must be a clear follow-up responsible person.
How does the mechanism work?
Step-by-step explanation
- If the subtask fails after the parent Agent ends, who notifies the user?
A handoff needs ownership and liveness boundaries beyond a conversational message.
- How is the user's cancellation midway transmitted?
With distributed responsibilities, local stopping is insufficient; task cancellation needs consistent semantics.
- Why can't all historical conversations be copied?
Context isolation not only saves tokens, but also makes responsibility boundaries checkable.
Design · Explain the trade-offs
Changed constraints and integration decision
Objectives of this level: handoff acceptance, current receipt access and original effect identity — Apply a changed constraint and scope the proposed platform adapter.
Visual guide · Acceptance transfers work
This is a responsibility contract, not an executed distributed handoff. Current receipt-read access and exact receipt binding remain required. Select the figure to open it at full size.
Changed constraints and integration decision
Remove return_apply but keep receipt_read from both action lists. Without receipt deny/capability; with a matching applied receipt completed/trusted_receipt even after deadline. Design an asynchronous owner/acknowledgement/retry/cancellation contract separately. This pure decision creates no durable child task and cannot stop or compensate remote work. Deliver a new-input JSON/result pair, an adapter boundary sketch and a short ADR comparing two alternatives, rejection/reconciliation behavior, ownership and reversal conditions. State implemented_local versus planned; connect to the same after-sales proposal/approval/merchant/receipt chain without inventing existing runtime features. Save the following block as agent_handoff_contract_variants.py beside your student module, then run it after implementation. It imports your own function, reads the public complete inputs and changes the declared fields; these two rule-visible variants are not unseen assessment.
import copy, json
from pathlib import Path
from agent_handoff_contract_student import check_handoff
checks = json.loads(Path("cases/agent-handoff-contract.json").read_text())["checks"]
payload = copy.deepcopy(checks[1]["input"])
payload["now"] = payload["envelope"]["deadline"]
before = copy.deepcopy(payload)
try:
actual = check_handoff(payload)
except ValueError as exc:
actual = "ValueError:" + str(exc)
assert payload == before, "input_mutation"
expected = {'status': 'completed', 'reason': 'trusted_receipt', 'operation_key': 'return-7-op'}
assert actual == expected, (actual, expected)
print(json.dumps({"variant":1,"input":payload,"actual":actual}, sort_keys=True))
payload = copy.deepcopy(checks[0]["input"])
payload["now"] = payload["envelope"]["deadline"]
before = copy.deepcopy(payload)
try:
actual = check_handoff(payload)
except ValueError as exc:
actual = "ValueError:" + str(exc)
assert payload == before, "input_mutation"
expected = {'status': 'denied', 'reason': 'deadline', 'operation_key': 'return-7-op'}
assert actual == expected, (actual, expected)
print(json.dumps({"variant":2,"input":payload,"actual":actual}, sort_keys=True))
python3 agent_handoff_contract_variants.py
Starting point and evidence
Download the source-only ZIP, extract it, and work in extended-agent-practice-v1 with lab_runner.py beside cases/. Python3.9+ standard library; no model, cloud, network or business request is made. Scaffold once in a fresh directory; it refuses overwrite. Reuse your module in later tracks. The empty template must exit1 on grade; scaffold exits0, overwrite exits2. Grade exits0 only when every fixed case passes and otherwise exits1.
- https://ai.lwkjob.com/downloads/extended-agent-practice-v1.zip
- https://ai.lwkjob.com/lab/extended-practice/lab_runner.py
- https://ai.lwkjob.com/lab/extended-practice/cases/agent-handoff-contract.json
python3 lab_runner.py scaffold --course agent-handoff-contract --out agent_handoff_contract_student.py
python3 lab_runner.py grade --course agent-handoff-contract --module agent_handoff_contract_student.py --out agent_handoff_contract_before.json
This course has12 public fixed cases. Each calls your check_handoff(payload), records input/expected/actual/error, strict JSON types, input immutability and no output-container aliases, plus module/runner/cases SHA and Python version. Inputs are complete JSON fixtures. Unknown or missing keys, null outside explicitly allowed fields, wrong types, duplicate IDs/list members where uniqueness is required raise ValueError:input_shape; booleans are not integers. Exceptions match exact class:message. Return fresh JSON values without mutating input.
Trusted identity, approvals, receipts and policy/index metadata are fixtures assembled by the exercise. In a real service the server must obtain them from authenticated/current authority sources; accepting client JSON with these labels does not authenticate it. The function is a decision over that trusted snapshot, not the adapter or race-proof enforcement.
Local function contract
payload exactly envelope/principal/receiver/now/max_hops/receipt. envelope exactly task_id/parent_id/tenant/order_id/operation_key/requested_action(nonempty str),deadline/hops(strict nonnegative int). principal exactly tenant(nonempty str),enabled(strict bool),actions(unique nonempty str list); receiver exactly actions with the same list rule. now/max_hops are strict nonnegative int, max_hops0 allows no new handoff. receipt is None or exactly task_id/tenant/order_id/operation_key(nonempty str),status(applied/rejected/unknown), representing an independently trusted fixture. Validate shapes first; then principal_disabled,tenant_mismatch. If receipt exists, require receipt_read in BOTH action lists or deny/receipt_permission, then exact binding of all four IDs or deny/receipt_binding; applied returns completed/trusted_receipt,unknown reconcile/unknown_effect,rejected denied/effect_rejected. Existing receipts are assessed before deadline/hops/write permission: those cannot erase an already applied effect. Without receipt reject deadline<=now as deadline, hops>=max_hops as hop_limit, requested action absent from either list as capability; otherwise accepted/handoff_only. All outputs exactly status/reason/operation_key(original key), no null output fields.
def check_handoff(payload):
raise NotImplementedError("Implement the public local contract")
Three reviewable inputs
accepted-not-completed
{
"envelope": {
"task_id": "return-7",
"parent_id": "support-7",
"tenant": "acme",
"order_id": "O-7",
"operation_key": "return-7-op",
"deadline": 20,
"hops": 0,
"requested_action": "return_apply"
},
"principal": {
"tenant": "acme",
"enabled": true,
"actions": [
"return_apply",
"receipt_read"
]
},
"receiver": {
"actions": [
"return_apply",
"receipt_read"
]
},
"now": 10,
"max_hops": 2,
"receipt": null
}
Expected / 预期: {"operation_key": "return-7-op", "reason": "handoff_only", "status": "accepted"}
applied-receipt
{
"envelope": {
"task_id": "return-7",
"parent_id": "support-7",
"tenant": "acme",
"order_id": "O-7",
"operation_key": "return-7-op",
"deadline": 20,
"hops": 0,
"requested_action": "return_apply"
},
"principal": {
"tenant": "acme",
"enabled": true,
"actions": [
"return_apply",
"receipt_read"
]
},
"receiver": {
"actions": [
"return_apply",
"receipt_read"
]
},
"now": 10,
"max_hops": 2,
"receipt": {
"task_id": "return-7",
"tenant": "acme",
"order_id": "O-7",
"operation_key": "return-7-op",
"status": "applied"
}
}
Expected / 预期: {"operation_key": "return-7-op", "reason": "trusted_receipt", "status": "completed"}
effect-survives-deadline
{
"envelope": {
"task_id": "return-7",
"parent_id": "support-7",
"tenant": "acme",
"order_id": "O-7",
"operation_key": "return-7-op",
"deadline": 10,
"hops": 0,
"requested_action": "return_apply"
},
"principal": {
"tenant": "acme",
"enabled": true,
"actions": [
"receipt_read"
]
},
"receiver": {
"actions": [
"receipt_read"
]
},
"now": 10,
"max_hops": 2,
"receipt": {
"task_id": "return-7",
"tenant": "acme",
"order_id": "O-7",
"operation_key": "return-7-op",
"status": "applied"
}
}
Expected / 预期: {"operation_key": "return-7-op", "reason": "trusted_receipt", "status": "completed"}
Responsibility and limits
Junior codes envelope validation and distinguishes accepted/completed/reconcile. Intermediate would integrate a trusted child endpoint and independently fetched receipts, preserve keys across retries and record ownership. Senior specifies durable task lifecycle, scoped external handoff, cancellation-after-commit and recovery responsibility. None of those distributed mechanisms is executed by this pure function. The four tracks are learning activities, not job ranks. Fixed authored examples and known repairs cannot prove independent diagnosis, real-world security or hiring readiness. Keep source, initial failure, personal diff, same-input rerun and a declared changed-condition result. A reviewer-new complete contract and observed personal work are separate; disclose assistance. The five-second worker guard is not a performance SLO or hostile-code sandbox.
Cross-business handoff: a ticket approval cannot be copied forward
Implement prepare_handoff in the independent ticket task and follow its actual call from Workflow.step(senior=True). Download https://ai.lwkjob.com/downloads/agent-workorder-transfer-v1.zip, complete junior/intermediate functions, then run python3 verify.py --learner my_workorder.py --level senior --out work/after-senior.json.
Saved state preserves original ticket/tenant/key/digest and versions; view comes from current tool authority, while approval is a fixture simulating an external human decision. Validate shapes first, then current identity, grant and worker epochs, customer confirmation/ticket version, intent and approval in the specified order. A new policy, grant or worker requires a separately authorized handoff; silently rewriting old fields is not approval. The logical expiry boundary expires_at==now is expired.
Among cumulative 54 senior checks, pre-handoff worker/grant/policy/approval changes must stop before a close request. A revocation or worker change after client validation must still fail in the authority's transaction. Two actual concurrent same-key HTTP writes produce one effect/receipt; rebinding that key to another intent conflicts. Inspect call events and the independent ledger, not just returned objects.
Submit your diff, positive/negative evidence, both stores, first-divergence diagnosis and an ADR; retain original regression. This validates local thread concurrency, SQLite transactions and fencing, not distributed locks, cross-host capacity or a real human-review identity system. Record public practice separately from senior employment responsibility; a fresh observed condition still needs a complete reviewer-specified contract.
code example
Changed constraints and integration decision — effect-survives-deadline
Additional review: explain why this case follows the contract and which single-field change would alter the branch. Public case: effect-survives-deadline Expected / 预期: {"operation_key": "return-7-op", "reason": "trusted_receipt", "status": "completed"} https://ai.lwkjob.com/lab/extended-practice/cases/agent-handoff-contract.json
Acceptance task for this level
handoff acceptance, current receipt access and original effect identity — Execute the declared changed inputs and deliver result pairs plus an adapter/ADR with implemented versus planned boundaries.
Reading this browser’s record…
Hide the answer and check your understanding
Does this exercise provide a durable background agent?
Expand reference derivation
No. It provides a bounded envelope/receipt decision; persistence, delivery and cancellation are separate work.
Further explanations and practice
When encountering unfamiliar principles, first read the implementation, continuous questioning and migration cases, and then independently explain the premise and boundaries. Answers and notes are saved to the original account record.
All linked explanations and exercises (1 )
Sources and verification scope
The principles are based on public information; the numbers, cases and tasks are the teaching design of this website. Offline experiments verify the range noted on this page, and the learning effect still needs to be judged through independent tasks and feedback.
- Anthropic: Design experience for multi-agent research systems
- MCP:Security best practices
- OpenAI Agents SDK: Run Loops and Maximum Rounds
- Extended practice runner and source ZIP
- Pure-function public contract
- Actual learner-module grader
- Enterprise ticket transfer: complete independent contracts
- Enterprise ticket transfer source package