interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

Run verified CPU jobs from the Spark on another machine (first cut)

closed dbc983cc5d336118 #662 · opened 2026-10-18 17:45 UTC · closed 2026-10-29 19:00 UTC

Imported from GitHub aien-dev/aien-sovereign-core-mv#662, by drakestapleton

Base e6852de85dfe503347d37ed2438d1ce6f1ac8c3a · Head 3606d0411991d65304e17124343e52b669e9bb82

drakestapleton wrote on 2026-10-18 17:45 UTC

What this adds

aien-hetjob: the Spark sends an allowlisted CPU job to another machine, the worker runs it and signs a receipt with its pinned key, and the Spark verifies the receipt and checks the answer against its own recompute. First cut of #637 (parent aienix#6).

  • Wire: PST1 frames (aien-protocols specs/pi-spark-task, crate aien-pi-spark-task), at most 1024 bytes each. The Spark sends request and cancel_request; the worker answers accepted, running, the receipt as text_chunks, receipt_reference, then completed, or failed / cancelled.
  • Jobs: matmul_u32 and digest_chain. Both are integer-exact with frozen golden digests, so x86_64 and aarch64 must agree bit for bit. Nothing else runs (DENIED_TASK); there is no remote shell.
  • Trust: the receipt is self-attested (ed25519 verify_strict, pinned roster, exact schema). The Spark trusts its own recompute; the matrix product is recomputed with a different loop order.
  • Limits: memory and work are checked by admission arithmetic before anything is allocated. The OS enforces only CPU seconds (RLIMIT_CPU) and no core dumps. A durable idempotence store (synced and renamed before completed), a flock with one worker per state folder, and a coordinator-owned deadline (cancel, grace, then UNCERTAIN).
  • Transport: SSH with a pinned host key and a forced-command key that can only start aien-hetjob serve.

Evidence

Real hardware, Spark to a MacBook Air M2 over the tailnet (RESULTS.md):

JobOutcomeM2 claimedSpark same algorithm
matmul 512³VERIFIED9.034 ms8.538 ms
matmul 1024³VERIFIED87.748 ms54.984 ms
digest_chain 10MVERIFIED1741.9 ms1178.2 ms

Exact retry replays the stored receipt. Wrong peer is REJECTED WRONG_PEER, over budget is refused before allocation, a reused key is DUPLICATE_ID, and a deadline gives CANCELLED in 2.0 s. The iMac is NOT_RUN (it runs the lab image and has no hosted OS). Energy: not measured. The Spark recomputes every output, so this verifies remote execution; it does not offload work yet.

Tests: cargo test -p aien-hetjob 16/16 on the Spark and the M2. Clippy is clean. Four mutation checks (verify_strict, oracle compare, stale counter, memory admission) each turn a test red. Preflight shows two failures outside this crate: #661 (browser mirror, on main) and a branch-name test that was fixed by renaming this branch.

Before merge

  • aien-protocols #36 then #37 merge; bump the aien-pi-spark-task git rev here from cc35d06 to the merged commit.
  • Cut 2 (a useful workload: batch tokenization with our own BPE) follows in its own PR.

Refs #637

🤖 Generated with Claude Code

drakestapleton wrote on 2026-10-29 19:00 UTC

Closing in org cleanup (Drake, 2026-10-29): abandoned; no activity in 11 days and merge conflicts with main. Reopen if still needed.

Apply it

git checkout -b patch-dbc983cc5d336118 e6852de85dfe503347d37ed2438d1ce6f1ac8c3a
curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/dbc983cc5d336118.patch | git am

Raw patch (mbox) · Diff

Provenance

This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record:

github-import 1
aien-dev/aien-sovereign-core-mv
662
3606d0411991d65304e17124343e52b669e9bb82
{"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":662,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/662","export_sha256":"d815604dc795b494a931d4c9d256159461266bed51d6da460421ed1d94dab90f","imported_utc":"2026-11-18T16:35:49Z"}

Changes

diff --git a/.crumb b/.crumb
index f5e6e78e..c93eed67 100644
--- a/.crumb
+++ b/.crumb
@@ -119,14 +119,14 @@
         }
       ],
       "children_root": "sha256:b85c8810abe85be616a42d2802e5637c38014f05e3c06d23705fef6ea5a766f2",
-      "compiled_at": "2026-10-18T15:37:23Z",
+      "compiled_at": "2026-10-18T18:17:57Z",
       "compiler": "crumb-compile/1",
-      "digest": "sha256:2dbc3bfc48f62db17b27a04f0fd028ee3ad19f77af8d9cac6f93d3e77d147f7b",
-      "evidence_files": 1578,
-      "evidence_root": "sha256:135e27a1a0704c4a8371cd2c1eb555f2b5beec61c212949b029a5457418a7160",
-      "files": 5891,
-      "generated_at_commit": "6b58967d3b40455d5180fa7f22237f0b46912b98",
-      "source_tree": "sha256:1769c5da9a48ba6c23bc738850153c93581c418175c8ef5ac9e31926c116dfb0"
+      "digest": "sha256:c4260b8cc00d572edfa8cc7e5506892a42300ce06c3495ba32b1b072cdf61371",
+      "evidence_files": 1592,
+      "evidence_root": "sha256:dd834f70bfdb3f67de9ed0bfb206f2d496e51c0b4e2f4e3afd29410ac6d872f1",
+      "files": 5917,
+      "generated_at_commit": "8614d32bf2ae8e068e0ae0f596fa25c28c1a63df",
+      "source_tree": "sha256:9880b5bd612e0bf4511c8a7187efffbb88693eff9fa8fea9a89553792675c709"
     }
   },
   "history": [],
diff --git a/Cargo.lock b/Cargo.lock
index b89eff65..697d4a27 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -167,6 +167,18 @@ dependencies = [
  "uuid",
 ]
 
+[[package]]
+name = "aien-hetjob"
+version = "0.1.0"
+dependencies = [
+ "aien-pi-spark-task",
+ "aien-test",
+ "ed25519-dalek",
+ "libc",
+ "serde_json",
+ "sha2 0.10.9",
+]
+
 [[package]]
 name = "aien-inference-abi"
 version = "0.1.0"
@@ -362,6 +374,14 @@ dependencies = [
  "tokenizers",
 ]
 
+[[package]]
+name = "aien-pi-spark-task"
+version = "0.1.0"
+source = "git+https://github.com/aien-dev/aien-protocols?rev=81b7d75f340a75ad468a241d152315fb5ef7c1a6#81b7d75f340a75ad468a241d152315fb5ef7c1a6"
+dependencies = [
+ "sha2 0.10.9",
+]
+
 [[package]]
 name = "aien-platform"
 version = "0.1.0"
