# Exercises: keep the failure, repair the boundary, rerun the check

[README](README.md) · [中文练习](EXERCISES.zh.md) · [Storage walkthrough](WALKTHROUGH.md#storage-map)

There are two kinds of work here. The eight named scenarios are authored diagnostic probes: correct code rejects the unsafe action, then continues the same `journey-return` recovery. The settlement starter is deliberately incomplete code for you to repair at an actual runtime boundary. Neither is an unseen learner assessment. All model events are offline fixtures; no provider calls occur.

<a id="settlement-repair"></a>

## 1. Preserve the red learner baseline

Copy the learner file outside the released source directory so that editing your answer does not alter release source fingerprints. These example `/tmp` names must not already contain work you need.

```sh
cp settlement_student.py /tmp/journey-settlement.py
python3 -B journey.py grade --work /tmp/journey-starter --student /tmp/journey-settlement.py
cp /tmp/journey-starter/report.json /tmp/journey-starter-red.json
python3 -B journey.py verify --work /tmp/journey-starter
python3 -B journey.py inspect --work /tmp/journey-starter --task-id journey-return
```

Expect grade exit 1 and verify exit 1. Find `learner_error.boundary=actual_unknown_settlement` and `NotImplementedError` in the saved report. The child already crossed the merchant boundary before the supervisor invoked the missing function. Inspect `returns`/`receipts`, `rt_tasks.reservation_id`, `rt_budget.reserved` and Agent `receipt_json`; a missing local receipt is not absence of a merchant effect. The failed hook leaves the original hold in place. Runtime state can still be `leased` because the hook failed before recording its `hold` decision; workflow state already records unknown.

First-break diagnosis: this failure comes from the unimplemented settlement function, not a missing Python package, model API key, or bad HTTP setup. Read the saved child exit and authoritative receipt before changing setup.

## 2. Implement the exact policy

Implement `decide_settlement(payload)` in `/tmp/journey-settlement.py`. Input is an exact dictionary with `reserved_units`, `actual_units`, `evidence`. Reject invalid input with `ValueError('invalid_settlement_input')`; do not mutate the payload. Strict integer checks must reject booleans. Reserved units must be at least 1. Evidence must be one of the three strings below. Actual units must be `None` except for `confirmed_receipt`, which requires a nonnegative strict integer.

| Evidence / condition | Exact return fields |
| --- | --- |
| `unknown` | `{'action':'hold','charge_units':0,'release_units':0}` |
| `confirmed_absent` | `{'action':'release','charge_units':0,'release_units':reserved_units}` |
| `confirmed_receipt`, actual ≤ reserved | `{'action':'settle','charge_units':actual_units,'release_units':reserved_units-actual_units}` |
| `confirmed_receipt`, actual > reserved | `{'action':'overrun','charge_units':actual_units,'release_units':0}` |

The runtime establishes evidence before this callback: receipt equality with merchant authority, confirmed absence under the fenced write lock, and confirmed usage from `rt_costs`. The callback chooses accounting, not whether a JSON object is authentic. Unknown cannot release capacity. Overrun keeps the hold and freezes the tenant for reconciliation; it does not borrow another tenant's budget. The grade checks overrun as a pure public contract case. The main HTTP route exercises 5 reserved → 3 confirmed units, not an actual overrun.

For an openly reference-assisted repair, inspect [settlement_reference.py](settlement_reference.py), then copy it to the learner path:

```sh
cp settlement_reference.py /tmp/journey-settlement.py
python3 -B journey.py resume --work /tmp/journey-starter --student /tmp/journey-settlement.py
python3 -B journey.py verify --work /tmp/journey-starter
python3 -B journey.py grade --work /tmp/journey-repaired --student /tmp/journey-settlement.py
```

Resume and verify should exit 0 after a correct repair; a full repaired grade should also exit 0. The verify command is exactly the one used on the red ledger. The fresh repaired grade changes only the work directory; the module path, grader, contract cases and storage checks remain the same. Retain `/tmp/journey-starter-red.json` as the baseline. Reference copying is a guided demonstration; for your own submission, implement the function before reading the reference.

## 3. Run each diagnostic on a fresh ledger

Use `python3 -B journey.py scenario --name NAME --work /tmp/journey-NAME` with one of the exact names below. Each normal scenario exits 0 only after its expected rejection/observation and the complete return recovery. Inspect its `report.json` and run `verify` on that same directory. Each subsection gives the diagnostic input, expected evidence, first-break question, implementation location and checks that must remain unchanged.

<a id="fair-queue"></a>

### Tenant scheduling

**Input:** `fair_queue` creates a separate `fair-fixture.sqlite` with `a1,a2` for acme and `b1,b2` for other, using one held slot. **Evidence:** actual admissions `a1,b1,a2,b2`, cursor preserved after reopening, and no admissible task while a hold occupies the slot. Read `fair_queue.rounds` in the scenario report for each round's `before`, `held`, `settled` and `reopened` snapshots. This fixture uses the same `Workflow.acquire_next()` as the main task; the four scheduler tasks do not each execute merchant returns.

**Diagnosis:** compare persisted cursor and actual holds before interpreting order. A schedule printout does not reserve capacity. Read `workflow.py:Workflow.acquire_next`, `runtime.py:Runtime.acquire` and `rt_tasks`/`rt_budget`. **Repair target:** tenant FIFO heads, rotation and atomic reserve/cursor commit, with current permission/capacity/budget rechecks. **Unchanged checks:** unknown retains its original hold; main return has one admission and one settlement. This fixture does not establish arbitrary workload fairness or measure time/cost fairness.

<a id="replay-conflict"></a>

### Old event and conflicting identity

**Input:** `replay_conflict` redelivers the original ready event after executing, then changes its body, reuses its sequence under another identity and submits a new backward transition. **Evidence:** identical delivery returns the original ready receipt while the current snapshot remains executing; errors are `event_conflict`, `sequence_conflict`, `status_transition` for the respective invalid probes.

**Diagnosis:** distinguish a delivery acknowledgment from a new transition; compare `event_id`, digest, `seq`, current cursor and receipt. **Repair target:** `workflow.py:Workflow.apply`; identity lookup precedes new-transition validation, and snapshot/cursor/event/receipt commit together. **Unchanged checks:** event history remains contiguous and the final completion requires runtime settlement. A replay receipt cannot prove or undo a merchant effect.

<a id="migration-rollback"></a>

### Interrupted semantic upgrade

**Input:** `migration_rollback` aborts the v1→v2 update with an authored SQLite trigger. **Evidence:** the old snapshot and runtime epoch remain unchanged after the abort; the later successful upgrade preserves operation key, approval epoch, budget-used and extensions, retains the reservation and is idempotent. The normal route also rejects live-worker migration with `migration_live_worker`.

**Diagnosis:** inspect both workflow and runtime rows; “v2 can be read” is too weak. **Repair target:** `workflow.py:Workflow.migrate`, one transaction for both tables, explicit semantic mapping and fencing. **Unchanged checks:** no new reservation, original approval and business identity survive, and the final merchant receipt remains singular. This is not a deployment rollback experiment.

<a id="stale-worker"></a>

### Old worker after migration

**Input:** `stale_worker` reuses the old claim at the actual HTTP return endpoint and at settlement after migration. **Evidence:** both are rejected as `runtime_stale_claim`. **Diagnosis:** compare epoch, worker, reservation and expiration with current `rt_tasks`, then inspect the merchant boundary rather than only local helper checks.

**Repair target:** `merchant_runtime.py` and `Runtime.assert_claim`, enforced in the same authority transaction as the write. **Unchanged checks:** rejecting an old writer does not delete the earlier committed receipt; a new worker still reconciles it. The runtime and merchant share one local SQLite authority file.

<a id="fallback-blocked"></a>

### Forbidden fallback

**Input:** `fallback_blocked` probes permission denial, refusal, permanent 400, missing tools capability, boolean/exhausted allowance and deadline overflow. **Evidence:** `fallback_forbidden`, `fallback_capability_missing`, `fallback_invalid_budget`, `fallback_budget_exhausted` or `fallback_deadline_exceeded`, as applicable. Unknown selects `reconcile_original_key`.

**Diagnosis:** check business write/receipt state first, then failure classification, capabilities and bounds. **Repair target:** `fallback.py:route` and `ScriptedModel.respond`; preserve the actual Agent request/facts, switch once, then keep normal bounded backup turns. **Unchanged checks:** no model/write attempt is introduced for unknown; model-attempt sources stay `offline_fixture`. The wait is a simulated unit, not provider Retry-After or measured latency.

<a id="evidence-missing"></a>

### Missing selected proof

**Input:** `evidence_missing` submits a well-shaped ordinary proposal citing only `d-general`, although retrieval contains `d-proof`. **Evidence:** `missing_policy_evidence`, no accepted bad proposal; the later valid candidate follows the usual approval path. **Diagnosis:** distinguish retrieved candidates, selected context and the candidate's actual policy IDs before editing a validator.

**Repair target:** `project/evidence_contract.py` and `project/agent.py`; retain decision-specific evidence/authority checks and real proposal-tool receipt. **Unchanged checks:** valid JSON and model prose cannot claim business completion; ordinary proposals still require general+proof. This exercise creates a fictional return request, never a refund.

<a id="forged-receipt"></a>

### Plausible but unconfirmed receipt

**Input:** `forged_receipt` hands settlement a JSON object containing the operation key without a matching authoritative receipt. **Evidence:** `runtime_receipt_unconfirmed`, no settlement from that object. **Diagnosis:** compare full receipt equality and task/tenant/owner/order/quantity/proposal binding with the merchant ledger; checking only a status string or key is insufficient.

**Repair target:** `runtime.py:Runtime.settle`, `project/agent.py` receipt checks and `acceptance.py`. **Unchanged checks:** usage must match `rt_costs`, final receipt agrees across ledgers and no extra business effect occurs.

<a id="lost-response"></a>

### Lost committed response

**Input:** `lost_response --stop-after-unknown` commits the merchant return, drops the response and crashes the child. **Evidence:** child exit 75, merchant receipt present, local receipt absent, unknown hold retained; the stop command exits 0 but independent verify exits 1. **Diagnosis:** separate transport observation from business fact.

**Repair target:** operationally run `resume` against the same work/key; implementation points are `Agent.execute`, workflow migration, recovery acquire and settlement. **Unchanged check:** run the exact same `python3 -B journey.py verify --work /tmp/journey-stop` before and after resume. Expect final exit 0 with the original key, one effect and one reservation/settlement.

<a id="tamper-check"></a>

## 4. Prove the verifier does not trust a green report

After the README demo has completed, alter a copy, not your preserved evidence:

```sh
python3 - <<'PY'
import json, shutil, sqlite3
from pathlib import Path
source, target = Path('/tmp/journey-demo'), Path('/tmp/journey-tamper')
shutil.copytree(source, target)
p = target / 'report.json'
report = json.loads(p.read_text())
report['passed'] = True
p.write_text(json.dumps(report))
db = sqlite3.connect(target / 'shared.sqlite')
db.execute("UPDATE rt_tasks SET actual_units=0 WHERE id='journey-return'")
db.commit()
db.close()
PY
python3 -B journey.py verify --work /tmp/journey-tamper
```

Expect exit 1 despite the green report; the storage-derived reservation/usage checks must fail. Restoring only the report is not a repair. Rebuild a fresh run from unchanged source, or restore an explicitly preserved database copy with its scope documented. Do not overwrite frozen public evidence.

## Evidence to submit

Keep the red report, repaired module hash, exact commands/exits, before/after storage observations and unchanged verifier output. Explain the first failed boundary and one rejected alternative hypothesis. Link the [published guided evidence](https://ai.lwkjob.com/research-evidence/harness-journey/README.md) as a reference, not as proof of your own run. Passing the supplied cases establishes the declared local contract; it does not certify production behavior, model quality or hiring level.