diff --git a/Cargo.toml b/Cargo.toml
index 52ca9775..ed97aea0 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -22,6 +22,7 @@ members = [
     "crates/spark-aegis",
     "crates/aien-inference-abi",
     "crates/aien-kv-cache",
+    "crates/aien-hetjob",
     "crates/aien-kv-store",
     "crates/aien-scheduler",
     "crates/aien-security",
diff --git a/crates/aien-hetjob/Cargo.toml b/crates/aien-hetjob/Cargo.toml
new file mode 100644
index 00000000..0f9cc1d8
--- /dev/null
+++ b/crates/aien-hetjob/Cargo.toml
@@ -0,0 +1,22 @@
+[package]
+name = "aien-hetjob"
+version = "0.1.0"
+edition = "2021"
+license.workspace = true
+description = "Allowlisted, integer-exact CPU jobs dispatched over PST1 to a hosted worker machine, with worker-signed receipts and an independent recompute on the coordinator (aien-sovereign-core#637)"
+
+[dependencies]
+# PST1 header reader and writer, pinned to the aien-protocols-mv main commit
+# that merged #37.
+aien-pi-spark-task = { git = "https://github.com/aien-dev/aien-protocols", rev = "81b7d75f340a75ad468a241d152315fb5ef7c1a6" }
+# Key files, executor fingerprints and canonical signed bytes are reused from
+# the local verification worker (ADR 0033 Decision 6); the bundle schema is not.
+aien-test = { path = "../../tools/aien-test" }
+ed25519-dalek = { version = "2.1", default-features = false, features = ["fast", "zeroize"] }
+libc = "0.2"
+serde_json = "1.0"
+sha2 = "0.10"
+
+[[bin]]
+name = "aien-hetjob"
+path = "src/main.rs"
diff --git a/crates/aien-hetjob/README.md b/crates/aien-hetjob/README.md
new file mode 100644
index 00000000..1645d0e6
--- /dev/null
+++ b/crates/aien-hetjob/README.md
@@ -0,0 +1,41 @@
+# aien-hetjob
+
+Runs allowlisted CPU jobs on another machine and checks the answer. The Spark (coordinator) sends a job to a hosted worker (today: an M2 MacBook over SSH); the worker runs it, signs a receipt with its own pinned key and stores it; the Spark verifies the receipt and compares the result with its own recompute. Issue: aien-sovereign-core#637, parent aienix#6.
+
+Status 2026-10-18: cut 1. Shown on real hardware from the Spark to the M2: [evidence/het637-m2-20261018/RESULTS.md](evidence/het637-m2-20261018/RESULTS.md). The iMac is NOT_RUN (no hosted OS). No useful workload yet (cut 2).
+
+## What a worker will run
+
+Only these kinds, integer-exact so every architecture gives the same bits (frozen digests in `tests/protocol_tests.rs`):
+
+| Kind | Job | Admission |
+|---|---|---|
+| `matmul_u32` | C = A x B over wrapping u32, A and B generated from a seed; result = sha256 of C | memory 4(mk + kn + mn) bytes and m*k*n multiply-adds against the limits |
+| `digest_chain` | sha256 applied N times to a 32-byte seed | N against the work limit |
+
+Anything else is refused (`DENIED_TASK`). There is no remote shell and no command line from the peer.
+
+## Wire
+
+PST1 (aien-protocols `specs/pi-spark-task`, crate `aien-pi-spark-task`), one message per frame, each frame a u16 length plus at most 1024 bytes. The Spark sends `request` and `cancel_request`; the worker answers `accepted`, `running`, the receipt as `text_chunk` messages, `receipt_reference` (sha256 of the receipt), then `completed` (the output digest), or `failed` / `cancelled`. PST1 Draft v0.1 calls the requester side "Pi"; here the Spark is the requester, and every worker status is a hint the Spark checks.
+
+## Trust and limits, stated plainly
+
+- Receipt: self-attested. The signature says which pinned key made the claim; the platform, program digest and timings are the worker's claims. The Spark trusts its own recompute.
+- Transport: SSH with a pinned host key, and a dedicated key whose `authorized_keys` line is `command="aien-hetjob serve --state ...",restrict`, so the key can only start the worker.
+- Ceilings: memory and work are admission arithmetic checked before allocation, not a kernel limit. The OS enforces only CPU seconds (`RLIMIT_CPU`) and no core dumps. On macOS there is no seccomp, no namespaces and no reliable address-space limit.
+- Durable results: a finished receipt is written, synced and renamed before `completed` is sent. A retry with the same idempotence key, task id and cause id gets the stored receipt; a different request under the same key is refused (`DUPLICATE_ID`). One worker per state folder (`flock`).
+- The Spark owns the deadline: it sends `cancel_request`, waits a grace period, then reports `UNCERTAIN` and closes the connection. A dropped link is `UNCERTAIN`, never `FAILED`.
+
+## Use
+
+```
+# on the worker
+aien-hetjob keygen --state ~/aien-hetjob/state      # prints the public key for the Spark's roster
+aien-hetjob caps --state ~/aien-hetjob/state        # claimed platform and a local baseline
+# on the Spark
+aien-hetjob dispatch --roster roster.txt --ssh macbook-hetjob --matmul 512 512 512 637
+aien-hetjob local --matmul 512 512 512 637          # same job here, worker algorithm and oracle timed
+```
+
+Exit 0 means verified; anything else prints `OUTCOME FAILED|CANCELLED|UNCERTAIN|REJECTED <reason>` and exits 1.
diff --git a/crates/aien-hetjob/evidence/het637-m2-20261018/01-matmul-512.txt b/crates/aien-hetjob/evidence/het637-m2-20261018/01-matmul-512.txt
new file mode 100644
index 00000000..a9320629
--- /dev/null
+++ b/crates/aien-hetjob/evidence/het637-m2-20261018/01-matmul-512.txt
@@ -0,0 +1,27 @@
+++ /home/drakestapleton/workspace/targets/het-637/release/aien-hetjob dispatch --roster crates/aien-hetjob/evidence/het637-m2-20261018/roster.txt --ssh macbook-hetjob --matmul 512 512 512 637 --idem 6a6f62637d6d326d61746d756c353132
+aien-hetjob serve: Summary { completed: 1, replayed: 0, denied: 0, cancelled: 0, failed: 0, refused_frames: 0 }
+task_id=5913c75cb62ae1b78cc6895efcdc08ce
+idempotence_key=6a6f62637d6d326d61746d756c353132
+kind=matmul_u32
+work_units=134217728
+round_trip_ms=144.814
+frames=6
+stale_ignored=0
+oracle_ms=119.805
+OUTCOME VERIFIED
+output_digest=837b7c5da06c8fa7201b96c47968da6f92cf3540b48d118739d604c66892c1a1
+oracle=matched
+worker_key_fingerprint=310482aafb104bcf37f0a14c00eb38f0aacbc9ea4bc02735497c4184ac7af309
+claimed_platform=macos aarch64 cpus=8 memory_bytes=8589934592
+claimed_program_digest=a57f7c08b47c1f37510cd981e8b30e8c045f2365687e39033c484643f3523077
+claimed_remote_compute_ms=9.034
+claimed_threads=4
+++ /home/drakestapleton/workspace/targets/het-637/release/aien-hetjob local --matmul 512 512 512 637 --threads 4
+kind=matmul_u32
+work_units=134217728
+worker_algorithm_digest=837b7c5da06c8fa7201b96c47968da6f92cf3540b48d118739d604c66892c1a1
+worker_algorithm_ms=8.538
+threads=4
+oracle_digest=837b7c5da06c8fa7201b96c47968da6f92cf3540b48d118739d604c66892c1a1
+oracle_ms=76.584
+agree=true
diff --git a/crates/aien-hetjob/evidence/het637-m2-20261018/02-matmul-1024.txt b/crates/aien-hetjob/evidence/het637-m2-20261018/02-matmul-1024.txt
new file mode 100644
index 00000000..92541cc7
--- /dev/null
+++ b/crates/aien-hetjob/evidence/het637-m2-20261018/02-matmul-1024.txt
@@ -0,0 +1,18 @@
+++ /home/drakestapleton/workspace/targets/het-637/release/aien-hetjob dispatch --roster crates/aien-hetjob/evidence/het637-m2-20261018/roster.txt --ssh macbook-hetjob --matmul 1024 1024 1024 2026
+aien-hetjob serve: Summary { completed: 1, replayed: 0, denied: 0, cancelled: 0, failed: 0, refused_frames: 0 }
+task_id=201c34c0eee4907a1f0377f52398db78
+idempotence_key=7647ad9a32992473f8faef0cf9a33afc
+kind=matmul_u32
+work_units=1073741824
+round_trip_ms=105.025
+frames=6
+stale_ignored=0
+oracle_ms=1195.342
+OUTCOME VERIFIED
+output_digest=1a6ac78095dee511101103c5f6b86dee751015930b434a5f6325368ee76d55dd
+oracle=matched
+worker_key_fingerprint=310482aafb104bcf37f0a14c00eb38f0aacbc9ea4bc02735497c4184ac7af309
+claimed_platform=macos aarch64 cpus=8 memory_bytes=8589934592
+claimed_program_digest=a57f7c08b47c1f37510cd981e8b30e8c045f2365687e39033c484643f3523077
+claimed_remote_compute_ms=87.748
+claimed_threads=4
diff --git a/crates/aien-hetjob/evidence/het637-m2-20261018/02b-matmul-1024-local.txt b/crates/aien-hetjob/evidence/het637-m2-20261018/02b-matmul-1024-local.txt
new file mode 100644
index 00000000..a226e6c8
--- /dev/null
+++ b/crates/aien-hetjob/evidence/het637-m2-20261018/02b-matmul-1024-local.txt
@@ -0,0 +1,9 @@
+++ /home/drakestapleton/workspace/targets/het-637/release/aien-hetjob local --matmul 1024 1024 1024 2026 --threads 4
+kind=matmul_u32
+work_units=1073741824
+worker_algorithm_digest=1a6ac78095dee511101103c5f6b86dee751015930b434a5f6325368ee76d55dd
+worker_algorithm_ms=54.984
+threads=4
+oracle_digest=1a6ac78095dee511101103c5f6b86dee751015930b434a5f6325368ee76d55dd
+oracle_ms=1195.252
+agree=true
diff --git a/crates/aien-hetjob/evidence/het637-m2-20261018/03-chain-10m.txt b/crates/aien-hetjob/evidence/het637-m2-20261018/03-chain-10m.txt
new file mode 100644
index 00000000..e0beec03
--- /dev/null
+++ b/crates/aien-hetjob/evidence/het637-m2-20261018/03-chain-10m.txt
@@ -0,0 +1,18 @@
+++ /home/drakestapleton/workspace/targets/het-637/release/aien-hetjob dispatch --roster crates/aien-hetjob/evidence/het637-m2-20261018/roster.txt --ssh macbook-hetjob --chain 10000000 abababababababababababababababababababababababababababababababab
+aien-hetjob serve: Summary { completed: 1, replayed: 0, denied: 0, cancelled: 0, failed: 0, refused_frames: 0 }
+task_id=52d6ae89dddc9248034871819a83f37b
+idempotence_key=b9322a6ae59c812ea6118eabc46b916a
+kind=digest_chain
+work_units=10000000
+round_trip_ms=1756.295
+frames=6
+stale_ignored=0
+oracle_ms=1182.042
+OUTCOME VERIFIED
+output_digest=2a083022beccae75b5497a9eff5887b5b9e7d5a18b53b5da33255d2bd00f148c
+oracle=matched
+worker_key_fingerprint=310482aafb104bcf37f0a14c00eb38f0aacbc9ea4bc02735497c4184ac7af309
+claimed_platform=macos aarch64 cpus=8 memory_bytes=8589934592
+claimed_program_digest=a57f7c08b47c1f37510cd981e8b30e8c045f2365687e39033c484643f3523077
+claimed_remote_compute_ms=1741.902
+claimed_threads=4
diff --git a/crates/aien-hetjob/evidence/het637-m2-20261018/03b-chain-10m-local.txt b/crates/aien-hetjob/evidence/het637-m2-20261018/03b-chain-10m-local.txt
new file mode 100644
index 00000000..ba13a41e
--- /dev/null
+++ b/crates/aien-hetjob/evidence/het637-m2-20261018/03b-chain-10m-local.txt
@@ -0,0 +1,9 @@
+++ /home/drakestapleton/workspace/targets/het-637/release/aien-hetjob local --chain 10000000 abababababababababababababababababababababababababababababababab
+kind=digest_chain
+work_units=10000000
+worker_algorithm_digest=2a083022beccae75b5497a9eff5887b5b9e7d5a18b53b5da33255d2bd00f148c
+worker_algorithm_ms=1178.227
+threads=4
+oracle_digest=2a083022beccae75b5497a9eff5887b5b9e7d5a18b53b5da33255d2bd00f148c
+oracle_ms=1195.040
+agree=true
diff --git a/crates/aien-hetjob/evidence/het637-m2-20261018/04-retry-first.txt b/crates/aien-hetjob/evidence/het637-m2-20261018/04-retry-first.txt
new file mode 100644
index 00000000..528055b5
--- /dev/null
+++ b/crates/aien-hetjob/evidence/het637-m2-20261018/04-retry-first.txt
@@ -0,0 +1,19 @@
+++ /home/drakestapleton/workspace/targets/het-637/release/aien-hetjob dispatch --roster crates/aien-hetjob/evidence/het637-m2-20261018/roster.txt --ssh macbook-hetjob --matmul 512 512 512 4242 --idem 72657472792d6d61746d756c2d353132 --task 7461736b2d72657472792d3531322d31 --cause c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0
+aien-hetjob serve: Summary { completed: 1, replayed: 0, denied: 0, cancelled: 0, failed: 0, refused_frames: 0 }
+cause_id=c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0
+task_id=7461736b2d72657472792d3531322d31
+idempotence_key=72657472792d6d61746d756c2d353132
+kind=matmul_u32
+work_units=134217728
+round_trip_ms=105.778
+frames=6
+stale_ignored=0
+oracle_ms=123.993
+OUTCOME VERIFIED
+output_digest=27da96a3df130f7859c8f6c3f58b292f3168bf17565399f2d22dcccda99f8a8c
+oracle=matched
+worker_key_fingerprint=310482aafb104bcf37f0a14c00eb38f0aacbc9ea4bc02735497c4184ac7af309
+claimed_platform=macos aarch64 cpus=8 memory_bytes=8589934592
+claimed_program_digest=a57f7c08b47c1f37510cd981e8b30e8c045f2365687e39033c484643f3523077
+claimed_remote_compute_ms=8.815
+claimed_threads=4
diff --git a/crates/aien-hetjob/evidence/het637-m2-20261018/04b-retry-replayed.txt b/crates/aien-hetjob/evidence/het637-m2-20261018/04b-retry-replayed.txt
new file mode 100644
index 00000000..daeb0236
--- /dev/null
+++ b/crates/aien-hetjob/evidence/het637-m2-20261018/04b-retry-replayed.txt
@@ -0,0 +1,19 @@
+++ /home/drakestapleton/workspace/targets/het-637/release/aien-hetjob dispatch --roster crates/aien-hetjob/evidence/het637-m2-20261018/roster.txt --ssh macbook-hetjob --matmul 512 512 512 4242 --idem 72657472792d6d61746d756c2d353132 --task 7461736b2d72657472792d3531322d31 --cause c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0
+aien-hetjob serve: Summary { completed: 0, replayed: 1, denied: 0, cancelled: 0, failed: 0, refused_frames: 0 }
+cause_id=c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0
+task_id=7461736b2d72657472792d3531322d31
+idempotence_key=72657472792d6d61746d756c2d353132
+kind=matmul_u32
+work_units=134217728
+round_trip_ms=138.666
+frames=5
+stale_ignored=0
+oracle_ms=107.119
+OUTCOME VERIFIED
+output_digest=27da96a3df130f7859c8f6c3f58b292f3168bf17565399f2d22dcccda99f8a8c
+oracle=matched
+worker_key_fingerprint=310482aafb104bcf37f0a14c00eb38f0aacbc9ea4bc02735497c4184ac7af309
+claimed_platform=macos aarch64 cpus=8 memory_bytes=8589934592
+claimed_program_digest=a57f7c08b47c1f37510cd981e8b30e8c045f2365687e39033c484643f3523077
+claimed_remote_compute_ms=8.815
+claimed_threads=4
diff --git a/crates/aien-hetjob/evidence/het637-m2-20261018/05-control-wrong-roster.txt b/crates/aien-hetjob/evidence/het637-m2-20261018/05-control-wrong-roster.txt
new file mode 100644
index 00000000..a30abcab
--- /dev/null
+++ b/crates/aien-hetjob/evidence/het637-m2-20261018/05-control-wrong-roster.txt
@@ -0,0 +1,11 @@
+++ /home/drakestapleton/workspace/targets/het-637/release/aien-hetjob dispatch --roster crates/aien-hetjob/evidence/het637-m2-20261018/wrong-roster.txt --ssh macbook-hetjob --matmul 64 64 64 1
+aien-hetjob serve: Summary { completed: 1, replayed: 0, denied: 0, cancelled: 0, failed: 0, refused_frames: 0 }
+task_id=acd4bd1ba4a612adaf542c2e62370371
+idempotence_key=247fa65e03511f758333d38bdfda32ff
+kind=matmul_u32
+work_units=262144
+round_trip_ms=207.333
+frames=5
+stale_ignored=0
+oracle_ms=0.141
+OUTCOME REJECTED WRONG_PEER:8d5fe96bea997f8acaf79b514bd37597becddef82a0a9075ef5c5bc53ad7be2a
diff --git a/crates/aien-hetjob/evidence/het637-m2-20261018/06-control-over-budget.txt b/crates/aien-hetjob/evidence/het637-m2-20261018/06-control-over-budget.txt
new file mode 100644
index 00000000..2c740227
--- /dev/null
+++ b/crates/aien-hetjob/evidence/het637-m2-20261018/06-control-over-budget.txt
@@ -0,0 +1,10 @@
+++ /home/drakestapleton/workspace/targets/het-637/release/aien-hetjob dispatch --roster crates/aien-hetjob/evidence/het637-m2-20261018/roster.txt --ssh macbook-hetjob --matmul 16384 16384 1 1 --no-oracle
+aien-hetjob serve: Summary { completed: 0, replayed: 0, denied: 1, cancelled: 0, failed: 0, refused_frames: 0 }
+task_id=a16f40660fb07d57dc9cecfc3aad8ef9
+idempotence_key=6f330511e2f4f4b6b986c09854ea8e5f
+kind=matmul_u32
+work_units=268435456
+round_trip_ms=255.374
+frames=1
+stale_ignored=0
+OUTCOME FAILED OVER_BUDGET:MEMORY need=1073872896 limit=536870912
diff --git a/crates/aien-hetjob/evidence/het637-m2-20261018/07-control-duplicate-id.txt b/crates/aien-hetjob/evidence/het637-m2-20261018/07-control-duplicate-id.txt
new file mode 100644
index 00000000..83dda63e
--- /dev/null
+++ b/crates/aien-hetjob/evidence/het637-m2-20261018/07-control-duplicate-id.txt
@@ -0,0 +1,11 @@
+++ /home/drakestapleton/workspace/targets/het-637/release/aien-hetjob dispatch --roster crates/aien-hetjob/evidence/het637-m2-20261018/roster.txt --ssh macbook-hetjob --matmul 64 64 64 2 --idem 6a6f62637d6d326d61746d756c353132
+aien-hetjob serve: Summary { completed: 0, replayed: 0, denied: 1, cancelled: 0, failed: 0, refused_frames: 0 }
+task_id=47621a951bf187b914bbe641df2b1f76
+idempotence_key=6a6f62637d6d326d61746d756c353132
+kind=matmul_u32
+work_units=262144
+round_trip_ms=240.648
+frames=1
+stale_ignored=0
+oracle_ms=0.347
+OUTCOME FAILED DUPLICATE_ID
diff --git a/crates/aien-hetjob/evidence/het637-m2-20261018/08-control-deadline-cancel.txt b/crates/aien-hetjob/evidence/het637-m2-20261018/08-control-deadline-cancel.txt
new file mode 100644
index 00000000..82e71a9c
--- /dev/null
+++ b/crates/aien-hetjob/evidence/het637-m2-20261018/08-control-deadline-cancel.txt
@@ -0,0 +1,10 @@
+++ /home/drakestapleton/workspace/targets/het-637/release/aien-hetjob dispatch --roster crates/aien-hetjob/evidence/het637-m2-20261018/roster.txt --ssh macbook-hetjob --chain 4294967295 abababababababababababababababababababababababababababababababab --deadline-s 2 --no-oracle
+aien-hetjob serve: Summary { completed: 0, replayed: 0, denied: 0, cancelled: 1, failed: 0, refused_frames: 0 }
+task_id=63fec0aec64bf65a5e264a1dbe7c37e9
+idempotence_key=5e30387fe3152ead180397acfdc7a252
+kind=digest_chain
+work_units=4294967295
+round_trip_ms=2004.720
+frames=3
+stale_ignored=0
+OUTCOME CANCELLED
diff --git a/crates/aien-hetjob/evidence/het637-m2-20261018/RESULTS.md b/crates/aien-hetjob/evidence/het637-m2-20261018/RESULTS.md
new file mode 100644
index 00000000..8d308386
--- /dev/null
+++ b/crates/aien-hetjob/evidence/het637-m2-20261018/RESULTS.md
@@ -0,0 +1,40 @@
+# het637-m2-20261018: Spark coordinator to M2 worker, first physical run
+
+Issue: aien-sovereign-core#637 (parent aienix#6). Branch `het/637-job-adapter`. Date 2026-10-18, about 18:00Z.
+
+## Setup
+
+| Item | Value |
+|---|---|
+| Coordinator | DGX Spark (GB10, Linux aarch64), `aien-hetjob` release build from this branch |
+| Worker | MacBook Air M2 (macOS 26.6.2, 8 CPUs, 8 GiB), `aien-hetjob` release build from the same source tree, `~/aien-hetjob/bin/aien-hetjob` |
+| Worker program digest (claimed, sha256 of the file) | `a57f7c08b47c1f37510cd981e8b30e8c045f2365687e39033c484643f3523077` |
+| Worker receipt key | `8d5fe96b...7be2a`, fingerprint `310482aa...af309` ([roster.txt](roster.txt)) |
+| Link | SSH over the tailnet; host key pinned (`StrictHostKeyChecking yes`, fingerprint in roster.txt); dedicated key with `command="aien-hetjob serve ...",restrict` in the M2 `authorized_keys`, so the key starts only the worker (asking it for `ls /` started the worker, which exited with no job) |
+| Worker limits | defaults: 512 MiB admission memory, 2^34 work units, 120 s wall, 4 threads, RLIMIT_CPU = 120 x 4 + 30 s |
+| iMac | NOT_RUN: it runs the AIENOS lab image and has no hosted OS; SSH times out. Its disk was not touched. |
+
+Tests: `cargo test -p aien-hetjob` 16/16 on the Spark (debug) and 16/16 on the M2 (release), including the frozen golden digests, so both architectures give the same bits for the same job.
+
+## Runs (files in this folder)
+
+| File | Job | Outcome | Worker compute (claimed) | Spark, same algorithm | Round trip |
+|---|---|---|---|---|---|
+| 01 | matmul_u32 512x512x512, seed 637 | VERIFIED, oracle matched | 9.034 ms | 8.538 ms | 144.814 ms |
+| 02 / 02b | matmul_u32 1024x1024x1024, seed 2026 | VERIFIED, oracle matched | 87.748 ms | 54.984 ms | 105.025 ms |
+| 03 / 03b | digest_chain 10,000,000 rounds | VERIFIED, oracle matched | 1741.902 ms | 1178.227 ms | 1756.295 ms |
+| 04 / 04b | matmul 512^3 seed 4242, then the exact retry (same idempotence key, task id, cause id) | VERIFIED both; the retry replayed the stored receipt (same compute time 8.815 ms, nothing recomputed) | 8.815 ms | | 105.778 / 138.666 ms |
+| 05 | roster holding a different real key | REJECTED `WRONG_PEER` (the M2's genuine receipt is refused) | | | |
+| 06 | matmul 16384x16384x1 | FAILED `OVER_BUDGET:MEMORY need=1073872896 limit=536870912`, refused before allocation | | | |
+| 07 | new job body under the idempotence key of 01 | FAILED `DUPLICATE_ID` | | | |
+| 08 | digest_chain 2^32-1 rounds, coordinator deadline 2 s | CANCELLED: the coordinator sent `cancel_request` at its deadline, the worker stopped and answered `cancelled` | | | 2004.720 ms |
+
+Round trip is measured from the request write to the final message. SSH session setup overlaps it and is not separately measured.
+
+## What this shows and what it does not
+
+- Shown: one frozen job dispatched from the Spark to a different physical machine, answered in PST1 frames, with a receipt signed by a pinned worker key, and the output digest matching the Spark's own recompute (a different loop order for the matrix product). Wrong peer, over budget, duplicate id, deadline cancel and exact retry behave as specified on the real link.
+- Self-attested: the platform, program digest and timings in the receipt are the M2 worker's own claims. The signature proves which pinned key made them, not that they are true.
+- Not offload: the Spark recomputes every output to check it, so these runs verify remote execution; they do not save the Spark any work. A check cheaper than recompute (for example Freivalds on a returned matrix) is future work.
+- No "useful workload" yet: matmul and the digest chain are deterministic test tasks. The issue's real workload (batch tokenization, model evaluation or a small forward pass) is cut 2.
+- Energy: not measured.
diff --git a/crates/aien-hetjob/evidence/het637-m2-20261018/roster.txt b/crates/aien-hetjob/evidence/het637-m2-20261018/roster.txt
new file mode 100644
index 00000000..ed6796a1
--- /dev/null
+++ b/crates/aien-hetjob/evidence/het637-m2-20261018/roster.txt
@@ -0,0 +1,4 @@
+# aien-hetjob roster: worker receipt keys the Spark coordinator accepts
+# M2 MacBook Air (macOS 26.6.2, Apple M2), key made 2026-10-18 by `aien-hetjob keygen` on the M2
+# M2 SSH host key as pinned in the Spark known_hosts: ED25519 SHA256:Jdrszoi5q21Jc/l6pvFPEYbpspSPhtpRTC1uLbq31S0;
+8d5fe96bea997f8acaf79b514bd37597becddef82a0a9075ef5c5bc53ad7be2a
diff --git a/crates/aien-hetjob/evidence/het637-m2-20261018/wrong-roster.txt b/crates/aien-hetjob/evidence/het637-m2-20261018/wrong-roster.txt
new file mode 100644
index 00000000..bcece548
--- /dev/null
+++ b/crates/aien-hetjob/evidence/het637-m2-20261018/wrong-roster.txt
@@ -0,0 +1,2 @@
+# a real ed25519 key that is NOT the M2 worker key (a Spark test key)
+58843530e2c38871b18738dd6edff99577f2c154e5737e6dcdbf1531163abd0d
diff --git a/crates/aien-hetjob/src/coordinator.rs b/crates/aien-hetjob/src/coordinator.rs
new file mode 100644
index 00000000..d6aca533
--- /dev/null
+++ b/crates/aien-hetjob/src/coordinator.rs
@@ -0,0 +1,226 @@
+//! The coordinator: sends one job, reads the worker's replies as hints,
+//! verifies the receipt and checks the output against its own recompute.
+//!
+//! The coordinator owns the job: its deadline, the open task and the
+//! connection. When the deadline passes it sends `cancel_request`, waits a
+//! short grace, and otherwise reports `Uncertain`; the caller then closes the
+//! connection (for SSH, kills the child). A drop before a final answer is
+//! `Uncertain`, never `Failed` or `Cancelled` (PST1 section 8).
+
+use crate::receipt::{Receipt, ReceiptError, MAX_RECEIPT_BYTES};
+use crate::task::TaskSpec;
+use crate::wire::{self, Ids, Inbound};
+use ed25519_dalek::VerifyingKey;
+use sha2::{Digest, Sha256};
+use std::io::{self, Read, Write};
+use std::sync::mpsc::{self, RecvTimeoutError};
+use std::time::{Duration, Instant};
+
+/// One job to send.
+#[derive(Debug, Clone, Copy)]
+pub struct Job {
+    pub spec: TaskSpec,
+    pub ids: Ids,
+}
+
+/// How long to wait, and the coordinator's own answer if it has one.
+#[derive(Debug, Clone, Copy)]
+pub struct Policy {
+    pub deadline: Duration,
+    pub cancel_grace: Duration,
+    /// The coordinator's recompute of the output digest (`task::oracle`).
+    /// `None` accepts a verified receipt without an output check and says so.
+    pub oracle: Option<[u8; 32]>,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum OracleCheck {
+    Matched,
+    NotChecked,
+}
+
+#[derive(Debug, Clone)]
+pub struct Verified {
+    pub receipt: Receipt,
+    pub worker_key: VerifyingKey,
+    pub output: [u8; 32],
+    pub oracle: OracleCheck,
+}
+
+#[derive(Debug, Clone)]
+pub enum Outcome {
+    Verified(Box<Verified>),
+    /// The worker reported `failed` with this reason.
+    Failed(String),
+    Cancelled,
+    /// No final answer: disconnect, deadline, or the worker said uncertain.
+    Uncertain(String),
+    /// The coordinator refused what the worker sent.
+    Rejected(String),
+}
+
+/// Counts that do not change the outcome.
+#[derive(Debug, Default, Clone, PartialEq, Eq)]
+pub struct Stats {
+    /// Messages for a different task or idempotence key, ignored.
+    pub stale_ignored: u32,
+    pub frames: u32,
+    pub round_trip: Duration,
+}
+
+fn reject(why: impl Into<String>) -> Option<Outcome> {
+    Some(Outcome::Rejected(why.into()))
+}
+
+struct Progress<'a> {
+    job: &'a Job,
+    roster: &'a [VerifyingKey],
+    oracle: Option<[u8; 32]>,
+    input_digest: [u8; 32],
+    expect: u32,
+    receipt_bytes: Vec<u8>,
+    receipt: Option<(Receipt, VerifyingKey)>,
+}
+
+impl Progress<'_> {
+    /// Some(outcome) ends the job.
+    fn step(&mut self, m: wire::Msg, stats: &mut Stats) -> Option<Outcome> {
+        let h = &m.header;
+        let ids = &self.job.ids;
+        if h.task_id != ids.task_id || h.idempotence_key != ids.idempotence_key {
+            stats.stale_ignored += 1;
+            return None;
+        }
+        if wire::requester_type(h.msg_type) {
+            return reject(format!("WRONG_SIDE:type {}", h.msg_type));
+        }
+        if h.cause_id != ids.cause_id || h.objective_id != ids.objective_id {
+            return reject("HEADER_MISMATCH");
+        }
+        if h.ordinal != self.expect {
+            return reject(format!(
+                "OUT_OF_ORDER:expected {} got {}",
+                self.expect, h.ordinal
+            ));
+        }
+        self.expect += 1;
+        match h.msg_type {
+            wire::T_ACCEPTED | wire::T_RUNNING | 3 => None,
+            wire::T_TEXT_CHUNK => {
+                if self.receipt.is_some() {
+                    return reject("TEXT_AFTER_RECEIPT");
+                }
+                self.receipt_bytes.extend_from_slice(&m.payload);
+                if self.receipt_bytes.len() > MAX_RECEIPT_BYTES {
+                    return reject(ReceiptError::TooLarge(self.receipt_bytes.len()).code());
+                }
+                None
+            }
+            wire::T_RECEIPT_REFERENCE => {
+                let digest: [u8; 32] = Sha256::digest(&self.receipt_bytes).into();
+                if m.payload != digest {
+                    return reject("RECEIPT_REFERENCE_MISMATCH");
+                }
+                let (r, key) = match Receipt::verify(&self.receipt_bytes, self.roster) {
+                    Ok(v) => v,
+                    Err(e) => return reject(e.code()),
+                };
+                let binds = [
+                    ("task_id", r.task_id == ids.task_id),
+                    ("idempotence_key", r.idempotence_key == ids.idempotence_key),
+                    ("cause_id", r.cause_id == ids.cause_id),
+                    ("input_digest", r.input_digest == self.input_digest),
+                    ("kind", r.kind == self.job.spec.kind_name()),
+                ];
+                if let Some((field, _)) = binds.iter().find(|(_, ok)| !ok) {
+                    return reject(format!("RECEIPT_MISMATCH:{field}"));
+                }
+                self.receipt = Some((r, key));
+                None
+            }
+            wire::T_COMPLETED => {
+                let Some((r, key)) = self.receipt.take() else {
+                    return reject("COMPLETED_WITHOUT_RECEIPT");
+                };
+                if m.payload != r.output_digest {
+                    return reject("RECEIPT_MISMATCH:output_digest");
+                }
+                let oracle = match self.oracle {
+                    Some(o) if o == r.output_digest => OracleCheck::Matched,
+                    Some(_) => return reject("ORACLE_MISMATCH"),
+                    None => OracleCheck::NotChecked,
+                };
+                let output = r.output_digest;
+                Some(Outcome::Verified(Box::new(Verified {
+                    receipt: r,
+                    worker_key: key,
+                    output,
+                    oracle,
+                })))
+            }
+            wire::T_FAILED => Some(Outcome::Failed(
+                String::from_utf8_lossy(&m.payload).into_owned(),
+            )),
+            wire::T_CANCELLED => Some(Outcome::Cancelled),
+            10 => Some(Outcome::Uncertain("WORKER_UNCERTAIN".to_string())),
+            other => reject(format!("UNEXPECTED_TYPE:{other}")),
+        }
+    }
+}
+
+/// Send `job` on `w`, read replies from `r`, return the outcome.
+pub fn dispatch<R: Read + Send + 'static, W: Write>(
+    r: R,
+    w: &mut W,
+    job: &Job,
+    roster: &[VerifyingKey],
+    policy: &Policy,
+) -> io::Result<(Outcome, Stats)> {
+    let payload = job.spec.encode();
+    let (tx, rx) = mpsc::channel::<Inbound>();
+    std::thread::spawn(move || wire::pump(r, tx, |i| i));
+    let t0 = Instant::now();
+    wire::write_frame(w, &wire::build(&job.ids, wire::T_REQUEST, 0, &payload))?;
+    let mut p = Progress {
+        job,
+        roster,
+        oracle: policy.oracle,
+        input_digest: Sha256::digest(&payload).into(),
+        expect: 0,
+        receipt_bytes: Vec::new(),
+        receipt: None,
+    };
+    let mut stats = Stats::default();
+    let mut deadline = t0 + policy.deadline;
+    let mut cancel_sent = false;
+    let outcome = loop {
+        let wait = deadline.saturating_duration_since(Instant::now());
+        match rx.recv_timeout(wait) {
+            Ok(Inbound::Msg(m)) => {
+                stats.frames += 1;
+                if let Some(o) = p.step(*m, &mut stats) {
+                    break o;
+                }
+            }
+            Ok(Inbound::Refused(code)) => break Outcome::Rejected(format!("PST1:{}", code.code())),
+            Ok(Inbound::Eof) => break Outcome::Uncertain("DISCONNECTED".to_string()),
+            Ok(Inbound::Broken(e)) => break Outcome::Uncertain(format!("DISCONNECTED:{e}")),
+            Err(RecvTimeoutError::Disconnected) => {
+                break Outcome::Uncertain("DISCONNECTED".to_string())
+            }
+            Err(RecvTimeoutError::Timeout) if !cancel_sent => {
+                cancel_sent = true;
+                deadline = Instant::now() + policy.cancel_grace;
+                let cancel = wire::build(&job.ids, wire::T_CANCEL_REQUEST, 1, &[]);
+                if wire::write_frame(w, &cancel).is_err() {
+                    break Outcome::Uncertain("DEADLINE:cancel not delivered".to_string());
+                }
+            }
+            Err(RecvTimeoutError::Timeout) => {
+                break Outcome::Uncertain("DEADLINE:no answer after cancel".to_string())
+            }
+        }
+    };
+    stats.round_trip = t0.elapsed();
+    Ok((outcome, stats))
+}
diff --git a/crates/aien-hetjob/src/host.rs b/crates/aien-hetjob/src/host.rs
new file mode 100644
index 00000000..201ecd08
--- /dev/null
+++ b/crates/aien-hetjob/src/host.rs
@@ -0,0 +1,82 @@
+//! What the worker can say about the machine it runs on, and the one limit
+//! the operating system enforces for it.
+
+use crate::receipt::Platform;
+use sha2::{Digest, Sha256};
+use std::io;
+
+/// Platform facts for the receipt and the capability report. All of them are
+/// the worker's own claims.
+pub fn platform() -> io::Result<Platform> {
+    Ok(Platform {
+        os: std::env::consts::OS.to_string(),
+        arch: std::env::consts::ARCH.to_string(),
+        cpus: std::thread::available_parallelism()
+            .map(|n| n.get() as u64)
+            .unwrap_or(1),
+        memory_bytes: memory_bytes(),
+        program_digest: program_digest()?,
+        version: env!("CARGO_PKG_VERSION").to_string(),
+    })
+}
+
+/// SHA-256 of the running executable's file.
+pub fn program_digest() -> io::Result<[u8; 32]> {
+    let exe = std::env::current_exe()?;
+    Ok(Sha256::digest(std::fs::read(exe)?).into())
+}
+
+#[cfg(target_os = "macos")]
+fn memory_bytes() -> u64 {
+    let mut v: u64 = 0;
+    let mut len = std::mem::size_of::<u64>();
+    // SAFETY: sysctlbyname writes at most `len` bytes into `v`, a u64 we own.
+    let rc = unsafe {
+        libc::sysctlbyname(
+            c"hw.memsize".as_ptr(),
+            (&mut v as *mut u64).cast(),
+            &mut len,
+            std::ptr::null_mut(),
+            0,
+        )
+    };
+    if rc == 0 {
+        v
+    } else {
+        0
+    }
+}
+
+#[cfg(not(target_os = "macos"))]
+fn memory_bytes() -> u64 {
+    std::fs::read_to_string("/proc/meminfo")
+        .ok()
+        .and_then(|s| {
+            s.lines()
+                .find(|l| l.starts_with("MemTotal:"))
+                .and_then(|l| l.split_whitespace().nth(1))
+                .and_then(|kb| kb.parse::<u64>().ok())
+        })
+        .map(|kb| kb * 1024)
+        .unwrap_or(0)
+}
+
+/// Cap the worker process's CPU seconds (RLIMIT_CPU) and forbid core dumps.
+/// This is the only ceiling the kernel enforces here; on macOS there is no
+/// reliable address-space limit and no seccomp or namespaces.
+pub fn limit_cpu_seconds(secs: u64) -> io::Result<()> {
+    let set = |res, v: u64| {
+        let lim = libc::rlimit {
+            rlim_cur: v as libc::rlim_t,
+            rlim_max: v as libc::rlim_t,
+        };
+        // SAFETY: setrlimit reads a struct we own.
+        if unsafe { libc::setrlimit(res, &lim) } != 0 {
+            Err(io::Error::last_os_error())
+        } else {
+            Ok(())
+        }
+    };
+    set(libc::RLIMIT_CPU, secs)?;
+    set(libc::RLIMIT_CORE, 0)
+}
diff --git a/crates/aien-hetjob/src/lib.rs b/crates/aien-hetjob/src/lib.rs
new file mode 100644
index 00000000..2d201021
--- /dev/null
+++ b/crates/aien-hetjob/src/lib.rs
@@ -0,0 +1,21 @@
+//! Heterogeneous CPU jobs for AIEN (aien-sovereign-core#637, parent aienix#6).
+//!
+//! A coordinator (the Spark) sends one allowlisted, integer-exact job to a
+//! hosted worker machine (an M2 MacBook, or any Unix host) over PST1 frames on
+//! a byte stream, normally SSH stdio to a forced-command key. The worker
+//! admits it against fixed ceilings, runs it, signs a receipt with its own
+//! pinned key and stores it durably; the coordinator checks the receipt and
+//! compares the output digest with its own recompute.
+//!
+//! What this proves and what it does not: a match proves the worker returned
+//! the right answer for that job. The receipt's platform, program and timing
+//! fields are the worker's own claims (self-attested). There is no remote
+//! shell: the worker runs only the kinds in `task`.
+
+pub mod coordinator;
+pub mod host;
+pub mod receipt;
+pub mod store;
+pub mod task;
+pub mod wire;
+pub mod worker;
diff --git a/crates/aien-hetjob/src/main.rs b/crates/aien-hetjob/src/main.rs
new file mode 100644
index 00000000..14842124
--- /dev/null
+++ b/crates/aien-hetjob/src/main.rs
@@ -0,0 +1,439 @@
+//! aien-hetjob: worker and coordinator front door (aien-sovereign-core#637).
+//!
+//!   aien-hetjob keygen --state DIR                 create the worker key (0600), print its public key
+//!   aien-hetjob caps --state DIR                   claimed platform, key, program digest, local baseline
+//!   aien-hetjob serve --state DIR [LIMITS]         serve PST1 on stdin/stdout until the peer closes
+//!   aien-hetjob dispatch --roster FILE (--ssh HOST [--remote CMD] | --local-worker DIR) JOB [--deadline-s N] [--no-oracle] [--idem HEX --task HEX --cause HEX to retry]
+//!   aien-hetjob local JOB [--threads N]            run the worker's algorithm and the oracle here, timed
+//!
+//! JOB is `--matmul M K N SEED` or `--chain ROUNDS SEED_HEX64`.
+//! LIMITS: --max-memory-mib N, --max-work N, --max-wall-s N, --threads N.
+//! Exit: 0 verified (or command done), 1 any other outcome, 2 usage error.
+
+use aien_hetjob::coordinator::{self, Job, OracleCheck, Outcome, Policy};
+use aien_hetjob::receipt::Receipt;
+use aien_hetjob::store::Store;
+use aien_hetjob::task::{self, Control, Limits, TaskSpec};
+use aien_hetjob::worker::Worker;
+use aien_hetjob::{host, wire};
+use aien_test::bundle::{fingerprint, hex_decode, hex_encode, keygen, load_signing_key};
+use ed25519_dalek::VerifyingKey;
+use sha2::{Digest, Sha256};
+use std::io::Read;
+use std::path::{Path, PathBuf};
+use std::process::{Command, ExitCode, Stdio};
+use std::sync::atomic::AtomicBool;
+use std::time::{Duration, Instant};
+
+fn usage(msg: &str) -> ExitCode {
+    eprintln!("aien-hetjob: {msg}\nsee the header of crates/aien-hetjob/src/main.rs for usage");
+    ExitCode::from(2)
+}
+
+struct Args(Vec<String>);
+
+impl Args {
+    fn flag(&mut self, name: &str) -> bool {
+        match self.0.iter().position(|a| a == name) {
+            Some(i) => {
+                self.0.remove(i);
+                true
+            }
+            None => false,
+        }
+    }
+    fn values(&mut self, name: &str, n: usize) -> Result<Option<Vec<String>>, String> {
+        let Some(i) = self.0.iter().position(|a| a == name) else {
+            return Ok(None);
+        };
+        if i + n >= self.0.len() {
+            return Err(format!("{name} needs {n} value(s)"));
+        }
+        let v: Vec<String> = self.0.drain(i..i + 1 + n).skip(1).collect();
+        Ok(Some(v))
+    }
+    fn one(&mut self, name: &str) -> Result<Option<String>, String> {
+        Ok(self.values(name, 1)?.map(|mut v| v.remove(0)))
+    }
+    fn num<T: std::str::FromStr>(&mut self, name: &str) -> Result<Option<T>, String> {
+        match self.one(name)? {
+            Some(s) => s
+                .parse()
+                .map(Some)
+                .map_err(|_| format!("{name}: not a number: {s}")),
+            None => Ok(None),
+        }
+    }
+    fn done(&self) -> Result<(), String> {
+        match self.0.first() {
+            Some(a) => Err(format!("unexpected argument {a}")),
+            None => Ok(()),
+        }
+    }
+}
+
+fn job_spec(a: &mut Args) -> Result<TaskSpec, String> {
+    if let Some(v) = a.values("--matmul", 4)? {
+        let p = |i: usize| {
+            v[i].parse::<u64>()
+                .map_err(|_| format!("--matmul: not a number: {}", v[i]))
+        };
+        let dim = |i: usize| {
+            p(i).and_then(|x| u16::try_from(x).map_err(|_| format!("--matmul: {x} above 65535")))
+        };
+        return Ok(TaskSpec::MatmulU32 {
+            m: dim(0)?,
+            k: dim(1)?,
+            n: dim(2)?,
+            seed: p(3)?,
+        });
+    }
+    if let Some(v) = a.values("--chain", 2)? {
+        let rounds = v[0]
+            .parse()
+            .map_err(|_| format!("--chain: not a number: {}", v[0]))?;
+        let seed = hex_decode(&v[1])
+            .and_then(|b| <[u8; 32]>::try_from(b).ok())
+            .ok_or("--chain: seed must be 64 hex digits")?;
+        return Ok(TaskSpec::DigestChain { rounds, seed });
+    }
+    Err("a job is required: --matmul M K N SEED or --chain ROUNDS SEED_HEX64".to_string())
+}
+
+fn limits(a: &mut Args) -> Result<Limits, String> {
+    let mut l = Limits::default();
+    if let Some(m) = a.num::<u64>("--max-memory-mib")? {
+        l.max_memory_bytes = m << 20;
+    }
+    if let Some(w) = a.num("--max-work")? {
+        l.max_work_units = w;
+    }
+    if let Some(s) = a.num("--max-wall-s")? {
+        l.max_wall = Duration::from_secs(s);
+    }
+    if let Some(t) = a.num("--threads")? {
+        l.max_threads = t;
+    }
+    Ok(l)
+}
+
+fn random<const N: usize>() -> std::io::Result<[u8; N]> {
+    let mut b = [0u8; N];
+    std::fs::File::open("/dev/urandom")?.read_exact(&mut b)?;
+    Ok(b)
+}
+
+fn read_roster(path: &Path) -> Result<Vec<VerifyingKey>, String> {
+    let txt = std::fs::read_to_string(path)
+        .map_err(|e| format!("cannot read roster {}: {e}", path.display()))?;
+    txt.lines()
+        .map(|l| l.split('#').next().unwrap_or("").trim())
+        .filter(|l| !l.is_empty())
+        .map(|l| {
+            hex_decode(l)
+                .and_then(|b| <[u8; 32]>::try_from(b).ok())
+                .and_then(|b| VerifyingKey::from_bytes(&b).ok())
+                .ok_or_else(|| format!("roster line is not a 32-byte ed25519 public key: {l}"))
+        })
+        .collect()
+}
+
+fn ms(d: Duration) -> String {
+    format!("{:.3}", d.as_secs_f64() * 1e3)
+}
+
+fn time_local(spec: &TaskSpec, threads: usize) -> ([u8; 32], Duration) {
+    let cancel = AtomicBool::new(false);
+    let t0 = Instant::now();
+    let ctl = Control {
+        cancel: &cancel,
+        deadline: t0 + Duration::from_secs(3600),
+        threads,
+    };
+    let d = task::run(spec, &ctl).expect("local run is never cancelled");
+    (d, t0.elapsed())
+}
+
+fn main() -> ExitCode {
+    let mut argv: Vec<String> = std::env::args().skip(1).collect();
+    if argv.is_empty() {
+        return usage("missing command");
+    }
+    let cmd = argv.remove(0);
+    let mut a = Args(argv);
+    match run(&cmd, &mut a) {
+        Ok(code) => code,
+        Err(e) if e.starts_with("usage:") => usage(&e[6..]),
+        Err(e) => {
+            eprintln!("aien-hetjob: {e}");
+            ExitCode::from(1)
+        }
+    }
+}
+
+fn run(cmd: &str, a: &mut Args) -> Result<ExitCode, String> {
+    let u = |e: String| format!("usage:{e}");
+    match cmd {
+        "keygen" => {
+            let state = PathBuf::from(a.one("--state").map_err(u)?.ok_or("usage:--state DIR")?);
+            a.done().map_err(u)?;
+            std::fs::create_dir_all(&state).map_err(|e| e.to_string())?;
+            let pk = keygen(&state.join(aien_hetjob::store::KEY_FILE))?;
+            println!("{pk}");
+            Ok(ExitCode::SUCCESS)
+        }
+        "caps" => {
+            let state = PathBuf::from(a.one("--state").map_err(u)?.ok_or("usage:--state DIR")?);
+            a.done().map_err(u)?;
+            let key = load_signing_key(&state.join(aien_hetjob::store::KEY_FILE))?;
+            let p = host::platform().map_err(|e| e.to_string())?;
+            let vk = key.verifying_key();
+            println!("pubkey={}", hex_encode(vk.as_bytes()));
+            println!("key_fingerprint={}", fingerprint(&vk));
+            println!(
+                "claimed_os={}\nclaimed_arch={}\nclaimed_cpus={}",
+                p.os, p.arch, p.cpus
+            );
+            println!(
+                "claimed_memory_bytes={}\nclaimed_program_digest={}",
+                p.memory_bytes,
+                hex_encode(&p.program_digest)
+            );
+            println!(
+                "claimed_version={}\nkinds=matmul_u32,digest_chain",
+                p.version
+            );
+            let base = TaskSpec::MatmulU32 {
+                m: 256,
+                k: 256,
+                n: 256,
+                seed: 1,
+            };
+            for t in [1usize, Limits::default().max_threads] {
+                let (_, d) = time_local(&base, t);
+                println!("baseline_matmul_256_threads_{t}_ms={}", ms(d));
+            }
+            Ok(ExitCode::SUCCESS)
+        }
+        "serve" => {
+            let state = PathBuf::from(a.one("--state").map_err(u)?.ok_or("usage:--state DIR")?);
+            let lim = limits(a).map_err(u)?;
+            a.done().map_err(u)?;
+            let store = Store::open(&state).map_err(|e| format!("REFUSED: {e}"))?;
+            let key = load_signing_key(&store.key_path())?;
+            // CPU seconds for one connection: every thread busy for the wall limit, plus slack.
+            host::limit_cpu_seconds(lim.max_wall.as_secs() * lim.max_threads as u64 + 30)
+                .map_err(|e| e.to_string())?;
+            let platform = host::platform().map_err(|e| e.to_string())?;
+            let w = Worker {
+                key,
+                limits: lim,
+                store,
+                platform,
+            };
+            let sum = w
+                .serve(std::io::stdin(), std::io::stdout().lock())
+                .map_err(|e| e.to_string())?;
+            eprintln!("aien-hetjob serve: {sum:?}");
+            Ok(ExitCode::SUCCESS)
+        }
+        "local" => {
+            let spec = job_spec(a).map_err(u)?;
+            let threads = a
+                .num("--threads")
+                .map_err(u)?
+                .unwrap_or(Limits::default().max_threads);
+            a.done().map_err(u)?;
+            let (d, t) = time_local(&spec, threads);
+            let t0 = Instant::now();
+            let o = task::oracle(&spec);
+            let to = t0.elapsed();
+            println!(
+                "kind={}\nwork_units={}",
+                spec.kind_name(),
+                spec.work_units()
+            );
+            println!(
+                "worker_algorithm_digest={}\nworker_algorithm_ms={}\nthreads={threads}",
+                hex_encode(&d),
+                ms(t)
+            );
+            println!(
+                "oracle_digest={}\noracle_ms={}\nagree={}",
+                hex_encode(&o),
+                ms(to),
+                d == o
+            );
+            Ok(if d == o {
+                ExitCode::SUCCESS
+            } else {
+                ExitCode::from(1)
+            })
+        }
+        "dispatch" => dispatch(a),
+        other => Err(format!("usage:unknown command {other}")),
+    }
+}
+
+fn dispatch(a: &mut Args) -> Result<ExitCode, String> {
+    let u = |e: String| format!("usage:{e}");
+    let roster = read_roster(Path::new(
+        &a.one("--roster").map_err(u)?.ok_or("usage:--roster FILE")?,
+    ))?;
+    let ssh = a.one("--ssh").map_err(u)?;
+    let remote = a
+        .one("--remote")
+        .map_err(u)?
+        .unwrap_or_else(|| "aien-hetjob serve --state aien-hetjob/state".to_string());
+    let local_worker = a.one("--local-worker").map_err(u)?;
+    let deadline = Duration::from_secs(a.num("--deadline-s").map_err(u)?.unwrap_or(120));
+    let no_oracle = a.flag("--no-oracle");
+    let idem = match a.one("--idem").map_err(u)? {
+        Some(h) => hex_decode(&h)
+            .and_then(|b| <[u8; 16]>::try_from(b).ok())
+            .ok_or("usage:--idem must be 32 hex digits")?,
+        None => random().map_err(|e| e.to_string())?,
+    };
+    // A retry of the same request repeats both the task id and the
+    // idempotence key (PST1 section 8); a new task id with an old key is a
+    // different request and the worker refuses it as DUPLICATE_ID.
+    let task_id = match a.one("--task").map_err(u)? {
+        Some(h) => hex_decode(&h)
+            .and_then(|b| <[u8; 16]>::try_from(b).ok())
+            .ok_or("usage:--task must be 32 hex digits")?,
+        None => random().map_err(|e| e.to_string())?,
+    };
+    let cause_id = match a.one("--cause").map_err(u)? {
+        Some(h) => hex_decode(&h)
+            .and_then(|b| <[u8; 32]>::try_from(b).ok())
+            .ok_or("usage:--cause must be 64 hex digits")?,
+        None => random().map_err(|e| e.to_string())?,
+    };
+    let spec = job_spec(a).map_err(u)?;
+    a.done().map_err(u)?;
+
+    let mut child = match (&ssh, &local_worker) {
+        (Some(host), None) => Command::new("ssh")
+            .args([
+                "-T",
+                "-o",
+                "BatchMode=yes",
+                "-o",
+                "StrictHostKeyChecking=yes",
+                host,
+            ])
+            .arg(&remote)
+            .stdin(Stdio::piped())
+            .stdout(Stdio::piped())
+            .spawn(),
+        (None, Some(dir)) => Command::new(std::env::current_exe().map_err(|e| e.to_string())?)
+            .args(["serve", "--state", dir])
+            .stdin(Stdio::piped())
+            .stdout(Stdio::piped())
+            .spawn(),
+        _ => return Err("usage:exactly one of --ssh HOST or --local-worker DIR".to_string()),
+    }
+    .map_err(|e| format!("cannot start the worker connection: {e}"))?;
+
+    let objective = Sha256::digest(format!(
+        "AIEN_E2E_OBJECTIVE_V1\naien-hetjob P1 {}",
+        spec.kind_name()
+    ))
+    .into();
+    let ids = wire::Ids {
+        cause_id,
+        origin_run_id: random().map_err(|e| e.to_string())?,
+        objective_id: objective,
+        subject_id: [0; 32],
+        task_id,
+        idempotence_key: idem,
+    };
+    let (oracle, oracle_time) = if no_oracle {
+        (None, Duration::ZERO)
+    } else {
+        let t0 = Instant::now();
+        let o = task::oracle(&spec);
+        (Some(o), t0.elapsed())
+    };
+    let policy = Policy {
+        deadline,
+        cancel_grace: Duration::from_secs(5),
+        oracle,
+    };
+    let job = Job { spec, ids };
+    let r = child.stdout.take().expect("piped stdout");
+    let mut w = child.stdin.take().expect("piped stdin");
+    let (outcome, stats) =
+        coordinator::dispatch(r, &mut w, &job, &roster, &policy).map_err(|e| e.to_string())?;
+    drop(w);
+    if matches!(outcome, Outcome::Uncertain(_)) {
+        let _ = child.kill();
+    }
+    let _ = child.wait();
+
+    println!(
+        "cause_id={}\ntask_id={}\nidempotence_key={}",
+        hex_encode(&ids.cause_id),
+        hex_encode(&ids.task_id),
+        hex_encode(&ids.idempotence_key)
+    );
+    println!(
+        "kind={}\nwork_units={}",
+        spec.kind_name(),
+        spec.work_units()
+    );
+    println!(
+        "round_trip_ms={}\nframes={}\nstale_ignored={}",
+        ms(stats.round_trip),
+        stats.frames,
+        stats.stale_ignored
+    );
+    if oracle.is_some() {
+        println!("oracle_ms={}", ms(oracle_time));
+    }
+    match outcome {
+        Outcome::Verified(v) => {
+            let r: &Receipt = &v.receipt;
+            println!("OUTCOME VERIFIED");
+            println!("output_digest={}", hex_encode(&v.output));
+            println!(
+                "oracle={}",
+                match v.oracle {
+                    OracleCheck::Matched => "matched",
+                    OracleCheck::NotChecked => "not-checked",
+                }
+            );
+            println!("worker_key_fingerprint={}", fingerprint(&v.worker_key));
+            println!(
+                "claimed_platform={} {} cpus={} memory_bytes={}",
+                r.platform.os, r.platform.arch, r.platform.cpus, r.platform.memory_bytes
+            );
+            println!(
+                "claimed_program_digest={}",
+                hex_encode(&r.platform.program_digest)
+            );
+            println!(
+                "claimed_remote_compute_ms={}",
+                ms(Duration::from_nanos(r.compute_ns))
+            );
+            println!("claimed_threads={}", r.threads);
+            Ok(ExitCode::SUCCESS)
+        }
+        Outcome::Failed(why) => {
+            println!("OUTCOME FAILED {why}");
+            Ok(ExitCode::from(1))
+        }
+        Outcome::Cancelled => {
+            println!("OUTCOME CANCELLED");
+            Ok(ExitCode::from(1))
+        }
+        Outcome::Uncertain(why) => {
+            println!("OUTCOME UNCERTAIN {why}");
+            Ok(ExitCode::from(1))
+        }
+        Outcome::Rejected(why) => {
+            println!("OUTCOME REJECTED {why}");
+            Ok(ExitCode::from(1))
+        }
+    }
+}
diff --git a/crates/aien-hetjob/src/receipt.rs b/crates/aien-hetjob/src/receipt.rs
new file mode 100644
index 00000000..37aee566
--- /dev/null
+++ b/crates/aien-hetjob/src/receipt.rs
@@ -0,0 +1,195 @@
+//! The worker's signed receipt for one finished job.
+//!
+//! The receipt is self-attested: the process that ran the job also holds the
+//! signing key and reports its own program digest, platform and timings. The
+//! signature proves which pinned worker key made the claim and that nothing
+//! changed on the way; it does not prove the claimed hardware or program.
+//! What the coordinator trusts is its own recompute of the output digest
+//! (`task::oracle`). Field names say `claimed_` for that reason.
+//!
+//! Canonical bytes and key fingerprints are those of the local verification
+//! bundle (`aien_test::bundle`), so one canonical JSON encoder signs both.
+
+use aien_test::bundle::{fingerprint, hex_decode, hex_encode, signed_bytes};
+use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
+use serde_json::{json, Value};
+
+pub const SCHEMA: &str = "aien.hetjob.receipt/1";
+/// Largest receipt a coordinator reads, checked before parsing.
+pub const MAX_RECEIPT_BYTES: usize = 8 * 1024;
+
+/// What the worker says about itself. Every field is a claim.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Platform {
+    pub os: String,
+    pub arch: String,
+    pub cpus: u64,
+    pub memory_bytes: u64,
+    pub program_digest: [u8; 32],
+    pub version: String,
+}
+
+/// The facts one receipt binds together.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Receipt {
+    pub task_id: [u8; 16],
+    pub idempotence_key: [u8; 16],
+    pub cause_id: [u8; 32],
+    pub kind: String,
+    pub input_digest: [u8; 32],
+    pub output_digest: [u8; 32],
+    pub started_unix_ms: u64,
+    pub compute_ns: u64,
+    pub threads: u64,
+    pub platform: Platform,
+}
+
+/// Why a receipt is not accepted.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum ReceiptError {
+    TooLarge(usize),
+    Schema(String),
+    /// The signing key is not in the coordinator's roster.
+    WrongPeer(String),
+    BadSignature,
+}
+
+impl ReceiptError {
+    pub fn code(&self) -> String {
+        match self {
+            ReceiptError::TooLarge(n) => format!("RECEIPT_TOO_LARGE:{n}"),
+            ReceiptError::Schema(s) => format!("RECEIPT_SCHEMA:{s}"),
+            ReceiptError::WrongPeer(fp) => format!("WRONG_PEER:{fp}"),
+            ReceiptError::BadSignature => "BAD_SIGNATURE".to_string(),
+        }
+    }
+}
+
+impl Receipt {
+    fn body(&self, key: &VerifyingKey) -> Value {
+        json!({
+            "schema": SCHEMA,
+            "attestation": "self-attested-by-worker",
+            "job": {
+                "task_id": hex_encode(&self.task_id),
+                "idempotence_key": hex_encode(&self.idempotence_key),
+                "cause_id": hex_encode(&self.cause_id),
+            },
+            "task": {
+                "kind": self.kind,
+                "input_digest": hex_encode(&self.input_digest),
+            },
+            "output_digest": hex_encode(&self.output_digest),
+            "timing": {
+                "started_unix_ms": self.started_unix_ms,
+                "compute_ns": self.compute_ns,
+                "threads": self.threads,
+            },
+            "worker": {
+                "pubkey": hex_encode(key.as_bytes()),
+                "key_fingerprint": fingerprint(key),
+                "claimed_os": self.platform.os,
+                "claimed_arch": self.platform.arch,
+                "claimed_cpus": self.platform.cpus,
+                "claimed_memory_bytes": self.platform.memory_bytes,
+                "claimed_program_digest": hex_encode(&self.platform.program_digest),
+                "claimed_version": self.platform.version,
+            },
+        })
+    }
+
+    /// Sign and serialise. The signature covers the canonical bytes of every
+    /// member except `signature`.
+    pub fn sign(&self, key: &SigningKey) -> Vec<u8> {
+        let mut v = self.body(&key.verifying_key());
+        let bytes = signed_bytes(&v).expect("receipt body is canonical-encodable");
+        let sig = key.sign(&bytes);
+        v["signature"] = Value::String(hex_encode(&sig.to_bytes()));
+        serde_json::to_vec(&v).expect("receipt serialises")
+    }
+
+    /// Parse, check the schema, check the key is pinned and the signature
+    /// verifies (strict: no small-order keys, canonical s).
+    pub fn verify(
+        bytes: &[u8],
+        roster: &[VerifyingKey],
+    ) -> Result<(Receipt, VerifyingKey), ReceiptError> {
+        if bytes.len() > MAX_RECEIPT_BYTES {
+            return Err(ReceiptError::TooLarge(bytes.len()));
+        }
+        let v: Value =
+            serde_json::from_slice(bytes).map_err(|e| ReceiptError::Schema(e.to_string()))?;
+        let s = |path: &[&str]| -> Result<String, ReceiptError> {
+            let mut cur = &v;
+            for p in path {
+                cur = cur
+                    .get(p)
+                    .ok_or_else(|| ReceiptError::Schema(format!("missing {}", path.join("."))))?;
+            }
+            cur.as_str()
+                .map(str::to_string)
+                .ok_or_else(|| ReceiptError::Schema(format!("{} not a string", path.join("."))))
+        };
+        let u = |path: &[&str]| -> Result<u64, ReceiptError> {
+            let mut cur = &v;
+            for p in path {
+                cur = cur
+                    .get(p)
+                    .ok_or_else(|| ReceiptError::Schema(format!("missing {}", path.join("."))))?;
+            }
+            cur.as_u64()
+                .ok_or_else(|| ReceiptError::Schema(format!("{} not an integer", path.join("."))))
+        };
+        fn fixed<const N: usize>(name: &str, hex: &str) -> Result<[u8; N], ReceiptError> {
+            hex_decode(hex)
+                .and_then(|b| b.try_into().ok())
+                .ok_or_else(|| ReceiptError::Schema(format!("{name} is not {N} bytes of hex")))
+        }
+        if s(&["schema"])? != SCHEMA {
+            return Err(ReceiptError::Schema("schema".to_string()));
+        }
+        let pk: [u8; 32] = fixed("worker.pubkey", &s(&["worker", "pubkey"])?)?;
+        let key = roster
+            .iter()
+            .find(|k| k.as_bytes() == &pk)
+            .copied()
+            .ok_or_else(|| ReceiptError::WrongPeer(hex_encode(&pk)))?;
+        if s(&["worker", "key_fingerprint"])? != fingerprint(&key) {
+            return Err(ReceiptError::Schema("worker.key_fingerprint".to_string()));
+        }
+        let sig: [u8; 64] = fixed("signature", &s(&["signature"])?)?;
+        let signed = signed_bytes(&v).map_err(|e| ReceiptError::Schema(format!("{e:?}")))?;
+        key.verify_strict(&signed, &Signature::from_bytes(&sig))
+            .map_err(|_| ReceiptError::BadSignature)?;
+        let r = Receipt {
+            task_id: fixed("job.task_id", &s(&["job", "task_id"])?)?,
+            idempotence_key: fixed("job.idempotence_key", &s(&["job", "idempotence_key"])?)?,
+            cause_id: fixed("job.cause_id", &s(&["job", "cause_id"])?)?,
+            kind: s(&["task", "kind"])?,
+            input_digest: fixed("task.input_digest", &s(&["task", "input_digest"])?)?,
+            output_digest: fixed("output_digest", &s(&["output_digest"])?)?,
+            started_unix_ms: u(&["timing", "started_unix_ms"])?,
+            compute_ns: u(&["timing", "compute_ns"])?,
+            threads: u(&["timing", "threads"])?,
+            platform: Platform {
+                os: s(&["worker", "claimed_os"])?,
+                arch: s(&["worker", "claimed_arch"])?,
+                cpus: u(&["worker", "claimed_cpus"])?,
+                memory_bytes: u(&["worker", "claimed_memory_bytes"])?,
+                program_digest: fixed(
+                    "worker.claimed_program_digest",
+                    &s(&["worker", "claimed_program_digest"])?,
+                )?,
+                version: s(&["worker", "claimed_version"])?,
+            },
+        };
+        // The canonical body must be exactly what this key signs for these
+        // facts: no extra or renamed members ride along under the signature.
+        let mut expect = r.body(&key);
+        expect["signature"] = v["signature"].clone();
+        if expect != v {
+            return Err(ReceiptError::Schema("unexpected members".to_string()));
+        }
+        Ok((r, key))
+    }
+}
diff --git a/crates/aien-hetjob/src/store.rs b/crates/aien-hetjob/src/store.rs
new file mode 100644
index 00000000..7883a7b4
--- /dev/null
+++ b/crates/aien-hetjob/src/store.rs
@@ -0,0 +1,110 @@
+//! The worker's state folder: signing key, an exclusive lock and the durable
+//! results that make a repeated request idempotent.
+//!
+//! A result is keyed by the idempotence key and bound to the task id and the
+//! request digest inside its receipt (PST1 section 8: same key and same task
+//! is the same request). It is written to a temporary file, synced, renamed
+//! and the folder synced, before the worker sends `completed`.
+
+use crate::receipt::{Receipt, ReceiptError};
+use aien_test::bundle::hex_encode;
+use ed25519_dalek::VerifyingKey;
+use std::fs::{self, File, OpenOptions};
+use std::io::{self, Write};
+use std::os::unix::io::AsRawFd;
+use std::path::{Path, PathBuf};
+
+pub const KEY_FILE: &str = "worker.key";
+const LOCK_FILE: &str = "LOCK";
+const RESULTS: &str = "results";
+
+/// An open state folder. Holding it holds the lock.
+pub struct Store {
+    dir: PathBuf,
+    _lock: File,
+}
+
+/// What a lookup found under one idempotence key.
+pub enum Lookup {
+    Missing,
+    /// Same task id and request digest: the stored receipt bytes.
+    Same(Vec<u8>),
+    /// The key is already bound to a different request.
+    Conflict,
+}
+
+impl Store {
+    /// Open (creating if needed) and take the exclusive lock. A second
+    /// opener, in this or another process, gets `WouldBlock`.
+    pub fn open(dir: &Path) -> io::Result<Store> {
+        fs::create_dir_all(dir.join(RESULTS))?;
+        let lock = OpenOptions::new()
+            .create(true)
+            .truncate(false)
+            .write(true)
+            .open(dir.join(LOCK_FILE))?;
+        // SAFETY: flock on a file descriptor we own; no memory is shared.
+        let rc = unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
+        if rc != 0 {
+            return Err(io::Error::new(
+                io::ErrorKind::WouldBlock,
+                "another worker holds this state folder",
+            ));
+        }
+        Ok(Store {
+            dir: dir.to_path_buf(),
+            _lock: lock,
+        })
+    }
+
+    pub fn key_path(&self) -> PathBuf {
+        self.dir.join(KEY_FILE)
+    }
+
+    fn result_path(&self, idem: &[u8; 16]) -> PathBuf {
+        self.dir
+            .join(RESULTS)
+            .join(format!("{}.receipt", hex_encode(idem)))
+    }
+
+    /// Look up a stored result. The stored receipt is re-verified against the
+    /// worker's own key, so a damaged file is never replayed.
+    pub fn lookup(
+        &self,
+        idem: &[u8; 16],
+        task_id: &[u8; 16],
+        input_digest: &[u8; 32],
+        own_key: &VerifyingKey,
+    ) -> io::Result<Lookup> {
+        let bytes = match fs::read(self.result_path(idem)) {
+            Ok(b) => b,
+            Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(Lookup::Missing),
+            Err(e) => return Err(e),
+        };
+        let (r, _) =
+            Receipt::verify(&bytes, std::slice::from_ref(own_key)).map_err(|e: ReceiptError| {
+                io::Error::new(
+                    io::ErrorKind::InvalidData,
+                    format!("stored receipt refused: {}", e.code()),
+                )
+            })?;
+        if &r.task_id == task_id && &r.input_digest == input_digest {
+            Ok(Lookup::Same(bytes))
+        } else {
+            Ok(Lookup::Conflict)
+        }
+    }
+
+    /// Store a receipt durably under its idempotence key.
+    pub fn put(&self, idem: &[u8; 16], receipt: &[u8]) -> io::Result<()> {
+        let path = self.result_path(idem);
+        let tmp = path.with_extension("tmp");
+        {
+            let mut f = File::create(&tmp)?;
+            f.write_all(receipt)?;
+            f.sync_all()?;
+        }
+        fs::rename(&tmp, &path)?;
+        File::open(self.dir.join(RESULTS))?.sync_all()
+    }
+}
diff --git a/crates/aien-hetjob/src/task.rs b/crates/aien-hetjob/src/task.rs
new file mode 100644
index 00000000..78a00bce
--- /dev/null
+++ b/crates/aien-hetjob/src/task.rs
@@ -0,0 +1,339 @@
+//! The allowlist: the only jobs a worker runs, their request payloads, the
+//! admission arithmetic, the worker's computation and the coordinator's
+//! independent recompute.
+//!
+//! Every kind is integer-exact (wrapping u32 arithmetic, SHA-256), so an
+//! x86_64 and an aarch64 machine must produce the same digest bit for bit.
+//! There is no floating point anywhere in this file.
+
+use sha2::{Digest, Sha256};
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::time::{Duration, Instant};
+
+/// Fixed-shape matrix product C = A x B over wrapping u32, inputs generated
+/// from a seed. Payload: kind, m, k, n (u16 BE each), seed (u64 BE).
+pub const KIND_MATMUL_U32: u8 = 1;
+/// SHA-256 applied `rounds` times to a 32-byte seed. Payload: kind,
+/// rounds (u32 BE), seed (32 bytes).
+pub const KIND_DIGEST_CHAIN: u8 = 2;
+
+const MATMUL_LEN: usize = 1 + 2 + 2 + 2 + 8;
+const CHAIN_LEN: usize = 1 + 4 + 32;
+const MATMUL_DOMAIN: &[u8] = b"AIEN-HETJOB-MATMUL-U32-V1";
+
+/// How often (in inner work items) the worker looks at the cancel flag and
+/// the deadline.
+const CHECK_EVERY: u32 = 4096;
+
+/// One allowlisted job.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum TaskSpec {
+    MatmulU32 { m: u16, k: u16, n: u16, seed: u64 },
+    DigestChain { rounds: u32, seed: [u8; 32] },
+}
+
+/// Why a request payload is not an allowlisted job.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum SpecError {
+    /// Empty payload.
+    Empty,
+    /// A kind byte that is not on the allowlist.
+    UnknownKind(u8),
+    /// The payload length does not match the kind.
+    BadLength,
+}
+
+/// Why admission refused a well-formed job.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Denial {
+    /// A matrix dimension or the round count is zero.
+    Empty,
+    /// Admission arithmetic says the job needs more memory than allowed.
+    OverMemory { need: u64, limit: u64 },
+    /// More multiply-adds or hash rounds than allowed.
+    OverWork { need: u64, limit: u64 },
+}
+
+impl Denial {
+    pub fn code(&self) -> String {
+        match self {
+            Denial::Empty => "OVER_BUDGET:EMPTY".to_string(),
+            Denial::OverMemory { need, limit } => {
+                format!("OVER_BUDGET:MEMORY need={need} limit={limit}")
+            }
+            Denial::OverWork { need, limit } => {
+                format!("OVER_BUDGET:WORK need={need} limit={limit}")
+            }
+        }
+    }
+}
+
+/// Worker ceilings. `max_memory_bytes` and `max_work_units` are admission
+/// arithmetic checked before anything is allocated; they are not a kernel
+/// enforced ceiling (see the crate README for what the OS enforces).
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct Limits {
+    pub max_memory_bytes: u64,
+    pub max_work_units: u64,
+    pub max_wall: Duration,
+    pub max_threads: usize,
+}
+
+impl Default for Limits {
+    fn default() -> Self {
+        Limits {
+            max_memory_bytes: 512 << 20,
+            max_work_units: 1 << 34,
+            max_wall: Duration::from_secs(120),
+            max_threads: 4,
+        }
+    }
+}
+
+/// Why the worker stopped before finishing.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Abort {
+    Cancelled,
+    Timeout,
+}
+
+/// What the worker's computation may look at while it runs.
+pub struct Control<'a> {
+    pub cancel: &'a AtomicBool,
+    pub deadline: Instant,
+    pub threads: usize,
+}
+
+impl Control<'_> {
+    fn stop(&self) -> Option<Abort> {
+        if self.cancel.load(Ordering::Relaxed) {
+            Some(Abort::Cancelled)
+        } else if Instant::now() >= self.deadline {
+            Some(Abort::Timeout)
+        } else {
+            None
+        }
+    }
+}
+
+impl TaskSpec {
+    /// The request payload (well under PST1's 800 bytes).
+    pub fn encode(&self) -> Vec<u8> {
+        match *self {
+            TaskSpec::MatmulU32 { m, k, n, seed } => {
+                let mut v = Vec::with_capacity(MATMUL_LEN);
+                v.push(KIND_MATMUL_U32);
+                v.extend_from_slice(&m.to_be_bytes());
+                v.extend_from_slice(&k.to_be_bytes());
+                v.extend_from_slice(&n.to_be_bytes());
+                v.extend_from_slice(&seed.to_be_bytes());
+                v
+            }
+            TaskSpec::DigestChain { rounds, seed } => {
+                let mut v = Vec::with_capacity(CHAIN_LEN);
+                v.push(KIND_DIGEST_CHAIN);
+                v.extend_from_slice(&rounds.to_be_bytes());
+                v.extend_from_slice(&seed);
+                v
+            }
+        }
+    }
+
+    pub fn decode(b: &[u8]) -> Result<TaskSpec, SpecError> {
+        let kind = *b.first().ok_or(SpecError::Empty)?;
+        match kind {
+            KIND_MATMUL_U32 => {
+                if b.len() != MATMUL_LEN {
+                    return Err(SpecError::BadLength);
+                }
+                let u16_at = |i: usize| u16::from_be_bytes([b[i], b[i + 1]]);
+                let mut seed = [0u8; 8];
+                seed.copy_from_slice(&b[7..15]);
+                Ok(TaskSpec::MatmulU32 {
+                    m: u16_at(1),
+                    k: u16_at(3),
+                    n: u16_at(5),
+                    seed: u64::from_be_bytes(seed),
+                })
+            }
+            KIND_DIGEST_CHAIN => {
+                if b.len() != CHAIN_LEN {
+                    return Err(SpecError::BadLength);
+                }
+                let mut seed = [0u8; 32];
+                seed.copy_from_slice(&b[5..37]);
+                Ok(TaskSpec::DigestChain {
+                    rounds: u32::from_be_bytes([b[1], b[2], b[3], b[4]]),
+                    seed,
+                })
+            }
+            other => Err(SpecError::UnknownKind(other)),
+        }
+    }
+
+    pub fn kind_name(&self) -> &'static str {
+        match self {
+            TaskSpec::MatmulU32 { .. } => "matmul_u32",
+            TaskSpec::DigestChain { .. } => "digest_chain",
+        }
+    }
+
+    /// Bytes the worker allocates for this job: A, B and C for the matrix
+    /// product, nothing that scales for the digest chain.
+    pub fn memory_bytes(&self) -> u64 {
+        match *self {
+            TaskSpec::MatmulU32 { m, k, n, .. } => {
+                let (m, k, n) = (u64::from(m), u64::from(k), u64::from(n));
+                4 * (m * k + k * n + m * n)
+            }
+            TaskSpec::DigestChain { .. } => 0,
+        }
+    }
+
+    /// Multiply-adds for the matrix product, hash rounds for the chain.
+    pub fn work_units(&self) -> u64 {
+        match *self {
+            TaskSpec::MatmulU32 { m, k, n, .. } => u64::from(m) * u64::from(k) * u64::from(n),
+            TaskSpec::DigestChain { rounds, .. } => u64::from(rounds),
+        }
+    }
+
+    /// Admission: checked before any allocation.
+    pub fn admit(&self, limits: &Limits) -> Result<(), Denial> {
+        if self.work_units() == 0 {
+            return Err(Denial::Empty);
+        }
+        let need = self.memory_bytes();
+        if need > limits.max_memory_bytes {
+            return Err(Denial::OverMemory {
+                need,
+                limit: limits.max_memory_bytes,
+            });
+        }
+        let need = self.work_units();
+        if need > limits.max_work_units {
+            return Err(Denial::OverWork {
+                need,
+                limit: limits.max_work_units,
+            });
+        }
+        Ok(())
+    }
+}
+
+fn splitmix64(state: &mut u64) -> u64 {
+    *state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);
+    let mut z = *state;
+    z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
+    z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
+    z ^ (z >> 31)
+}
+
+/// A (m x k, row major) then B (k x n, row major) from one splitmix64 stream.
+pub fn matmul_inputs(m: usize, k: usize, n: usize, seed: u64) -> (Vec<u32>, Vec<u32>) {
+    let mut s = seed;
+    let a = (0..m * k).map(|_| splitmix64(&mut s) as u32).collect();
+    let b = (0..k * n).map(|_| splitmix64(&mut s) as u32).collect();
+    (a, b)
+}
+
+fn matmul_digest(m: u16, k: u16, n: u16, seed: u64, c: &[u32]) -> [u8; 32] {
+    let mut h = Sha256::new();
+    h.update(MATMUL_DOMAIN);
+    h.update(m.to_be_bytes());
+    h.update(k.to_be_bytes());
+    h.update(n.to_be_bytes());
+    h.update(seed.to_be_bytes());
+    for x in c {
+        h.update(x.to_be_bytes());
+    }
+    h.finalize().into()
+}
+
+/// The worker's computation: row bands across threads, i-k-j order inside a
+/// band, cancel flag and deadline checked between rows.
+pub fn run(spec: &TaskSpec, ctl: &Control) -> Result<[u8; 32], Abort> {
+    match *spec {
+        TaskSpec::MatmulU32 { m, k, n, seed } => {
+            let (mu, ku, nu) = (usize::from(m), usize::from(k), usize::from(n));
+            let (a, b) = matmul_inputs(mu, ku, nu, seed);
+            let mut c = vec![0u32; mu * nu];
+            let threads = ctl.threads.clamp(1, mu.max(1));
+            let band = mu.div_ceil(threads);
+            let abort = std::thread::scope(|s| {
+                let mut handles = Vec::new();
+                for (t, rows) in c.chunks_mut(band * nu).enumerate() {
+                    let (a, b) = (&a, &b);
+                    handles.push(s.spawn(move || {
+                        let i0 = t * band;
+                        for (di, crow) in rows.chunks_mut(nu).enumerate() {
+                            if let Some(why) = ctl.stop() {
+                                return Some(why);
+                            }
+                            let arow = &a[(i0 + di) * ku..(i0 + di + 1) * ku];
+                            for (p, &aip) in arow.iter().enumerate() {
+                                let brow = &b[p * nu..(p + 1) * nu];
+                                for (cij, &bpj) in crow.iter_mut().zip(brow) {
+                                    *cij = cij.wrapping_add(aip.wrapping_mul(bpj));
+                                }
+                            }
+                        }
+                        None
+                    }));
+                }
+                handles
+                    .into_iter()
+                    .filter_map(|h| h.join().expect("matmul band panicked"))
+                    .next()
+            });
+            match abort {
+                Some(why) => Err(why),
+                None => Ok(matmul_digest(m, k, n, seed, &c)),
+            }
+        }
+        TaskSpec::DigestChain { rounds, seed } => {
+            let mut h = seed;
+            for i in 0..rounds {
+                if i % CHECK_EVERY == 0 {
+                    if let Some(why) = ctl.stop() {
+                        return Err(why);
+                    }
+                }
+                h = Sha256::digest(h).into();
+            }
+            Ok(h)
+        }
+    }
+}
+
+/// The coordinator's recompute. The matrix product uses a different loop
+/// order (i-j-k dot products, one thread) from the worker, so a shared bug in
+/// the blocked loop does not hide. The digest chain has only one algorithm;
+/// its independence is a different machine and a different build, nothing
+/// more.
+pub fn oracle(spec: &TaskSpec) -> [u8; 32] {
+    match *spec {
+        TaskSpec::MatmulU32 { m, k, n, seed } => {
+            let (mu, ku, nu) = (usize::from(m), usize::from(k), usize::from(n));
+            let (a, b) = matmul_inputs(mu, ku, nu, seed);
+            let mut c = vec![0u32; mu * nu];
+            for i in 0..mu {
+                for j in 0..nu {
+                    let mut acc = 0u32;
+                    for p in 0..ku {
+                        acc = acc.wrapping_add(a[i * ku + p].wrapping_mul(b[p * nu + j]));
+                    }
+                    c[i * nu + j] = acc;
+                }
+            }
+            matmul_digest(m, k, n, seed, &c)
+        }
+        TaskSpec::DigestChain { rounds, seed } => {
+            let mut h = seed;
+            for _ in 0..rounds {
+                h = Sha256::digest(h).into();
+            }
+            h
+        }
+    }
+}
diff --git a/crates/aien-hetjob/src/wire.rs b/crates/aien-hetjob/src/wire.rs
new file mode 100644
index 00000000..2dd16ebf
--- /dev/null
+++ b/crates/aien-hetjob/src/wire.rs
@@ -0,0 +1,162 @@
+//! PST1 messages on a byte stream.
+//!
+//! The stream (SSH stdio, or a socket pair in tests) carries one PST1 message
+//! per frame: a u16 big-endian length, then exactly that many bytes, at most
+//! `pst::MAX_MESSAGE` (1024). That is the M6-A rule of one PST1 message per
+//! transport message; nothing is reassembled across frames.
+//!
+//! Roles: the coordinator sends PST1's requester types (`request`,
+//! `cancel_request`); the worker sends the executor types. PST1 Draft v0.1
+//! names those sides "Pi" and "Spark"; here the Spark is the requester. Every
+//! status the worker sends is a hint to the coordinator, which owns the open
+//! job, the deadline and the connection.
+
+use aien_pi_spark_task as pst;
+use std::io::{self, Read, Write};
+
+pub const T_REQUEST: u8 = 1;
+pub const T_ACCEPTED: u8 = 2;
+pub const T_RUNNING: u8 = 4;
+pub const T_TEXT_CHUNK: u8 = 5;
+pub const T_COMPLETED: u8 = 7;
+pub const T_FAILED: u8 = 8;
+pub const T_CANCELLED: u8 = 9;
+pub const T_RECEIPT_REFERENCE: u8 = 12;
+pub const T_CANCEL_REQUEST: u8 = 13;
+pub const T_RESUME_REQUEST: u8 = 14;
+
+/// PST1 `effect_class` COMPUTE: the only class a worker admits.
+pub const EFFECT_COMPUTE: u8 = 1;
+
+/// True for the types only the requester (coordinator) may send.
+pub fn requester_type(t: u8) -> bool {
+    matches!(t, T_REQUEST | T_CANCEL_REQUEST | T_RESUME_REQUEST)
+}
+
+/// The identifiers one job carries in every PST1 header.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct Ids {
+    pub cause_id: [u8; 32],
+    pub origin_run_id: [u8; 32],
+    pub objective_id: [u8; 32],
+    pub subject_id: [u8; 32],
+    pub task_id: [u8; 16],
+    pub idempotence_key: [u8; 16],
+}
+
+impl Ids {
+    pub fn of(h: &pst::Header) -> Ids {
+        Ids {
+            cause_id: h.cause_id,
+            origin_run_id: h.origin_run_id,
+            objective_id: h.objective_id,
+            subject_id: h.subject_id,
+            task_id: h.task_id,
+            idempotence_key: h.idempotence_key,
+        }
+    }
+}
+
+/// A decoded message that owns its payload.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Msg {
+    pub header: pst::Header,
+    pub payload: Vec<u8>,
+}
+
+/// Build one PST1 message.
+pub fn build(ids: &Ids, msg_type: u8, ordinal: u32, payload: &[u8]) -> Vec<u8> {
+    assert!(
+        payload.len() <= pst::MAX_PAYLOAD,
+        "PST1 payload above 800 bytes"
+    );
+    let h = pst::Header {
+        version: pst::VERSION,
+        msg_type,
+        cause_id: ids.cause_id,
+        origin_run_id: ids.origin_run_id,
+        objective_id: ids.objective_id,
+        subject_id: ids.subject_id,
+        parent_task_id: [0; 16],
+        task_id: ids.task_id,
+        idempotence_key: ids.idempotence_key,
+        ordinal,
+        effect_class: EFFECT_COMPUTE,
+        payload_len: payload.len() as u16,
+        payload_digest: pst::payload_digest(payload),
+    };
+    let mut out = vec![0u8; pst::HEADER_LEN + payload.len()];
+    let n = pst::encode(&h, payload, &mut out).expect("PST1 encode of a bounded payload");
+    out.truncate(n);
+    out
+}
+
+/// Write one frame and flush.
+pub fn write_frame(w: &mut impl Write, msg: &[u8]) -> io::Result<()> {
+    if msg.len() > pst::MAX_MESSAGE {
+        return Err(io::Error::new(
+            io::ErrorKind::InvalidInput,
+            "frame above 1024 bytes",
+        ));
+    }
+    w.write_all(&(msg.len() as u16).to_be_bytes())?;
+    w.write_all(msg)?;
+    w.flush()
+}
+
+/// Read one frame. `Ok(None)` is a clean end of stream at a frame boundary.
+/// A declared length above 1024 is an error before any body byte is read.
+pub fn read_frame(r: &mut impl Read) -> io::Result<Option<Vec<u8>>> {
+    let mut len = [0u8; 2];
+    match r.read(&mut len[..1])? {
+        0 => return Ok(None),
+        _ => r.read_exact(&mut len[1..])?,
+    }
+    let n = usize::from(u16::from_be_bytes(len));
+    if n > pst::MAX_MESSAGE {
+        return Err(io::Error::new(
+            io::ErrorKind::InvalidData,
+            format!("frame length {n} above 1024"),
+        ));
+    }
+    let mut body = vec![0u8; n];
+    r.read_exact(&mut body)?;
+    Ok(Some(body))
+}
+
+/// Decode a frame with the PST1 reader; the refusal code is the spec's.
+pub fn decode(frame: &[u8]) -> Result<Msg, pst::Refusal> {
+    let m = pst::decode(frame)?;
+    Ok(Msg {
+        header: m.header,
+        payload: m.payload.to_vec(),
+    })
+}
+
+/// What a reader thread hands to its owner.
+#[derive(Debug)]
+pub enum Inbound {
+    Msg(Box<Msg>),
+    Refused(pst::Refusal),
+    Eof,
+    Broken(String),
+}
+
+/// Read frames until end of stream, decoding each, and send them on `tx`.
+/// Stops after the first end, I/O error or closed channel.
+pub fn pump<T>(mut r: impl Read, tx: std::sync::mpsc::Sender<T>, wrap: impl Fn(Inbound) -> T) {
+    loop {
+        let item = match read_frame(&mut r) {
+            Ok(Some(f)) => match decode(&f) {
+                Ok(m) => Inbound::Msg(Box::new(m)),
+                Err(code) => Inbound::Refused(code),
+            },
+            Ok(None) => Inbound::Eof,
+            Err(e) => Inbound::Broken(e.to_string()),
+        };
+        let last = matches!(item, Inbound::Eof | Inbound::Broken(_));
+        if tx.send(wrap(item)).is_err() || last {
+            return;
+        }
+    }
+}
diff --git a/crates/aien-hetjob/src/worker.rs b/crates/aien-hetjob/src/worker.rs
new file mode 100644
index 00000000..f8dc355e
--- /dev/null
+++ b/crates/aien-hetjob/src/worker.rs
@@ -0,0 +1,294 @@
+//! The worker: admits allowlisted jobs one at a time and answers in PST1.
+//!
+//! Reply sequence for an admitted job (worker ordinals, from 0):
+//! `accepted`, `running`, then on success the receipt as consecutive
+//! `text_chunk` messages, `receipt_reference` (SHA-256 of the receipt bytes)
+//! and `completed` (the 32-byte output digest). The receipt is stored durably
+//! before `completed` is sent. A cancel ends in `cancelled`; the deadline in
+//! `failed` with `TIMEOUT`. A request that is not admitted gets one `failed`
+//! with ordinal 0 and creates no task.
+
+use crate::receipt::{Platform, Receipt};
+use crate::store::{Lookup, Store};
+use crate::task::{self, Abort, Control, Limits, TaskSpec};
+use crate::wire::{self, Ids, Inbound, Msg};
+use aien_pi_spark_task as pst;
+use ed25519_dalek::SigningKey;
+use sha2::{Digest, Sha256};
+use std::io::{self, Read, Write};
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::mpsc;
+use std::sync::Arc;
+use std::time::{Instant, SystemTime, UNIX_EPOCH};
+
+pub struct Worker {
+    pub key: SigningKey,
+    pub limits: Limits,
+    pub store: Store,
+    pub platform: Platform,
+}
+
+/// Counts for one served connection.
+#[derive(Debug, Default, Clone, PartialEq, Eq)]
+pub struct Summary {
+    pub completed: u32,
+    pub replayed: u32,
+    pub denied: u32,
+    pub cancelled: u32,
+    pub failed: u32,
+    /// Frames the PST1 reader refused (no reply is possible without ids).
+    pub refused_frames: u32,
+}
+
+enum Event {
+    In(Inbound),
+    Done(Finished),
+}
+
+struct Finished {
+    task_id: [u8; 16],
+    result: Result<[u8; 32], Abort>,
+    started_unix_ms: u64,
+    compute_ns: u64,
+}
+
+struct Running {
+    ids: Ids,
+    spec: TaskSpec,
+    input_digest: [u8; 32],
+    cancel: Arc<AtomicBool>,
+    handle: std::thread::JoinHandle<()>,
+    next: u32,
+}
+
+fn send(w: &mut impl Write, ids: &Ids, t: u8, ordinal: u32, payload: &[u8]) -> io::Result<()> {
+    wire::write_frame(w, &wire::build(ids, t, ordinal, payload))
+}
+
+/// Receipt chunks, reference and `completed`, starting at ordinal `next`.
+fn deliver(
+    w: &mut impl Write,
+    ids: &Ids,
+    mut next: u32,
+    receipt: &[u8],
+    output: &[u8; 32],
+) -> io::Result<()> {
+    for chunk in receipt.chunks(pst::MAX_PAYLOAD) {
+        send(w, ids, wire::T_TEXT_CHUNK, next, chunk)?;
+        next += 1;
+    }
+    let reference: [u8; 32] = Sha256::digest(receipt).into();
+    send(w, ids, wire::T_RECEIPT_REFERENCE, next, &reference)?;
+    send(w, ids, wire::T_COMPLETED, next + 1, output)
+}
+
+fn peer_gone(e: &io::Error) -> bool {
+    matches!(
+        e.kind(),
+        io::ErrorKind::BrokenPipe
+            | io::ErrorKind::ConnectionReset
+            | io::ErrorKind::ConnectionAborted
+    )
+}
+
+fn unix_ms() -> u64 {
+    SystemTime::now()
+        .duration_since(UNIX_EPOCH)
+        .map(|d| d.as_millis() as u64)
+        .unwrap_or(0)
+}
+
+impl Worker {
+    /// Serve one connection until the peer closes it. Returns the counts.
+    pub fn serve<R: Read + Send + 'static, W: Write>(&self, r: R, mut w: W) -> io::Result<Summary> {
+        let (tx, rx) = mpsc::channel::<Event>();
+        let reader_tx = tx.clone();
+        std::thread::spawn(move || wire::pump(r, reader_tx, Event::In));
+        let mut running: Option<Running> = None;
+        let mut sum = Summary::default();
+        let res = self.serve_loop(&mut w, &tx, &rx, &mut running, &mut sum);
+        if let Some(job) = running.take() {
+            job.cancel.store(true, Ordering::Relaxed);
+            let _ = job.handle.join();
+        }
+        match res {
+            // The peer may hang up while a reply is being written (it refused
+            // this worker, or gave up): that ends the session like end of input.
+            Err(e) if !peer_gone(&e) => Err(e),
+            _ => Ok(sum),
+        }
+    }
+
+    fn serve_loop<W: Write>(
+        &self,
+        mut w: W,
+        tx: &mpsc::Sender<Event>,
+        rx: &mpsc::Receiver<Event>,
+        running: &mut Option<Running>,
+        sum: &mut Summary,
+    ) -> io::Result<()> {
+        loop {
+            let ev = rx.recv().expect("worker holds a sender");
+            match ev {
+                Event::In(Inbound::Msg(m)) => self.on_msg(&mut w, tx, running, sum, *m)?,
+                Event::In(Inbound::Refused(_)) => sum.refused_frames += 1,
+                Event::In(Inbound::Eof) | Event::In(Inbound::Broken(_)) => return Ok(()),
+                Event::Done(fin) => {
+                    let Some(job) = running.take() else { continue };
+                    if job.ids.task_id != fin.task_id {
+                        *running = Some(job);
+                        continue;
+                    }
+                    let _ = job.handle.join();
+                    match fin.result {
+                        Ok(output) => {
+                            let receipt = Receipt {
+                                task_id: job.ids.task_id,
+                                idempotence_key: job.ids.idempotence_key,
+                                cause_id: job.ids.cause_id,
+                                kind: job.spec.kind_name().to_string(),
+                                input_digest: job.input_digest,
+                                output_digest: output,
+                                started_unix_ms: fin.started_unix_ms,
+                                compute_ns: fin.compute_ns,
+                                threads: self.limits.max_threads as u64,
+                                platform: self.platform.clone(),
+                            }
+                            .sign(&self.key);
+                            if let Err(e) = self.store.put(&job.ids.idempotence_key, &receipt) {
+                                sum.failed += 1;
+                                send(
+                                    &mut w,
+                                    &job.ids,
+                                    wire::T_FAILED,
+                                    job.next,
+                                    format!("STORE_ERROR:{e}").as_bytes(),
+                                )?;
+                            } else {
+                                sum.completed += 1;
+                                deliver(&mut w, &job.ids, job.next, &receipt, &output)?;
+                            }
+                        }
+                        Err(Abort::Cancelled) => {
+                            sum.cancelled += 1;
+                            send(&mut w, &job.ids, wire::T_CANCELLED, job.next, &[])?;
+                        }
+                        Err(Abort::Timeout) => {
+                            sum.failed += 1;
+                            send(&mut w, &job.ids, wire::T_FAILED, job.next, b"TIMEOUT")?;
+                        }
+                    }
+                }
+            }
+        }
+    }
+
+    fn on_msg<W2: Write>(
+        &self,
+        w: &mut W2,
+        tx: &mpsc::Sender<Event>,
+        running: &mut Option<Running>,
+        sum: &mut Summary,
+        m: Msg,
+    ) -> io::Result<()> {
+        let ids = Ids::of(&m.header);
+        let t = m.header.msg_type;
+        if !wire::requester_type(t) {
+            return deny(
+                w,
+                sum,
+                &ids,
+                format!("REFUSED:{}", pst::Refusal::WrongSide.code()),
+            );
+        }
+        match t {
+            wire::T_CANCEL_REQUEST => {
+                if let Some(job) = running.as_ref().filter(|j| j.ids.task_id == ids.task_id) {
+                    job.cancel.store(true, Ordering::Relaxed);
+                }
+                Ok(())
+            }
+            wire::T_RESUME_REQUEST => deny(w, sum, &ids, "UNSUPPORTED:resume_request"),
+            _ => {
+                if let Some(job) = running.as_ref() {
+                    if job.ids.task_id == ids.task_id
+                        && job.ids.idempotence_key == ids.idempotence_key
+                    {
+                        return Ok(()); // the same request again while it runs
+                    }
+                    return deny(w, sum, &ids, "BUSY");
+                }
+                if m.header.effect_class != wire::EFFECT_COMPUTE {
+                    return deny(w, sum, &ids, "DENIED_EFFECT");
+                }
+                let spec = match TaskSpec::decode(&m.payload) {
+                    Ok(s) => s,
+                    Err(e) => return deny(w, sum, &ids, format!("DENIED_TASK:{e:?}")),
+                };
+                if let Err(d) = spec.admit(&self.limits) {
+                    return deny(w, sum, &ids, d.code());
+                }
+                let input_digest = m.header.payload_digest;
+                match self.store.lookup(
+                    &ids.idempotence_key,
+                    &ids.task_id,
+                    &input_digest,
+                    &self.key.verifying_key(),
+                ) {
+                    Ok(Lookup::Missing) => {}
+                    Ok(Lookup::Same(receipt)) => {
+                        let (r, _) = Receipt::verify(&receipt, &[self.key.verifying_key()])
+                            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.code()))?;
+                        sum.replayed += 1;
+                        send(w, &ids, wire::T_ACCEPTED, 0, &[])?;
+                        return deliver(w, &ids, 1, &receipt, &r.output_digest);
+                    }
+                    Ok(Lookup::Conflict) => return deny(w, sum, &ids, "DUPLICATE_ID"),
+                    Err(e) => return deny(w, sum, &ids, format!("STORE_REFUSED:{e}")),
+                }
+                send(w, &ids, wire::T_ACCEPTED, 0, &[])?;
+                send(w, &ids, wire::T_RUNNING, 1, &[])?;
+                let cancel = Arc::new(AtomicBool::new(false));
+                let (flag, done, limits, task_id) =
+                    (cancel.clone(), tx.clone(), self.limits, ids.task_id);
+                let handle = std::thread::spawn(move || {
+                    let started_unix_ms = unix_ms();
+                    let t0 = Instant::now();
+                    let ctl = Control {
+                        cancel: &flag,
+                        deadline: t0 + limits.max_wall,
+                        threads: limits.max_threads,
+                    };
+                    let result = task::run(&spec, &ctl);
+                    let compute_ns = t0.elapsed().as_nanos() as u64;
+                    let _ = done.send(Event::Done(Finished {
+                        task_id,
+                        result,
+                        started_unix_ms,
+                        compute_ns,
+                    }));
+                });
+                *running = Some(Running {
+                    ids,
+                    spec,
+                    input_digest,
+                    cancel,
+                    handle,
+                    next: 2,
+                });
+                Ok(())
+            }
+        }
+    }
+}
+
+/// Refuse one request: a single `failed` with ordinal 0, no task created.
+fn deny<W: Write>(
+    w: &mut W,
+    sum: &mut Summary,
+    ids: &Ids,
+    reason: impl AsRef<str>,
+) -> io::Result<()> {
+    sum.denied += 1;
+    send(w, ids, wire::T_FAILED, 0, reason.as_ref().as_bytes())
+}
diff --git a/crates/aien-hetjob/tests/protocol_tests.rs b/crates/aien-hetjob/tests/protocol_tests.rs
new file mode 100644
index 00000000..7842aae1
--- /dev/null
+++ b/crates/aien-hetjob/tests/protocol_tests.rs
@@ -0,0 +1,694 @@
+//! Coordinator and worker over a socket pair: the happy path, every refusal
+//! the issue names (wrong peer, duplicate id, out of budget, stale result,
+//! timeout, cancel, disconnect, denied task) and receipt tampering.
+
+use aien_hetjob::coordinator::{dispatch, Job, OracleCheck, Outcome, Policy, Stats};
+use aien_hetjob::receipt::{Platform, Receipt};
+use aien_hetjob::store::Store;
+use aien_hetjob::task::{self, Limits, TaskSpec};
+use aien_hetjob::wire::{self, Ids, Inbound};
+use aien_hetjob::worker::{Summary, Worker};
+use aien_pi_spark_task as pst;
+use ed25519_dalek::{SigningKey, VerifyingKey};
+use sha2::{Digest, Sha256};
+use std::os::unix::net::UnixStream;
+use std::path::PathBuf;
+use std::time::Duration;
+
+fn tmpdir(tag: &str) -> PathBuf {
+    let d = std::env::temp_dir().join(format!("aien-hetjob-{tag}-{}", std::process::id()));
+    let _ = std::fs::remove_dir_all(&d);
+    std::fs::create_dir_all(&d).unwrap();
+    d
+}
+
+fn key(seed: u8) -> SigningKey {
+    SigningKey::from_bytes(&[seed; 32])
+}
+
+fn platform() -> Platform {
+    Platform {
+        os: "testos".into(),
+        arch: "testarch".into(),
+        cpus: 2,
+        memory_bytes: 1 << 30,
+        program_digest: [7; 32],
+        version: "0.1.0".into(),
+    }
+}
+
+fn worker(tag: &str, limits: Limits) -> Worker {
+    Worker {
+        key: key(1),
+        limits,
+        store: Store::open(&tmpdir(tag)).unwrap(),
+        platform: platform(),
+    }
+}
+
+fn ids(task: u8, idem: u8) -> Ids {
+    Ids {
+        cause_id: [0xC1; 32],
+        origin_run_id: [0; 32],
+        objective_id: [0x0B; 32],
+        subject_id: [0; 32],
+        task_id: [task; 16],
+        idempotence_key: [idem; 16],
+    }
+}
+
+fn policy(spec: &TaskSpec) -> Policy {
+    Policy {
+        deadline: Duration::from_secs(20),
+        cancel_grace: Duration::from_secs(5),
+        oracle: Some(task::oracle(spec)),
+    }
+}
+
+const SMALL: TaskSpec = TaskSpec::MatmulU32 {
+    m: 9,
+    k: 13,
+    n: 5,
+    seed: 42,
+};
+
+/// Run one job against a real worker on a fresh connection.
+fn run_job(
+    w: &Worker,
+    job: &Job,
+    roster: &[VerifyingKey],
+    p: &Policy,
+) -> (Outcome, Stats, Summary) {
+    let (c, s) = UnixStream::pair().unwrap();
+    std::thread::scope(|sc| {
+        let h = sc.spawn(|| {
+            let s2 = s.try_clone().unwrap();
+            w.serve(s2, s).unwrap()
+        });
+        let r = c.try_clone().unwrap();
+        let mut wr = c;
+        let (o, st) = dispatch(r, &mut wr, job, roster, p).unwrap();
+        wr.shutdown(std::net::Shutdown::Both).unwrap();
+        (o, st, h.join().unwrap())
+    })
+}
+
+/// A scripted worker: reads the request, then writes whatever `script` returns.
+fn scripted(
+    job: &Job,
+    roster: &[VerifyingKey],
+    p: &Policy,
+    script: impl FnOnce(&Ids) -> Vec<Vec<u8>> + Send,
+) -> (Outcome, Stats) {
+    let (c, mut s) = UnixStream::pair().unwrap();
+    std::thread::scope(|sc| {
+        sc.spawn(move || {
+            let req = wire::read_frame(&mut s).unwrap().unwrap();
+            let m = wire::decode(&req).unwrap();
+            for f in script(&Ids::of(&m.header)) {
+                if wire::write_frame(&mut s, &f).is_err() {
+                    return;
+                }
+            }
+            // Keep reading (a cancel may arrive) until the coordinator closes.
+            while let Ok(Some(_)) = wire::read_frame(&mut s) {}
+        });
+        let r = c.try_clone().unwrap();
+        let mut wr = c;
+        let out = dispatch(r, &mut wr, job, roster, p).unwrap();
+        wr.shutdown(std::net::Shutdown::Both).unwrap();
+        out
+    })
+}
+
+/// The frames an honest worker sends for `spec`, signed by `k`.
+fn honest_frames(ids: &Ids, spec: &TaskSpec, k: &SigningKey) -> (Vec<Vec<u8>>, Vec<u8>, [u8; 32]) {
+    let out = task::oracle(spec);
+    let receipt = Receipt {
+        task_id: ids.task_id,
+        idempotence_key: ids.idempotence_key,
+        cause_id: ids.cause_id,
+        kind: spec.kind_name().into(),
+        input_digest: Sha256::digest(spec.encode()).into(),
+        output_digest: out,
+        started_unix_ms: 1,
+        compute_ns: 2,
+        threads: 1,
+        platform: platform(),
+    }
+    .sign(k);
+    (frames_for(ids, &receipt, &out), receipt, out)
+}
+
+fn frames_for(ids: &Ids, receipt: &[u8], out: &[u8; 32]) -> Vec<Vec<u8>> {
+    let mut f = vec![
+        wire::build(ids, wire::T_ACCEPTED, 0, &[]),
+        wire::build(ids, wire::T_RUNNING, 1, &[]),
+    ];
+    let mut ord = 2;
+    for c in receipt.chunks(pst::MAX_PAYLOAD) {
+        f.push(wire::build(ids, wire::T_TEXT_CHUNK, ord, c));
+        ord += 1;
+    }
+    let r: [u8; 32] = Sha256::digest(receipt).into();
+    f.push(wire::build(ids, wire::T_RECEIPT_REFERENCE, ord, &r));
+    f.push(wire::build(ids, wire::T_COMPLETED, ord + 1, out));
+    f
+}
+
+fn rejected(o: &Outcome) -> String {
+    match o {
+        Outcome::Rejected(s) => s.clone(),
+        other => panic!("expected Rejected, got {other:?}"),
+    }
+}
+
+fn failed(o: &Outcome) -> String {
+    match o {
+        Outcome::Failed(s) => s.clone(),
+        other => panic!("expected Failed, got {other:?}"),
+    }
+}
+
+#[test]
+fn verified_matmul_and_chain_match_the_oracle() {
+    let w = worker("happy", Limits::default());
+    let roster = [key(1).verifying_key()];
+    for spec in [
+        SMALL,
+        TaskSpec::DigestChain {
+            rounds: 5000,
+            seed: [3; 32],
+        },
+    ] {
+        let job = Job {
+            spec,
+            ids: ids(1, 1 + spec.encode()[0]),
+        };
+        let (o, st, sum) = run_job(&w, &job, &roster, &policy(&spec));
+        match o {
+            Outcome::Verified(v) => {
+                assert_eq!(v.oracle, OracleCheck::Matched);
+                assert_eq!(v.output, task::oracle(&spec));
+                assert_eq!(v.receipt.platform, platform());
+            }
+            other => panic!("{other:?}"),
+        }
+        assert_eq!(st.stale_ignored, 0);
+        assert_eq!(sum.completed, 1);
+    }
+}
+
+/// Frozen answers: every machine, every architecture, must give exactly
+/// these digests. A mismatch on any host is a FAIL no matter what else agrees.
+#[test]
+fn golden_digests_are_frozen() {
+    let hex = |d: [u8; 32]| d.iter().map(|b| format!("{b:02x}")).collect::<String>();
+    let cases = [
+        (
+            TaskSpec::MatmulU32 {
+                m: 1,
+                k: 1,
+                n: 1,
+                seed: 0,
+            },
+            GOLD_1X1X1,
+        ),
+        (
+            TaskSpec::MatmulU32 {
+                m: 64,
+                k: 48,
+                n: 32,
+                seed: 7,
+            },
+            GOLD_64X48X32,
+        ),
+        (
+            TaskSpec::MatmulU32 {
+                m: 257,
+                k: 129,
+                n: 63,
+                seed: 637,
+            },
+            GOLD_257X129X63,
+        ),
+        (
+            TaskSpec::DigestChain {
+                rounds: 100_000,
+                seed: [0xAB; 32],
+            },
+            GOLD_CHAIN_100K,
+        ),
+    ];
+    for (spec, want) in cases {
+        assert_eq!(hex(task::oracle(&spec)), want, "{spec:?}");
+    }
+}
+
+const GOLD_1X1X1: &str = "ba9dd3b4a9ec4978d83ac9e8fb8027811cd1159a2213ff8275979ced89ada395";
+const GOLD_64X48X32: &str = "45a719e726d84e362c0d334773d0952540e4538d690456bb7f00e2ca9e851497";
+const GOLD_257X129X63: &str = "156a39687d2d61627f1df918c4187ae5d923bd6c12b45d390397384880a0e25c";
+const GOLD_CHAIN_100K: &str = "10430bf8db9967c61125c551188b695087b206817032692bb40e09d7c07f50b7";
+
+#[test]
+fn worker_algorithm_equals_oracle_for_awkward_shapes_and_threads() {
+    let never = std::sync::atomic::AtomicBool::new(false);
+    for (m, k, n) in [(1, 1, 1), (3, 1, 7), (17, 33, 1), (64, 64, 64), (5, 200, 9)] {
+        for threads in [1, 2, 3, 8, 64] {
+            let spec = TaskSpec::MatmulU32 {
+                m,
+                k,
+                n,
+                seed: u64::from(m) * 1000 + u64::from(n),
+            };
+            let ctl = task::Control {
+                cancel: &never,
+                deadline: std::time::Instant::now() + Duration::from_secs(60),
+                threads,
+            };
+            assert_eq!(
+                task::run(&spec, &ctl).unwrap(),
+                task::oracle(&spec),
+                "{spec:?} threads={threads}"
+            );
+        }
+    }
+}
+
+#[test]
+fn wrong_peer_is_rejected() {
+    let w = worker("wrongpeer", Limits::default());
+    let job = Job {
+        spec: SMALL,
+        ids: ids(2, 2),
+    };
+    let (o, _, _) = run_job(&w, &job, &[key(9).verifying_key()], &policy(&SMALL));
+    assert!(rejected(&o).starts_with("WRONG_PEER:"), "{o:?}");
+}
+
+#[test]
+fn duplicate_id_is_refused_and_same_request_replays() {
+    let w = worker("dup", Limits::default());
+    let roster = [key(1).verifying_key()];
+    let first = Job {
+        spec: SMALL,
+        ids: ids(3, 3),
+    };
+    assert!(matches!(
+        run_job(&w, &first, &roster, &policy(&SMALL)).0,
+        Outcome::Verified(_)
+    ));
+    // Same idempotence key, different task id: refused, no second task.
+    let other_task = Job {
+        spec: SMALL,
+        ids: ids(4, 3),
+    };
+    let (o, _, sum) = run_job(&w, &other_task, &roster, &policy(&SMALL));
+    assert_eq!(failed(&o), "DUPLICATE_ID");
+    assert_eq!(sum.completed, 0);
+    // Same key, same task, different job body: also refused.
+    let other_body = Job {
+        spec: TaskSpec::MatmulU32 {
+            m: 9,
+            k: 13,
+            n: 5,
+            seed: 43,
+        },
+        ids: ids(3, 3),
+    };
+    assert_eq!(
+        failed(&run_job(&w, &other_body, &roster, &policy(&other_body.spec)).0),
+        "DUPLICATE_ID"
+    );
+    // Same request again: the stored receipt is replayed, nothing recomputed.
+    let (o, _, sum) = run_job(&w, &first, &roster, &policy(&SMALL));
+    assert!(matches!(o, Outcome::Verified(_)), "{o:?}");
+    assert_eq!((sum.replayed, sum.completed), (1, 0));
+}
+
+#[test]
+fn out_of_budget_is_refused_before_allocation() {
+    let lim = Limits {
+        max_memory_bytes: 1 << 20,
+        max_work_units: 1 << 20,
+        ..Limits::default()
+    };
+    let w = worker("budget", lim);
+    let roster = [key(1).verifying_key()];
+    let big_mem = TaskSpec::MatmulU32 {
+        m: 1024,
+        k: 1024,
+        n: 1,
+        seed: 1,
+    };
+    let o = run_job(
+        &w,
+        &Job {
+            spec: big_mem,
+            ids: ids(5, 5),
+        },
+        &roster,
+        &policy(&SMALL),
+    )
+    .0;
+    assert!(failed(&o).starts_with("OVER_BUDGET:MEMORY"), "{o:?}");
+    let big_work = TaskSpec::DigestChain {
+        rounds: (1 << 20) + 1,
+        seed: [1; 32],
+    };
+    let o = run_job(
+        &w,
+        &Job {
+            spec: big_work,
+            ids: ids(6, 6),
+        },
+        &roster,
+        &policy(&SMALL),
+    )
+    .0;
+    assert!(failed(&o).starts_with("OVER_BUDGET:WORK"), "{o:?}");
+    let empty = TaskSpec::MatmulU32 {
+        m: 0,
+        k: 4,
+        n: 4,
+        seed: 1,
+    };
+    let o = run_job(
+        &w,
+        &Job {
+            spec: empty,
+            ids: ids(7, 7),
+        },
+        &roster,
+        &policy(&SMALL),
+    )
+    .0;
+    assert_eq!(failed(&o), "OVER_BUDGET:EMPTY");
+}
+
+/// Send raw frames to a real worker, read `replies` answers, then close.
+fn raw_exchange(w: &Worker, frames: &[Vec<u8>], replies: usize) -> (Vec<wire::Msg>, Summary) {
+    let (mut c, s) = UnixStream::pair().unwrap();
+    std::thread::scope(|sc| {
+        let h = sc.spawn(|| {
+            let s2 = s.try_clone().unwrap();
+            w.serve(s2, s).unwrap()
+        });
+        for f in frames {
+            wire::write_frame(&mut c, f).unwrap();
+        }
+        let mut got = Vec::new();
+        while got.len() < replies {
+            let f = wire::read_frame(&mut c)
+                .unwrap()
+                .expect("worker closed early");
+            got.push(wire::decode(&f).unwrap());
+        }
+        c.shutdown(std::net::Shutdown::Write).unwrap();
+        while let Ok(Some(f)) = wire::read_frame(&mut c) {
+            got.push(wire::decode(&f).unwrap());
+        }
+        (got, h.join().unwrap())
+    })
+}
+
+#[test]
+fn denied_task_wrong_side_and_wrong_effect_create_no_task() {
+    let w = worker("denied", Limits::default());
+    let i = ids(8, 8);
+    let unknown_kind = wire::build(&i, wire::T_REQUEST, 0, &[9, 1, 2, 3]);
+    let wrong_side = wire::build(&ids(9, 9), wire::T_COMPLETED, 0, &[0; 32]);
+    let mut h = wire::decode(&wire::build(
+        &ids(10, 10),
+        wire::T_REQUEST,
+        0,
+        &SMALL.encode(),
+    ))
+    .unwrap()
+    .header;
+    h.effect_class = 2;
+    let payload = SMALL.encode();
+    let mut effect = vec![0u8; pst::HEADER_LEN + payload.len()];
+    pst::encode(&h, &payload, &mut effect).unwrap();
+    let (got, sum) = raw_exchange(&w, &[unknown_kind, wrong_side, effect], 3);
+    let reasons: Vec<String> = got
+        .iter()
+        .map(|m| String::from_utf8_lossy(&m.payload).into_owned())
+        .collect();
+    assert!(
+        got.iter()
+            .all(|m| m.header.msg_type == wire::T_FAILED && m.header.ordinal == 0),
+        "{reasons:?}"
+    );
+    assert_eq!(
+        reasons,
+        [
+            "DENIED_TASK:UnknownKind(9)",
+            "REFUSED:PST_WRONG_SIDE",
+            "DENIED_EFFECT"
+        ]
+    );
+    assert_eq!((sum.denied, sum.completed), (3, 0));
+}
+
+#[test]
+fn corrupt_frame_is_dropped_and_the_next_request_still_runs() {
+    let w = worker("corrupt", Limits::default());
+    let mut bad = wire::build(&ids(11, 11), wire::T_REQUEST, 0, &SMALL.encode());
+    let last = bad.len() - 1;
+    bad[last] ^= 1; // payload no longer matches its digest
+    let good = wire::build(&ids(12, 12), wire::T_REQUEST, 0, &SMALL.encode());
+    let (got, sum) = raw_exchange(&w, &[bad, good], 6);
+    assert_eq!(sum.refused_frames, 1);
+    assert!(got.iter().all(|m| m.header.task_id == [12; 16]));
+    assert_eq!(got.last().unwrap().header.msg_type, wire::T_COMPLETED);
+}
+
+/// A writer whose peer has hung up.
+struct HungUp;
+
+impl std::io::Write for HungUp {
+    fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
+        Err(std::io::ErrorKind::BrokenPipe.into())
+    }
+    fn flush(&mut self) -> std::io::Result<()> {
+        Ok(())
+    }
+}
+
+#[test]
+fn peer_hanging_up_mid_reply_ends_the_session_cleanly() {
+    // The input stays open, so the hang-up is seen only by the failed write
+    // (the order the wrong-peer test can hit when the result is fast).
+    let w = worker("hungup", Limits::default());
+    let (mut c, s) = UnixStream::pair().unwrap();
+    let req = wire::build(&ids(14, 14), wire::T_REQUEST, 0, &SMALL.encode());
+    wire::write_frame(&mut c, &req).unwrap();
+    let sum = w.serve(s, HungUp).expect("a hang-up is not a worker error");
+    assert_eq!(sum.completed + sum.failed, 0);
+}
+
+#[test]
+fn stale_frames_for_another_task_are_ignored() {
+    let spec = SMALL;
+    let job = Job {
+        spec,
+        ids: ids(13, 13),
+    };
+    let k = key(1);
+    let (o, st) = scripted(&job, &[k.verifying_key()], &policy(&spec), |i| {
+        let (mut f, _, _) = honest_frames(i, &spec, &k);
+        let old = ids(99, 99);
+        let (stale, _, _) = honest_frames(&old, &spec, &k);
+        f.insert(0, stale.last().unwrap().clone()); // an old task's `completed`
+        f
+    });
+    assert!(matches!(o, Outcome::Verified(_)), "{o:?}");
+    assert_eq!(st.stale_ignored, 1);
+}
+
+#[test]
+fn out_of_order_and_missing_receipt_are_rejected() {
+    let k = key(1);
+    let roster = [k.verifying_key()];
+    let job = Job {
+        spec: SMALL,
+        ids: ids(14, 14),
+    };
+    let (o, _) = scripted(&job, &roster, &policy(&SMALL), |i| {
+        vec![wire::build(i, wire::T_RUNNING, 1, &[])]
+    });
+    assert_eq!(rejected(&o), "OUT_OF_ORDER:expected 0 got 1");
+    let (o, _) = scripted(&job, &roster, &policy(&SMALL), |i| {
+        vec![
+            wire::build(i, wire::T_ACCEPTED, 0, &[]),
+            wire::build(i, wire::T_COMPLETED, 1, &task::oracle(&SMALL)),
+        ]
+    });
+    assert_eq!(rejected(&o), "COMPLETED_WITHOUT_RECEIPT");
+}
+
+#[test]
+fn tampered_receipts_and_wrong_outputs_are_rejected() {
+    let k = key(1);
+    let roster = [k.verifying_key()];
+    let job = Job {
+        spec: SMALL,
+        ids: ids(15, 15),
+    };
+    let p = policy(&SMALL);
+    // completed carries a different digest than the signed receipt.
+    let (o, _) = scripted(&job, &roster, &p, |i| {
+        let (_, receipt, mut out) = honest_frames(i, &SMALL, &k);
+        out[0] ^= 1;
+        frames_for(i, &receipt, &out)
+    });
+    assert_eq!(rejected(&o), "RECEIPT_MISMATCH:output_digest");
+    // A receipt byte changed after the reference digest was taken.
+    let (o, _) = scripted(&job, &roster, &p, |i| {
+        let (mut f, _, _) = honest_frames(i, &SMALL, &k);
+        let chunk = wire::decode(&f[2]).unwrap();
+        let mut body = chunk.payload.clone();
+        body[10] ^= 1;
+        f[2] = wire::build(i, wire::T_TEXT_CHUNK, 2, &body);
+        f
+    });
+    assert_eq!(rejected(&o), "RECEIPT_REFERENCE_MISMATCH");
+    // A field edited under an honest reference digest: the signature fails.
+    let (o, _) = scripted(&job, &roster, &p, |i| {
+        let (_, receipt, out) = honest_frames(i, &SMALL, &k);
+        let edited = String::from_utf8(receipt)
+            .unwrap()
+            .replace("\"compute_ns\":2", "\"compute_ns\":3");
+        frames_for(i, edited.as_bytes(), &out)
+    });
+    assert_eq!(rejected(&o), "BAD_SIGNATURE");
+    // A receipt honestly signed for another job body.
+    let (o, _) = scripted(&job, &roster, &p, |i| {
+        let other = TaskSpec::MatmulU32 {
+            m: 9,
+            k: 13,
+            n: 5,
+            seed: 1,
+        };
+        let (f, _, _) = honest_frames(i, &other, &k);
+        f
+    });
+    assert_eq!(rejected(&o), "RECEIPT_MISMATCH:input_digest");
+    // A worker that signs a wrong answer honestly: only the oracle catches it.
+    let wrong = Policy {
+        oracle: Some([0x55; 32]),
+        ..p
+    };
+    let (o, _) = scripted(&job, &roster, &wrong, |i| honest_frames(i, &SMALL, &k).0);
+    assert_eq!(rejected(&o), "ORACLE_MISMATCH");
+}
+
+#[test]
+fn coordinator_deadline_cancels_the_running_job() {
+    let w = worker("cancel", Limits::default());
+    let long = TaskSpec::DigestChain {
+        rounds: u32::MAX,
+        seed: [5; 32],
+    };
+    let p = Policy {
+        deadline: Duration::from_millis(200),
+        cancel_grace: Duration::from_secs(10),
+        oracle: None,
+    };
+    let (o, _, sum) = run_job(
+        &w,
+        &Job {
+            spec: long,
+            ids: ids(16, 16),
+        },
+        &[key(1).verifying_key()],
+        &p,
+    );
+    assert!(matches!(o, Outcome::Cancelled), "{o:?}");
+    assert_eq!(sum.cancelled, 1);
+}
+
+#[test]
+fn worker_wall_limit_reports_timeout() {
+    let lim = Limits {
+        max_wall: Duration::from_millis(100),
+        ..Limits::default()
+    };
+    let w = worker("timeout", lim);
+    let long = TaskSpec::DigestChain {
+        rounds: u32::MAX,
+        seed: [6; 32],
+    };
+    let p = Policy {
+        deadline: Duration::from_secs(30),
+        cancel_grace: Duration::from_secs(5),
+        oracle: None,
+    };
+    let (o, _, _) = run_job(
+        &w,
+        &Job {
+            spec: long,
+            ids: ids(17, 17),
+        },
+        &[key(1).verifying_key()],
+        &p,
+    );
+    assert_eq!(failed(&o), "TIMEOUT");
+}
+
+#[test]
+fn disconnect_and_silence_are_uncertain_never_failed() {
+    let roster = [key(1).verifying_key()];
+    let job = Job {
+        spec: SMALL,
+        ids: ids(18, 18),
+    };
+    // The worker accepts, then the link drops.
+    let (c, mut s) = UnixStream::pair().unwrap();
+    let h = std::thread::spawn(move || {
+        let req = wire::read_frame(&mut s).unwrap().unwrap();
+        let i = Ids::of(&wire::decode(&req).unwrap().header);
+        wire::write_frame(&mut s, &wire::build(&i, wire::T_ACCEPTED, 0, &[])).unwrap();
+    });
+    let r = c.try_clone().unwrap();
+    let mut wr = c;
+    let (o, _) = dispatch(r, &mut wr, &job, &roster, &policy(&SMALL)).unwrap();
+    h.join().unwrap();
+    assert!(
+        matches!(&o, Outcome::Uncertain(s) if s.starts_with("DISCONNECTED")),
+        "{o:?}"
+    );
+    // A worker that never answers, even to the cancel.
+    let p = Policy {
+        deadline: Duration::from_millis(100),
+        cancel_grace: Duration::from_millis(100),
+        oracle: None,
+    };
+    let (o, _) = scripted(&job, &roster, &p, |_| Vec::new());
+    assert!(
+        matches!(&o, Outcome::Uncertain(s) if s.starts_with("DEADLINE")),
+        "{o:?}"
+    );
+}
+
+#[test]
+fn a_second_worker_cannot_open_the_same_state_folder() {
+    let d = tmpdir("lock");
+    let _first = Store::open(&d).unwrap();
+    let second = Store::open(&d).err().expect("second open must be refused");
+    assert_eq!(second.kind(), std::io::ErrorKind::WouldBlock);
+}
+
+#[test]
+fn frames_above_1024_bytes_are_refused_before_reading() {
+    let mut src: &[u8] = &[0x04, 0x01, 0, 0];
+    let e = wire::read_frame(&mut src).unwrap_err();
+    assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
+    let (tx, rx) = std::sync::mpsc::channel();
+    wire::pump(&[0x00, 0x03, 1, 2, 3][..], tx, |i| i);
+    assert!(matches!(
+        rx.recv().unwrap(),
+        Inbound::Refused(pst::Refusal::BadLength)
+    ));
+}