diff --git a/.crumb b/.crumb index 1dbf165..e92e10c 100644 --- a/.crumb +++ b/.crumb @@ -13,27 +13,27 @@ "generated": { "children": [ { - "digest": "568edf1ba4cc3e991aefc7d761a9e782c79fa20d9a5fb49d9f1da59661e1a668", - "last_commit": "8a9c8e2", + "digest": "694274091a86847f3e2a283507f126b9785db773c366109d2defdf179637f3b7", + "last_commit": "724be77", "name": "crates", "purpose": "Directory crates. Purpose not yet described by a human." }, { - "digest": "7dcc2b4dd4387e1c881350a18e174c57f8f8af8e4d6a2c609045008f5536b5b8", - "last_commit": "a50a2fa", + "digest": "a648f528cb2717a8a4c48ab49ff96d8c815d708bf958c11d205dc544dda5254f", + "last_commit": "724be77", "name": "specs", "purpose": "Directory specs. Purpose not yet described by a human." } ], - "children_root": "sha256:772219c4d552f80fe973032e5e9e4e006a2c1ef26f5db0228c80f53c2a49987e", - "compiled_at": "2026-10-16T09:02:49Z", + "children_root": "sha256:ab7331fcefd7d12eb70ecfdd5027dab680c263a6443357c7149b8e1c7ac98e8b", + "compiled_at": "2026-10-18T15:29:41Z", "compiler": "crumb-compile/1", - "digest": "sha256:ea0344741dca8587a2f35956bc1a2acd9983087a6456acfd87a55e785d1b30b8", + "digest": "sha256:bd53d07a10322b7c3cd7617d16622fe10ff1c0aad090784dbb0b2d51223c7ad6", "evidence_files": 1, "evidence_root": "sha256:87c36bf8ed7be61c064552ebf141834707770b75d070ea49328a3e06d510afba", - "files": 473, - "generated_at_commit": "3f1436c2dc91bba047089739b41463c6c1d8de9e", - "source_tree": "sha256:1cd574c189b35493c20f2d6a65f0874a9454d83894df1b0146fbb4eaf23d13cb" + "files": 546, + "generated_at_commit": "724be772636bbefac37ee89559ed99d42173bd94", + "source_tree": "sha256:c72305a0f8390c2ad6b8f91413262833f0aec889eba37b61ae8c316a5ee0c3fa" }, "owner_lane": "", "seed": { diff --git a/CHANGELOG.md b/CHANGELOG.md index 4730a93..a16052c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,42 @@ VERSIONING.md. ### Specifications +- `specs/pi-spark-task`: PST1 Draft v0.3 (C6, aien-protocols-mv#33): tool-call + tasks (section 11). Two Pi types, `tool_call_request` (15, a 36-byte head: + INTERPLANE request digest and length) and `tool_call_chunk` (16, the + INTERPLANE canonical request bytes in 800-byte pieces, nothing added); the + receiver joins the chunks, checks the digest and refuses on mismatch; an + ordinary task never carries a tool-call payload; approval stays with the + Spark approval desk and AIENOS authority. Five new codes. One canonical + request from interplane-core at interplane-mv `83df0f0` + (`tools/interplane-request`), 7 new single-message vectors and 9 new + recorded sessions; 32 checks, 32 mutants killed. `crates/aien-pi-spark-task` + reads the head and joins and checks the chunks (`ToolCall`, `TaskBody`); its + new test reads the same tool vectors byte for byte. +- `specs/pi-spark-task`: PST1 Draft v0.2 (C5, aien-protocols-mv#32): session + rules (section 10): who may send which type, the allowed sequence for one + task, the check order inside a session, and a recording container for test + vectors; nine new codes. `pst_verify` gains `--session` and + `--session-fuzz`; 19 recorded sessions in `vectors/sessions/`; 26 checks, + 26 mutants killed. +- `crates/aien-pi-spark-task` (C4, aien-protocols-mv#31): Rust reader and + writer for the PST1 fixed header, no `unsafe`, no JSON, fixed bounds. Its + test walks `specs/pi-spark-task/vectors/expected.txt` and requires the same + verdict line as the C checker and byte-identical re-encoding. +- `specs/pi-spark-task`: PST1 Draft v0.1 (C3, aien-protocols-mv#30): a 4-byte + `PST1` magic now opens the header (`reserved1` shrank to 1 byte and + `reserved2` was removed, so the header stays 224 bytes; fields after `type` + moved by 4), a fixed check order (section 4.1), and two codes + (`PST_BAD_MAGIC`, `PST_NO_OBJECTIVE`). Version 0 is refused as + `PST_DOWNGRADE`. Adds the C reference checker and encoder + `tools/pst_verify.c` (C99, libc only, no heap), 23 header vectors with + `vectors/expected.txt`, `tools/check-vectors.sh` and + `tools/mutate-verifier.sh` (15 checks, 15 mutants killed). +- `specs/pi-spark-task`: PST1 Draft v0, the Pi-Spark task message for + ALLEN Pi/Spark lane C1 (aien-protocols-mv#28): inventory of reused formats, + layering over M6-A and M6-B, 224-byte big-endian header, 14 message types, + size and refusal rules, the limits of exactly once, and a no-permission + clause. No code and no vectors yet (C3). - `specs/osh-platform`: OSH Platform ABI v1 DRAFT (not frozen) for the Omega-native shell of aien-architecture#158: step and status protocol, request record, platform operations, authority and interrupted-effect diff --git a/CONSUMERS.md b/CONSUMERS.md index 841d91f..a387828 100644 --- a/CONSUMERS.md +++ b/CONSUMERS.md @@ -10,6 +10,7 @@ carries a newer tag with migration notes, all consumers target `v0.1.0`. | `spark-inquisitor` | protocol-types, evaluation-protocol, probe | v0.1.0 | | `spark-rsi` | protocol-types, evaluation-protocol, probe | v0.1.0 | | `aien-sovereign-core` (`spark-harvester`, `spark-mail-rs`) | protocol-types, provenance, probe | v0.1.0 | +| `aien-sovereign-core` (Spark side of the Pi link, lane D, aien-sovereign-core-mv#585; planned, not yet a dependency) | pi-spark-task (`crates/aien-pi-spark-task`, PST1 Draft v0.1) | v0.1.0 | Consumption is by path dependency today. A consumer moves to a newer tag by recording the new version in this table in the same change that adopts it. diff --git a/Cargo.lock b/Cargo.lock index 1da2c0f..8dda224 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -87,6 +87,13 @@ dependencies = [ "uuid", ] +[[package]] +name = "aien-pi-spark-task" +version = "0.1.0" +dependencies = [ + "sha2 0.10.9", +] + [[package]] name = "aien-probe" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 0ae7089..0a47c3f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,6 +10,7 @@ members = [ "crates/aien-evaluation-protocol", "crates/aien-provenance", "crates/aien-probe", + "crates/aien-pi-spark-task", ] [workspace.package] diff --git a/README.md b/README.md index f4d0b8c..bc7c583 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,8 @@ Research-grade and pre-alpha. The specifications and reference Rust crates (AGPL ```text specs/ Normative specifications (Community Specification License 1.0): agent-state, inference, evaluation, crumb-visible, execution-transcript, - evidence-receipt (partial), verified-crumb, osh-platform (draft) + evidence-receipt (partial), verified-crumb, osh-platform (draft), + pi-spark-task (PST1 draft) crates/ Reference Rust crates (AGPL-3.0-or-later), legacy: aien-protocol-types, aien-agent-state-abi, aien-inference-protocol, aien-inference-client, aien-action-protocol, aien-event-protocol, diff --git a/crates/.crumb b/crates/.crumb index 2dcd18d..5c5ef5c 100644 --- a/crates/.crumb +++ b/crates/.crumb @@ -80,9 +80,15 @@ "name": "aien-inference-protocol", "purpose": "Directory crates/aien-inference-protocol. Purpose not yet described by a human." }, + { + "digest": "46bedbbd7dab0ef7dd852db1ac105306e23ef617430d78d9fc5c938b60a3e2e4", + "last_commit": "724be77", + "name": "aien-pi-spark-task", + "purpose": "PST1 Pi-Spark task message: Rust header reader and writer that must match the C checker byte for" + }, { "digest": "8882b1057235e20f8b0af49350d3e4a1cdc1a4c6259170fcbc66cc905cc1a7a8", - "last_commit": "f250aa2", + "last_commit": "8a9c8e2", "name": "aien-probe", "purpose": "Directory crates/aien-probe. Purpose not yet described by a human." }, @@ -99,15 +105,15 @@ "purpose": "Directory crates/aien-provenance. Purpose not yet described by a human." } ], - "children_root": "sha256:b552586103a38f8880dcc92d669e9391a5e924eec6578a237b5d842bfe046f05", - "compiled_at": "2026-10-15T11:35:44Z", + "children_root": "sha256:a5c86cba24e3f9ea17785f5199c1b01caf5324b74681b0ff186785f52b825cc9", + "compiled_at": "2026-10-18T15:29:41Z", "compiler": "crumb-compile/1", - "digest": "sha256:568edf1ba4cc3e991aefc7d761a9e782c79fa20d9a5fb49d9f1da59661e1a668", + "digest": "sha256:694274091a86847f3e2a283507f126b9785db773c366109d2defdf179637f3b7", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 29, - "generated_at_commit": "f250aa2e0f8c3da108da0c2b2d9f80ddf67ae7a1", - "source_tree": "sha256:325f848278a692d37df4599578dbe32f7d3a87d50398c9aac9ac83d84a0344ca" + "files": 33, + "generated_at_commit": "724be772636bbefac37ee89559ed99d42173bd94", + "source_tree": "sha256:1e06e92835e772391b8f30b357f1849123f21f0d6ff94459f5668c28f595f247" }, "owner_lane": "", "seed": { diff --git a/crates/aien-pi-spark-task/.crumb b/crates/aien-pi-spark-task/.crumb new file mode 100644 index 0000000..d91d303 --- /dev/null +++ b/crates/aien-pi-spark-task/.crumb @@ -0,0 +1,33 @@ +{ + "extensions": { + "generated": { + "children": [ + { + "digest": "4413056938a48b50f591186249ba26babb95d5d534a624a51473436033b7d51c", + "last_commit": "724be77", + "name": "src", + "purpose": "PST1 header decode, encode and verdict line" + }, + { + "digest": "84049d671dbcdc0fb16c2910911db929e9412dd4cdc9ffbbeefc5ce99bc6174c", + "last_commit": "724be77", + "name": "tests", + "purpose": "Parity test: walks specs/pi-spark-task/vectors/expected.txt against the C checker's verdicts" + } + ], + "children_root": "sha256:299e5a6722e879ff80b3550cadda3ea69c8e444dc1db72d1a77aabb6e936fe00", + "compiled_at": "2026-10-18T15:29:41Z", + "compiler": "crumb-compile/1", + "digest": "sha256:46bedbbd7dab0ef7dd852db1ac105306e23ef617430d78d9fc5c938b60a3e2e4", + "evidence_files": 0, + "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "files": 4, + "generated_at_commit": "724be772636bbefac37ee89559ed99d42173bd94", + "source_tree": "sha256:c75f89910352b0755343e5629e7c2e0952a3a05d9400fd98ed809d99d5a9ba73" + } + }, + "layer": "crates/aien-pi-spark-task", + "name": "crates/aien-pi-spark-task", + "purpose": "PST1 Pi-Spark task message: Rust header reader and writer that must match the C checker byte for byte", + "schema_version": "1.0.0" +} diff --git a/crates/aien-pi-spark-task/Cargo.toml b/crates/aien-pi-spark-task/Cargo.toml new file mode 100644 index 0000000..9be3176 --- /dev/null +++ b/crates/aien-pi-spark-task/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "aien-pi-spark-task" +version = "0.1.0" +edition = "2021" +license = "AGPL-3.0-or-later" +description = "PST1 Pi-Spark task message: fixed-size header reader and writer (specs/pi-spark-task)" + +[dependencies] +sha2 = { workspace = true } diff --git a/crates/aien-pi-spark-task/src/.crumb b/crates/aien-pi-spark-task/src/.crumb new file mode 100644 index 0000000..7858618 --- /dev/null +++ b/crates/aien-pi-spark-task/src/.crumb @@ -0,0 +1,20 @@ +{ + "extensions": { + "generated": { + "children": [], + "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "compiled_at": "2026-10-18T15:29:41Z", + "compiler": "crumb-compile/1", + "digest": "sha256:4413056938a48b50f591186249ba26babb95d5d534a624a51473436033b7d51c", + "evidence_files": 0, + "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "files": 1, + "generated_at_commit": "724be772636bbefac37ee89559ed99d42173bd94", + "source_tree": "sha256:edbd438f0042ebfef78370253e69a90d2e5806ac22e42ddcae977ec5372592c8" + } + }, + "layer": "crates/aien-pi-spark-task/src", + "name": "crates/aien-pi-spark-task/src", + "purpose": "PST1 header decode, encode and verdict line", + "schema_version": "1.0.0" +} diff --git a/crates/aien-pi-spark-task/src/lib.rs b/crates/aien-pi-spark-task/src/lib.rs new file mode 100644 index 0000000..f2547c1 --- /dev/null +++ b/crates/aien-pi-spark-task/src/lib.rs @@ -0,0 +1,570 @@ +//! PST1, the Pi-Spark task message: reader and writer for the fixed header. +//! +//! Spec: `specs/pi-spark-task/SPEC.md` (Draft v0.3, contract 0.1.0, wire +//! version 1). The C reference checker is `specs/pi-spark-task/tools/pst_verify.c`; +//! this crate must give the same verdict on the same bytes (the test in +//! `tests/vectors.rs` walks the shared vectors). +//! +//! Bounds are fixed: a message is 224 header bytes plus at most 800 payload +//! bytes. Decoding borrows the payload from the input and allocates nothing. +//! There is no JSON anywhere in the decode path. +//! +//! First cut (aien-protocols-mv#31): the header only. C6 (aien-protocols-mv#33) +//! adds the tool-call body (SPEC.md section 11): the 36-byte head of a +//! `tool_call_request` is checked in [`decode`], and [`TaskBody`] joins the +//! `tool_call_chunk` payloads into the INTERPLANE canonical request and checks +//! its digest. The side of the sender and the other session rules (section 10) +//! are not read here. +#![forbid(unsafe_code)] + +use sha2::{Digest, Sha256}; + +/// Bytes in the fixed header. +pub const HEADER_LEN: usize = 224; +/// Largest payload. +pub const MAX_PAYLOAD: usize = 800; +/// Largest message (header plus payload). +pub const MAX_MESSAGE: usize = HEADER_LEN + MAX_PAYLOAD; +/// The four bytes that open every message. +pub const MAGIC: [u8; 4] = *b"PST1"; +/// The only wire version. +pub const VERSION: u8 = 1; +/// Highest message type (section 5). +pub const MAX_TYPE: u8 = 16; +/// The `request` type (an ordinary, non-tool task). +pub const TYPE_REQUEST: u8 = 1; +/// The `failed` type. +pub const TYPE_FAILED: u8 = 8; +/// The `cancelled` type. +pub const TYPE_CANCELLED: u8 = 9; +/// The `tool_call_request` type: opens a tool-call task (section 11). +pub const TYPE_TOOL_CALL_REQUEST: u8 = 15; +/// The `tool_call_chunk` type: the next piece of the canonical request. +pub const TYPE_TOOL_CALL_CHUNK: u8 = 16; +/// Bytes in a tool-call head: the INTERPLANE digest and the canonical length. +pub const TOOL_HEAD_LEN: usize = 36; +/// Longest INTERPLANE canonical request one tool-call task can carry. +pub const MAX_TOOL_REQUEST: u32 = 102_400; + +const O_MAGIC: usize = 0; +const O_VERSION: usize = 4; +const O_TYPE: usize = 5; +const O_RES0: usize = 6; +const O_CAUSE: usize = 8; +const O_ORIGIN: usize = 40; +const O_OBJECTIVE: usize = 72; +const O_SUBJECT: usize = 104; +const O_PARENT: usize = 136; +const O_TASK: usize = 152; +const O_IDEM: usize = 168; +const O_ORDINAL: usize = 184; +const O_EFFECT: usize = 188; +const O_RES1: usize = 189; +const O_PLEN: usize = 190; +const O_DIGEST: usize = 192; + +/// A refusal code from SPEC.md section 7. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Refusal { + BadMagic, + BadVersion, + Downgrade, + BadType, + WrongSide, + BadLength, + TrailingBytes, + ReservedNonzero, + NoCause, + NoTask, + NoObjective, + DigestMismatch, + BadEffectClass, + SubjectMismatch, + BadOrder, + BadToolHead, + ToolChunkSize, + ToolDigestMismatch, + ToolIncomplete, + NotToolTask, +} + +impl Refusal { + /// The code name exactly as SPEC.md section 7 and the C checker print it. + pub fn code(self) -> &'static str { + match self { + Refusal::BadMagic => "PST_BAD_MAGIC", + Refusal::BadVersion => "PST_BAD_VERSION", + Refusal::Downgrade => "PST_DOWNGRADE", + Refusal::BadType => "PST_BAD_TYPE", + Refusal::WrongSide => "PST_WRONG_SIDE", + Refusal::BadLength => "PST_BAD_LENGTH", + Refusal::TrailingBytes => "PST_TRAILING_BYTES", + Refusal::ReservedNonzero => "PST_RESERVED_NONZERO", + Refusal::NoCause => "PST_NO_CAUSE", + Refusal::NoTask => "PST_NO_TASK", + Refusal::NoObjective => "PST_NO_OBJECTIVE", + Refusal::DigestMismatch => "PST_DIGEST_MISMATCH", + Refusal::BadEffectClass => "PST_BAD_EFFECT_CLASS", + Refusal::SubjectMismatch => "PST_SUBJECT_MISMATCH", + Refusal::BadOrder => "PST_BAD_ORDER", + Refusal::BadToolHead => "PST_BAD_TOOL_HEAD", + Refusal::ToolChunkSize => "PST_TOOL_CHUNK_SIZE", + Refusal::ToolDigestMismatch => "PST_TOOL_DIGEST_MISMATCH", + Refusal::ToolIncomplete => "PST_TOOL_INCOMPLETE", + Refusal::NotToolTask => "PST_NOT_TOOL_TASK", + } + } +} + +/// The decoded fixed header (SPEC.md section 4). Reserved bytes and the +/// magic are not stored: they have exactly one allowed value. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Header { + pub version: u8, + pub msg_type: u8, + pub cause_id: [u8; 32], + pub origin_run_id: [u8; 32], + pub objective_id: [u8; 32], + pub subject_id: [u8; 32], + pub parent_task_id: [u8; 16], + pub task_id: [u8; 16], + pub idempotence_key: [u8; 16], + pub ordinal: u32, + pub effect_class: u8, + pub payload_len: u16, + pub payload_digest: [u8; 32], +} + +/// One accepted message: the header and the payload it borrows. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Message<'a> { + pub header: Header, + pub payload: &'a [u8], +} + +/// Why `encode` could not write a message. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum EncodeError { + /// The payload is longer than 800 bytes. + PayloadTooLong, + /// `payload_len` in the header differs from the payload given. + LengthMismatch, + /// The output buffer is too small. + BufferTooSmall, +} + +fn arr(b: &[u8], at: usize) -> [u8; N] { + let mut a = [0u8; N]; + a.copy_from_slice(&b[at..at + N]); + a +} + +fn all_zero(b: &[u8]) -> bool { + b.iter().all(|&x| x == 0) +} + +/// Decode and check one message in the order of SPEC.md section 4.1, the +/// same order as the C checker, so the same bytes give the same code. +pub fn decode(b: &[u8]) -> Result, Refusal> { + // 1. length bounds + if b.len() < HEADER_LEN || b.len() > MAX_MESSAGE { + return Err(Refusal::BadLength); + } + // 2. magic + if b[O_MAGIC..O_MAGIC + 4] != MAGIC { + return Err(Refusal::BadMagic); + } + // 3. version + if b[O_VERSION] < VERSION { + return Err(Refusal::Downgrade); + } + if b[O_VERSION] > VERSION { + return Err(Refusal::BadVersion); + } + // 4. type + if b[O_TYPE] == 0 || b[O_TYPE] > MAX_TYPE { + return Err(Refusal::BadType); + } + // 5. reserved + if !all_zero(&b[O_RES0..O_RES0 + 2]) || b[O_RES1] != 0 { + return Err(Refusal::ReservedNonzero); + } + // 6, 7. payload length against the bytes present + let payload_len = u16::from_be_bytes(arr(b, O_PLEN)); + let body = &b[HEADER_LEN..]; + if body.len() < usize::from(payload_len) { + return Err(Refusal::BadLength); + } + if body.len() > usize::from(payload_len) { + return Err(Refusal::TrailingBytes); + } + // 8..11. field rules + if b[O_EFFECT] > 2 { + return Err(Refusal::BadEffectClass); + } + if all_zero(&b[O_CAUSE..O_CAUSE + 32]) { + return Err(Refusal::NoCause); + } + if all_zero(&b[O_TASK..O_TASK + 16]) || all_zero(&b[O_IDEM..O_IDEM + 16]) { + return Err(Refusal::NoTask); + } + let opens_task = b[O_TYPE] == TYPE_REQUEST || b[O_TYPE] == TYPE_TOOL_CALL_REQUEST; + if opens_task && all_zero(&b[O_OBJECTIVE..O_OBJECTIVE + 32]) { + return Err(Refusal::NoObjective); + } + // 12. payload digest + let digest: [u8; 32] = Sha256::digest(body).into(); + if digest[..] != b[O_DIGEST..O_DIGEST + 32] { + return Err(Refusal::DigestMismatch); + } + // 13. tool-call head + if b[O_TYPE] == TYPE_TOOL_CALL_REQUEST { + ToolCallHead::parse(body)?; + } + Ok(Message { + header: Header { + version: b[O_VERSION], + msg_type: b[O_TYPE], + cause_id: arr(b, O_CAUSE), + origin_run_id: arr(b, O_ORIGIN), + objective_id: arr(b, O_OBJECTIVE), + subject_id: arr(b, O_SUBJECT), + parent_task_id: arr(b, O_PARENT), + task_id: arr(b, O_TASK), + idempotence_key: arr(b, O_IDEM), + ordinal: u32::from_be_bytes(arr(b, O_ORDINAL)), + effect_class: b[O_EFFECT], + payload_len, + payload_digest: arr(b, O_DIGEST), + }, + payload: body, + }) +} + +/// Write one message into `out` and return the byte count. Fields are written +/// exactly as given; the digest is not recomputed (use [`payload_digest`]). +pub fn encode(h: &Header, payload: &[u8], out: &mut [u8]) -> Result { + if payload.len() > MAX_PAYLOAD { + return Err(EncodeError::PayloadTooLong); + } + if usize::from(h.payload_len) != payload.len() { + return Err(EncodeError::LengthMismatch); + } + let n = HEADER_LEN + payload.len(); + if out.len() < n { + return Err(EncodeError::BufferTooSmall); + } + let o = &mut out[..n]; + o[..HEADER_LEN].fill(0); + o[O_MAGIC..O_MAGIC + 4].copy_from_slice(&MAGIC); + o[O_VERSION] = h.version; + o[O_TYPE] = h.msg_type; + o[O_CAUSE..O_CAUSE + 32].copy_from_slice(&h.cause_id); + o[O_ORIGIN..O_ORIGIN + 32].copy_from_slice(&h.origin_run_id); + o[O_OBJECTIVE..O_OBJECTIVE + 32].copy_from_slice(&h.objective_id); + o[O_SUBJECT..O_SUBJECT + 32].copy_from_slice(&h.subject_id); + o[O_PARENT..O_PARENT + 16].copy_from_slice(&h.parent_task_id); + o[O_TASK..O_TASK + 16].copy_from_slice(&h.task_id); + o[O_IDEM..O_IDEM + 16].copy_from_slice(&h.idempotence_key); + o[O_ORDINAL..O_ORDINAL + 4].copy_from_slice(&h.ordinal.to_be_bytes()); + o[O_EFFECT] = h.effect_class; + o[O_PLEN..O_PLEN + 2].copy_from_slice(&h.payload_len.to_be_bytes()); + o[O_DIGEST..O_DIGEST + 32].copy_from_slice(&h.payload_digest); + o[HEADER_LEN..].copy_from_slice(payload); + Ok(n) +} + +/// The payload of a `tool_call_request` (SPEC.md section 11.2): the digest of +/// the INTERPLANE canonical request and its length in bytes, and nothing else. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ToolCallHead { + /// SHA-256 of the canonical bytes; INTERPLANE writes it as `sha256:` + hex. + pub interplane_digest: [u8; 32], + /// Length of the canonical bytes, 1 to [`MAX_TOOL_REQUEST`]. + pub canonical_len: u32, +} + +impl ToolCallHead { + /// Read a head. Exactly 36 bytes, length 1 to 102400; anything else is + /// `PST_BAD_TOOL_HEAD`. + pub fn parse(payload: &[u8]) -> Result { + if payload.len() != TOOL_HEAD_LEN { + return Err(Refusal::BadToolHead); + } + let canonical_len = u32::from_be_bytes(arr(payload, 32)); + if canonical_len == 0 || canonical_len > MAX_TOOL_REQUEST { + return Err(Refusal::BadToolHead); + } + Ok(ToolCallHead { + interplane_digest: arr(payload, 0), + canonical_len, + }) + } + + /// The digest as INTERPLANE prints it: `sha256:` and 64 lower-case hex digits. + pub fn interplane_digest_string(&self) -> String { + let mut s = String::with_capacity(71); + s.push_str("sha256:"); + hex(&mut s, &self.interplane_digest); + s + } +} + +/// A tool call being received: the head and the canonical bytes so far. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ToolCall { + head: ToolCallHead, + bytes: Vec, + verified: bool, +} + +impl ToolCall { + /// Start collecting the bytes the head announces. + pub fn new(head: ToolCallHead) -> Self { + ToolCall { + head, + bytes: Vec::with_capacity(head.canonical_len as usize), + verified: false, + } + } + + /// The head this call was opened with. + pub fn head(&self) -> &ToolCallHead { + &self.head + } + + /// Add one `tool_call_chunk` payload (section 11.3). Every chunk is + /// exactly 800 bytes except the last, which is exactly what is left. + /// Returns `Ok(true)` when the last chunk is in and the joined bytes match + /// the head's digest. + pub fn push_chunk(&mut self, chunk: &[u8]) -> Result { + if self.verified { + return Err(Refusal::BadOrder); + } + let left = self.head.canonical_len as usize - self.bytes.len(); + if chunk.len() != left.min(MAX_PAYLOAD) { + return Err(Refusal::ToolChunkSize); + } + self.bytes.extend_from_slice(chunk); + if self.bytes.len() < self.head.canonical_len as usize { + return Ok(false); + } + if payload_digest(&self.bytes) != self.head.interplane_digest { + return Err(Refusal::ToolDigestMismatch); + } + self.verified = true; + Ok(true) + } + + /// The INTERPLANE canonical request, exactly as sent, once every chunk is + /// in and the digest matched. `None` before that. + pub fn canonical_bytes(&self) -> Option<&[u8]> { + self.verified.then_some(&self.bytes[..]) + } +} + +/// What a task carries, fixed by the message that opened it (section 11.1). +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum TaskBody { + /// Opened by `request`: an ordinary task. It never carries tool-call chunks. + Chat, + /// Opened by `tool_call_request`: carries one INTERPLANE canonical request. + ToolCall(ToolCall), +} + +impl TaskBody { + /// The body a task opened by `m` carries, or `None` if `m` opens no task. + pub fn open(m: &Message<'_>) -> Option> { + match m.header.msg_type { + TYPE_REQUEST => Some(Ok(TaskBody::Chat)), + TYPE_TOOL_CALL_REQUEST => { + Some(ToolCallHead::parse(m.payload).map(|h| TaskBody::ToolCall(ToolCall::new(h)))) + } + _ => None, + } + } + + /// A `tool_call_chunk` for this task. A chunk on an ordinary task is + /// `PST_NOT_TOOL_TASK`. + pub fn chunk(&mut self, payload: &[u8]) -> Result { + match self { + TaskBody::Chat => Err(Refusal::NotToolTask), + TaskBody::ToolCall(call) => call.push_chunk(payload), + } + } + + /// May the Spark send `msg_type` for this task yet? Until the whole + /// request is in and verified, only `failed` and `cancelled` are allowed + /// (`PST_TOOL_INCOMPLETE`). + pub fn check_spark(&self, msg_type: u8) -> Result<(), Refusal> { + match self { + TaskBody::ToolCall(call) + if call.canonical_bytes().is_none() + && msg_type != TYPE_FAILED + && msg_type != TYPE_CANCELLED => + { + Err(Refusal::ToolIncomplete) + } + _ => Ok(()), + } + } +} + +/// SHA-256 of a payload, for filling `Header::payload_digest`. +pub fn payload_digest(payload: &[u8]) -> [u8; 32] { + Sha256::digest(payload).into() +} + +fn hex(out: &mut String, bytes: &[u8]) { + const HX: &[u8; 16] = b"0123456789abcdef"; + for &x in bytes { + out.push(char::from(HX[usize::from(x >> 4)])); + out.push(char::from(HX[usize::from(x & 15)])); + } +} + +/// The verdict line in the exact format of `pst_verify FILE` and +/// `vectors/expected.txt`. +pub fn verdict_line(result: &Result, Refusal>) -> String { + let m = match result { + Err(r) => return format!("refuse {}", r.code()), + Ok(m) => &m.header, + }; + let mut s = String::with_capacity(512); + s.push_str(&format!( + "ok type={} version={} cause=", + m.msg_type, m.version + )); + hex(&mut s, &m.cause_id); + s.push_str(" origin="); + hex(&mut s, &m.origin_run_id); + s.push_str(" objective="); + hex(&mut s, &m.objective_id); + s.push_str(" subject="); + hex(&mut s, &m.subject_id); + s.push_str(" parent="); + hex(&mut s, &m.parent_task_id); + s.push_str(" task="); + hex(&mut s, &m.task_id); + s.push_str(" idem="); + hex(&mut s, &m.idempotence_key); + s.push_str(&format!( + " ordinal={} effect={} len={} digest=", + m.ordinal, m.effect_class, m.payload_len + )); + hex(&mut s, &m.payload_digest); + s +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sample() -> (Header, &'static [u8]) { + let payload: &'static [u8] = b"hello"; + let h = Header { + version: VERSION, + msg_type: TYPE_REQUEST, + cause_id: [1; 32], + origin_run_id: [2; 32], + objective_id: [3; 32], + subject_id: [4; 32], + parent_task_id: [0; 16], + task_id: [5; 16], + idempotence_key: [6; 16], + ordinal: 0, + effect_class: 1, + payload_len: 5, + payload_digest: payload_digest(payload), + }; + (h, payload) + } + + #[test] + fn encode_then_decode_round_trips() { + let (h, p) = sample(); + let mut out = [0u8; MAX_MESSAGE]; + let n = encode(&h, p, &mut out).unwrap(); + let m = decode(&out[..n]).unwrap(); + assert_eq!(m.header, h); + assert_eq!(m.payload, p); + } + + #[test] + fn encode_refuses_what_it_cannot_write() { + let (mut h, p) = sample(); + let mut small = [0u8; HEADER_LEN]; + assert_eq!(encode(&h, p, &mut small), Err(EncodeError::BufferTooSmall)); + h.payload_len = 4; + let mut out = [0u8; MAX_MESSAGE]; + assert_eq!(encode(&h, p, &mut out), Err(EncodeError::LengthMismatch)); + let long = [0u8; MAX_PAYLOAD + 1]; + assert_eq!( + encode(&h, &long, &mut [0u8; 2048]), + Err(EncodeError::PayloadTooLong) + ); + } + fn head_for(bytes: &[u8]) -> [u8; TOOL_HEAD_LEN] { + let mut h = [0u8; TOOL_HEAD_LEN]; + h[..32].copy_from_slice(&payload_digest(bytes)); + h[32..].copy_from_slice(&(bytes.len() as u32).to_be_bytes()); + h + } + + #[test] + fn tool_call_joins_chunks_and_checks_the_digest() { + let canonical: Vec = (0..1700u32).map(|i| b'a' + (i % 26) as u8).collect(); + let head = ToolCallHead::parse(&head_for(&canonical)).unwrap(); + let mut call = ToolCall::new(head); + assert_eq!(call.push_chunk(&canonical[..800]), Ok(false)); + assert_eq!(call.canonical_bytes(), None); + assert_eq!(call.push_chunk(&canonical[800..1600]), Ok(false)); + assert_eq!(call.push_chunk(&canonical[1600..]), Ok(true)); + assert_eq!(call.canonical_bytes(), Some(&canonical[..])); + assert_eq!(call.push_chunk(b"x"), Err(Refusal::BadOrder)); + + let mut altered = canonical.clone(); + altered[5] ^= 1; + let mut call = ToolCall::new(head); + call.push_chunk(&altered[..800]).unwrap(); + call.push_chunk(&altered[800..1600]).unwrap(); + assert_eq!( + call.push_chunk(&altered[1600..]), + Err(Refusal::ToolDigestMismatch) + ); + + let mut call = ToolCall::new(head); + assert_eq!( + call.push_chunk(&canonical[..799]), + Err(Refusal::ToolChunkSize) + ); + } + + #[test] + fn tool_head_is_exactly_digest_and_length() { + let h = head_for(b"{}"); + assert!(ToolCallHead::parse(&h).is_ok()); + assert_eq!(ToolCallHead::parse(&h[..35]), Err(Refusal::BadToolHead)); + let mut extra = h.to_vec(); + extra.push(0); + assert_eq!(ToolCallHead::parse(&extra), Err(Refusal::BadToolHead)); + let mut zero = h; + zero[32..].fill(0); + assert_eq!(ToolCallHead::parse(&zero), Err(Refusal::BadToolHead)); + let mut over = h; + over[32..].copy_from_slice(&(MAX_TOOL_REQUEST + 1).to_be_bytes()); + assert_eq!(ToolCallHead::parse(&over), Err(Refusal::BadToolHead)); + } + + #[test] + fn chat_tasks_carry_no_tool_chunks_and_spark_waits_for_the_whole_call() { + let mut chat = TaskBody::Chat; + assert_eq!(chat.chunk(b"{}"), Err(Refusal::NotToolTask)); + let head = ToolCallHead::parse(&head_for(b"{}")).unwrap(); + let mut tool = TaskBody::ToolCall(ToolCall::new(head)); + assert_eq!(tool.check_spark(2), Err(Refusal::ToolIncomplete)); + assert_eq!(tool.check_spark(TYPE_FAILED), Ok(())); + assert_eq!(tool.chunk(b"{}"), Ok(true)); + assert_eq!(tool.check_spark(2), Ok(())); + } +} diff --git a/crates/aien-pi-spark-task/tests/.crumb b/crates/aien-pi-spark-task/tests/.crumb new file mode 100644 index 0000000..e5db1ab --- /dev/null +++ b/crates/aien-pi-spark-task/tests/.crumb @@ -0,0 +1,20 @@ +{ + "extensions": { + "generated": { + "children": [], + "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "compiled_at": "2026-10-18T15:29:41Z", + "compiler": "crumb-compile/1", + "digest": "sha256:84049d671dbcdc0fb16c2910911db929e9412dd4cdc9ffbbeefc5ce99bc6174c", + "evidence_files": 0, + "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "files": 2, + "generated_at_commit": "724be772636bbefac37ee89559ed99d42173bd94", + "source_tree": "sha256:f22e88871eff84d31b26a5778bbb2722a6b5837f2e9411284c5ca261081b34a1" + } + }, + "layer": "crates/aien-pi-spark-task/tests", + "name": "crates/aien-pi-spark-task/tests", + "purpose": "Parity test: walks specs/pi-spark-task/vectors/expected.txt against the C checker's verdicts", + "schema_version": "1.0.0" +} diff --git a/crates/aien-pi-spark-task/tests/tool_call.rs b/crates/aien-pi-spark-task/tests/tool_call.rs new file mode 100644 index 0000000..6ed3ec6 --- /dev/null +++ b/crates/aien-pi-spark-task/tests/tool_call.rs @@ -0,0 +1,140 @@ +//! Tool-call tasks (SPEC.md section 11) against the shared vectors. +//! +//! Reads the same files the C reference checker reads, byte for byte: +//! `vectors/interplane-tool-request.json` (the INTERPLANE canonical request), +//! `vectors/ok-tool-call-request.pst`, and every recorded session in +//! `vectors/sessions/expected.txt` whose name contains `tool`. For each +//! session the Rust reader must print the same verdict line as +//! `pst_verify --session`. +//! +//! Scope: this reader checks the single-message rules ([`decode`]) and the +//! tool-call rules ([`TaskBody`]). The other session rules of section 10 +//! (side, subject, ordinals, context, the order table) are checked by the C +//! checker only; the tool vectors are built so that none of them decides the +//! verdict. + +use std::collections::HashMap; +use std::path::PathBuf; + +use aien_pi_spark_task::{ + decode, payload_digest, Refusal, TaskBody, ToolCallHead, TYPE_TOOL_CALL_CHUNK, +}; + +/// The digest interplane-core printed for the carried request at +/// aien-dev/interplane-mv 83df0f074b2c572473cd535c89f767df48933f4a. +const INTERPLANE_DIGEST: &str = + "sha256:78dbef7ee689b20ad9ae530fd7fa8417fb671778667b27f910484156776990d6"; + +fn vectors_dir() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../specs/pi-spark-task/vectors") +} + +fn read(name: &str) -> Vec { + std::fs::read(vectors_dir().join(name)).unwrap_or_else(|e| panic!("read {name}: {e}")) +} + +#[test] +fn the_head_names_the_carried_interplane_request() { + let canonical = read("interplane-tool-request.json"); + let bytes = read("ok-tool-call-request.pst"); + let msg = decode(&bytes).expect("ok-tool-call-request.pst is accepted"); + let head = ToolCallHead::parse(msg.payload).expect("a 36-byte head"); + assert_eq!(head.interplane_digest_string(), INTERPLANE_DIGEST); + assert_eq!(payload_digest(&canonical), head.interplane_digest); + assert_eq!(head.canonical_len as usize, canonical.len()); +} + +/// One recorded session (section 10.4 container), checked for the +/// single-message and tool-call rules. Also returns the canonical bytes of +/// every tool call that completed. +fn tool_session(b: &[u8]) -> (String, Vec>) { + let mut tasks: HashMap<[u8; 16], TaskBody> = HashMap::new(); + let mut done = Vec::new(); + assert_eq!(&b[..4], b"PSS1", "recording magic"); + let mut o = 4; + let mut step = 0usize; + let refuse = |r: Refusal, step: usize| format!("refuse {} step={step}", r.code()); + while o < b.len() { + step += 1; + let side = b[o]; + let len = usize::from(u16::from_be_bytes([b[o + 1], b[o + 2]])); + let rec = &b[o + 3..o + 3 + len]; + o += 3 + len; + let msg = match decode(rec) { + Ok(m) => m, + Err(r) => return (refuse(r, step), done), + }; + let id = msg.header.task_id; + if let Some(body) = TaskBody::open(&msg) { + match body { + Ok(body) => { + tasks.entry(id).or_insert(body); + } + Err(r) => return (refuse(r, step), done), + } + continue; + } + let Some(task) = tasks.get_mut(&id) else { + panic!("step {step}: a tool vector names an unknown task"); + }; + if msg.header.msg_type == TYPE_TOOL_CALL_CHUNK { + match task.chunk(msg.payload) { + Ok(true) => { + if let TaskBody::ToolCall(call) = task { + done.push(call.canonical_bytes().expect("verified").to_vec()); + } + } + Ok(false) => {} + Err(r) => return (refuse(r, step), done), + } + } else if side == 2 { + if let Err(r) = task.check_spark(msg.header.msg_type) { + return (refuse(r, step), done); + } + } + } + (format!("ok steps={step} tasks={}", tasks.len()), done) +} + +#[test] +fn every_tool_session_matches_the_c_checker() { + let canonical = read("interplane-tool-request.json"); + let list = String::from_utf8(read("sessions/expected.txt")).expect("utf-8"); + let mut checked = 0usize; + let mut carried = 0usize; + let mut failures = Vec::new(); + for line in list.lines() { + if line.is_empty() || line.starts_with('#') { + continue; + } + let (name, want) = line.split_once(' ').expect("file name and verdict"); + if !name.contains("tool") { + continue; + } + let (got, done) = tool_session(&read(&format!("sessions/{name}"))); + if got != want { + failures.push(format!("{name}\n expected: {want}\n got: {got}")); + } + for bytes in done { + // Carried unchanged: the joined chunks are the INTERPLANE bytes. + if bytes != canonical { + failures.push(format!( + "{name}: joined bytes differ from the INTERPLANE request" + )); + } + carried += 1; + } + checked += 1; + } + assert!( + failures.is_empty(), + "{} of {checked} tool sessions differ:\n{}", + failures.len(), + failures.join("\n") + ); + assert!( + checked >= 9, + "expected at least 9 tool sessions, found {checked}" + ); + assert!(carried >= 1, "no tool session carried the whole request"); +} diff --git a/crates/aien-pi-spark-task/tests/vectors.rs b/crates/aien-pi-spark-task/tests/vectors.rs new file mode 100644 index 0000000..e134c6c --- /dev/null +++ b/crates/aien-pi-spark-task/tests/vectors.rs @@ -0,0 +1,58 @@ +//! Walks `specs/pi-spark-task/vectors/expected.txt` and requires the Rust +//! reader to print the same verdict line as the C reference checker +//! (`tools/pst_verify.c`) for every file, and to write every accepted message +//! back out as the identical bytes. + +use std::path::PathBuf; + +use aien_pi_spark_task::{decode, encode, verdict_line, MAX_MESSAGE}; + +fn vectors_dir() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../specs/pi-spark-task/vectors") +} + +#[test] +fn every_expected_line_matches_the_c_checker() { + let dir = vectors_dir(); + let list = std::fs::read_to_string(dir.join("expected.txt")).expect("read expected.txt"); + let mut checked = 0usize; + let mut accepted = 0usize; + let mut failures = Vec::new(); + for line in list.lines() { + if line.is_empty() || line.starts_with('#') { + continue; + } + let (name, want) = line + .split_once(' ') + .expect("line has a file name and a verdict"); + let bytes = std::fs::read(dir.join(name)).expect("read vector"); + let result = decode(&bytes); + let got = verdict_line(&result); + if got != want { + failures.push(format!("{name}\n expected: {want}\n got: {got}")); + } + if let Ok(msg) = &result { + let mut out = [0u8; MAX_MESSAGE]; + let n = encode(&msg.header, msg.payload, &mut out).expect("re-encode accepted message"); + if out[..n] != bytes[..] { + failures.push(format!("{name}: round trip gave different bytes")); + } + accepted += 1; + } + checked += 1; + } + assert!( + failures.is_empty(), + "{} of {checked} vectors differ:\n{}", + failures.len(), + failures.join("\n") + ); + assert!( + checked >= 23, + "expected at least 23 vectors, found {checked}" + ); + assert!( + accepted >= 4, + "expected at least 4 accepted vectors, found {accepted}" + ); +} diff --git a/specs/.crumb b/specs/.crumb index 33c0cc3..fea3fe2 100644 --- a/specs/.crumb +++ b/specs/.crumb @@ -69,17 +69,23 @@ "last_commit": "37a2159", "name": "osh-platform", "purpose": "OSH platform ABI draft (osh-platform)" + }, + { + "digest": "bb11033e885aff1ebb016de2755677a4474c91e5c8d62f48a89af9c9f7f19171", + "last_commit": "724be77", + "name": "pi-spark-task", + "purpose": "PST1 Pi-Spark task message format (draft)" } ], - "children_root": "sha256:6cf5b33d05298483b233481bc67ac65845482a73ed7a7e876ba7b3cef3bc3527", - "compiled_at": "2026-10-14T13:23:26Z", + "children_root": "sha256:70c974dffb6c59da1ea5d43aef4941afd1fd48f313609467725f15fba0a25888", + "compiled_at": "2026-10-18T15:29:41Z", "compiler": "crumb-compile/1", - "digest": "sha256:7dcc2b4dd4387e1c881350a18e174c57f8f8af8e4d6a2c609045008f5536b5b8", + "digest": "sha256:a648f528cb2717a8a4c48ab49ff96d8c815d708bf958c11d205dc544dda5254f", "evidence_files": 1, "evidence_root": "sha256:87c36bf8ed7be61c064552ebf141834707770b75d070ea49328a3e06d510afba", - "files": 416, - "generated_at_commit": "7d10e1adb9d04310273d6022f2744d471995db55", - "source_tree": "sha256:bdeace5168d590bab6484e6221c2e36cba90badd8a0abf00b02a72dd5884fe44" + "files": 485, + "generated_at_commit": "724be772636bbefac37ee89559ed99d42173bd94", + "source_tree": "sha256:c69d242ad807b6b2772be5aa828a816cd7e1df60a1e5693d803a3d2a728e658e" }, "owner_lane": "", "seed": { diff --git a/specs/pi-spark-task/.crumb b/specs/pi-spark-task/.crumb new file mode 100644 index 0000000..03d453d --- /dev/null +++ b/specs/pi-spark-task/.crumb @@ -0,0 +1,19 @@ +{ + "extensions": { + "generated": { + "children": [], + "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "compiled_at": "2026-10-18T15:29:41Z", + "compiler": "crumb-compile/1", + "digest": "sha256:bb11033e885aff1ebb016de2755677a4474c91e5c8d62f48a89af9c9f7f19171", + "evidence_files": 0, + "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "files": 69, + "generated_at_commit": "724be772636bbefac37ee89559ed99d42173bd94", + "source_tree": "sha256:4948ae24b0a64323301c4e3ecb9ae280bd016a6e8fbf1564fccafa661285c723" + } + }, + "name": "pi-spark-task", + "purpose": "PST1 Pi-Spark task message format (draft)", + "schema_version": "1.0.0" +} diff --git a/specs/pi-spark-task/SPEC.md b/specs/pi-spark-task/SPEC.md new file mode 100644 index 0000000..d735efe --- /dev/null +++ b/specs/pi-spark-task/SPEC.md @@ -0,0 +1,289 @@ +# Pi-Spark Task Message: PST1 + +**Status**: Draft v0.3 (ALLEN Pi/Spark lane C1, 2026-10-16; C3 added the magic, the check order and two codes; C5 added the session rules, section 10; C6 added tool-call tasks, section 11). Not yet produced or read by any runtime. Reference checker and vectors: `tools/pst_verify.c`, `vectors/`. +**Contract version**: 0.1.0 (major zero: may change by minor bump, see VERSIONING.md) +**Wire version**: 1 (the `version` byte below) +**License**: Community Specification License 1.0 +**Tracking**: aien-dev/aien-protocols-mv#28 (C1), parent #27, lane C of aien-dev/aien-architecture-mv#231 +**Not in this document**: the Spark gate (C2), the Rust reader (C4), network framing and retry (aienos-mv#398). + +## 1. Purpose + +The Pi and the Spark need one agreed way to say "please do this task", "here is how it is going" and "here is the receipt". PST1 is that agreement: one bounded message that rides inside exactly one message of the existing reliable channel (M6-A), which rides inside the existing secure session (M6-B). + +PST1 is a control-plane application format. It is not a network stack, not a scheduler, not an authorization layer and not a replacement for INTERPLANE. No PST1 message grants a capability or a permission (section 9). + +## 2. Inventory of what already exists + +| Existing piece | Where | Reused? | Reason | +|---|---|---|---| +| M6-A reliable channel | AIENOS `native/net/aienos_ctl.h` | Yes, as the carrier | In-order, exactly-once delivery inside one session. `CT_MAX_PAYLOAD` is 1024. Big-endian. | +| M6-B secure session | AIENOS `native/net/aienos_sec.h` | Yes, as the trust anchor | Mutual authentication against a pinned roster of one peer key, and an 8-byte `session_id`. TEST keys only today. | +| Cause id and origin run id | aien-architecture `docs/hardening/causal-id-join-v0.md` sections 2.1 and 2.3 (DRAFT, ADR 0025 PROPOSED) | Yes, as header fields | One 32-byte cause id is copied across every handoff, never minted again by the receiver. No runtime mints it yet. | +| Objective id | aien-sovereign-core `crates/aien-runtime/src/objective.rs` | Yes, as a header field | SHA-256 of `AIEN_E2E_OBJECTIVE_V1`, a newline, and the objective text. Written on the Spark by the operator tool, never by the daemon. | +| Effect ledger | aien-sovereign-core `crates/aien-runtime/src/effects.rs` | Yes, as the reconciliation authority | States OPEN, DONE, NOT_DONE, UNRESOLVED. Uncertain results are reconciled against it. | +| ALLEN subject | AIENOS `docs/adr/0018-allen-subject-state-object.md` | Yes, as a reference | The 32-byte agent id. No key material travels. | +| `aien-event-protocol`, `aien-action-protocol` | this repository, `crates/` | No | JSON with unbounded text and free-form `serde_json::Value` payloads. They cannot meet a fixed size limit. | +| TRN1 | this repository, `specs/execution-transcript/` | Pattern only | The house pattern for a byte format with a C reference checker and refusal codes. TRN1 is little-endian; PST1 is not (section 6). | +| INTERPLANE core | `interplane` `rust/crates/interplane-core` | Its canonical request is carried unchanged, only for real tool calls (section 11) | It translates tool requests. It is not a scheduler, a link or an authority. | + +## 3. Layering + +| Layer | Proves or does | Trust | +|---|---|---| +| M6-B | Who the peer is (the pinned key) and which session this is (`session_id`). | Trusted because the transport proved it. | +| M6-A | Delivers each message in order, exactly once, inside one session. | Trusted because the transport proved it. | +| PST1 | Says what the message means: which task, which objective, which kind of event. | Every PST1 field is a claim by the sender. | + +Rules that follow: + +1. The peer and the session are never read from a PST1 field. A receiver takes them from the transport and ignores any PST1 field that claims otherwise. PST1 has no peer field and no session field. +2. A PST1 field that the receiver can check against its own authoritative records (objective id, ALLEN subject id, effect state) is checked before it is believed. +3. A transport acknowledgement means "the message arrived". It never means "the work is done" (section 8). + +## 4. Fixed header + +One PST1 message is a 224-byte fixed header followed by `payload_len` bytes of payload. All integers are big-endian. Every reserved byte is zero on send and refused if non-zero on receipt. + +| Offset | Size | Field | Allowed values | +|---|---|---|---| +| 0 | 4 | `magic` | The ASCII bytes `PST1` (0x50 0x53 0x54 0x31) | +| 4 | 1 | `version` | 1 | +| 5 | 1 | `type` | 1 to 16 (section 5) | +| 6 | 2 | `reserved0` | 0 | +| 8 | 32 | `cause_id` | Not all zero | +| 40 | 32 | `origin_run_id` | Any value (opaque, copied) | +| 72 | 32 | `objective_id` | Not all zero for `request`; copied on every later message | +| 104 | 32 | `subject_id` | The ALLEN subject reference (ADR 0018); no key material | +| 136 | 16 | `parent_task_id` | All zero means "no parent" | +| 152 | 16 | `task_id` | Not all zero | +| 168 | 16 | `idempotence_key` | Not all zero; see section 8 | +| 184 | 4 | `ordinal` | u32; see section 5 | +| 188 | 1 | `effect_class` | 0 NONE, 1 COMPUTE, 2 EFFECT | +| 189 | 1 | `reserved1` | 0 | +| 190 | 2 | `payload_len` | 0 to 800 | +| 192 | 32 | `payload_digest` | SHA-256 of the payload bytes (of the empty string when `payload_len` is 0) | + +Total header: 224 bytes. + +Change from Draft v0 (C3, aien-protocols-mv#30): Draft v0 had no magic, so a receiver could not tell a PST1 message from any other 1024-byte blob, and the C3 vectors could not test a "bad magic" refusal. The 4-byte magic now opens the header. To keep the header at 224 bytes (and the 800-byte payload cap), `reserved1` shrank from 3 bytes to 1 and `reserved2` was removed. Every field after `type` moved by 4 bytes, except `payload_digest`, which stays at 192. + +`effect_class` is a claim about the work, not a permission. EFFECT work still needs a real grant from the Spark approval desk (lane G, G6). + +### 4.1 Check order + +A receiver checks one message in this order and reports the first rule that fails. The C reference checker (`tools/pst_verify.c`) and every other reader follow the same order, so the same bytes always give the same code. + +1. Fewer than 224 bytes, or more than 1024 bytes: `PST_BAD_LENGTH`. +2. `magic` is not `PST1`: `PST_BAD_MAGIC`. +3. `version` is 0 (below the lowest version this receiver accepts): `PST_DOWNGRADE`. `version` above 1: `PST_BAD_VERSION`. +4. `type` is 0 or above 16: `PST_BAD_TYPE`. +5. `reserved0` or `reserved1` is non-zero: `PST_RESERVED_NONZERO`. +6. The bytes after the header are fewer than `payload_len`: `PST_BAD_LENGTH`. (A `payload_len` above 800 always lands here or in step 1, since 224 plus 801 is more than 1024.) +7. The bytes after the header are more than `payload_len`: `PST_TRAILING_BYTES`. +8. `effect_class` above 2: `PST_BAD_EFFECT_CLASS`. +9. `cause_id` all zero: `PST_NO_CAUSE`. +10. `task_id` all zero, then `idempotence_key` all zero: `PST_NO_TASK`. +11. `type` is `request` or `tool_call_request` and `objective_id` is all zero: `PST_NO_OBJECTIVE`. +12. `payload_digest` differs from the SHA-256 of the payload: `PST_DIGEST_MISMATCH`. +13. `type` is `tool_call_request` and the payload is not exactly 36 bytes, or its canonical length is 0 or above 102400: `PST_BAD_TOOL_HEAD` (section 11.2). + +The checks that need more than one message (`PST_WRONG_SIDE`, `PST_SUBJECT_MISMATCH`, a version lower than the one already used in the session, and the tool-call body checks of section 11.3) come after these and belong to the session rules (sections 10 and 11). + +## 5. Message types + +`request`, `cancel request`, `resume request`, `tool_call_request` and `tool_call_chunk` are sent by the Pi. Every other type is sent by the Spark. A message of a type from the wrong side is refused. + +| Value | Type | Side | Payload | +|---|---|---|---| +| 1 | `request` | Pi | Task description bytes (UTF-8 text, or the request body named by the task kind) | +| 2 | `accepted` | Spark | Empty | +| 3 | `queued` | Spark | Empty | +| 4 | `running` | Spark | Empty | +| 5 | `text_chunk` | Spark | One piece of streamed text | +| 6 | `waiting_for_approval` | Spark | The 32-byte digest of the action awaiting approval | +| 7 | `completed` | Spark | The 32-byte digest of the result | +| 8 | `failed` | Spark | A short reason code and text | +| 9 | `cancelled` | Spark | Empty | +| 10 | `uncertain_after_disconnect` | Spark | Empty. Means "not known whether it happened" (section 8) | +| 11 | `resume_snapshot` | Spark | The state of one task as read from the authoritative records | +| 12 | `receipt_reference` | Spark | The 32-byte digest of a receipt held on the Spark | +| 13 | `cancel_request` | Pi | Empty | +| 14 | `resume_request` | Pi | Empty | +| 15 | `tool_call_request` | Pi | The 36-byte tool-call head: the INTERPLANE request digest and length (section 11) | +| 16 | `tool_call_chunk` | Pi | The next piece of the INTERPLANE canonical request bytes (section 11) | + +`ordinal` numbers the messages of one task from the sender's side, starting at 0 and rising by one. `text_chunk` messages of one task carry consecutive ordinals so a lost or repeated chunk is visible. The order rules between types are in section 10. + +Status is derived from authoritative execution state on the Spark. A `completed`, `failed` or `cancelled` message is only sent after the authoritative record says so. Events are hints until the receiver has checked what it can. + +## 6. Size and byte order + +1. One PST1 message (224 header bytes plus up to 800 payload bytes, so at most 1024) fits in one M6-A message (`CT_MAX_PAYLOAD`, 1024). A message that would be longer is refused with `PST_BAD_LENGTH`. +2. A long text stream is split into numbered `text_chunk` messages. There is no reassembly of one PST1 message across several transport messages. The receiver joins chunks by ordinal, not by transport framing. The body of a tool-call task is the one other joined body: its INTERPLANE request travels in numbered `tool_call_chunk` messages (section 11), each still one complete PST1 message. +3. **Byte order is big-endian**, to match the M6-A and M6-B headers PST1 rides inside, so one implementation reads one convention on the whole link. TRN1 chose little-endian for a file format that never rides on this link. This choice is a recommendation made without a measurement; it is not final until C3 vectors and the aienos lane both accept it. + +## 7. Refusal codes + +A receiver refuses the message and takes no action. It reports one of these, choosing by the check order in section 4.1. A refusal never changes task state. + +| Code | Meaning | +|---|---| +| `PST_BAD_MAGIC` | The first 4 bytes are not `PST1` | +| `PST_BAD_VERSION` | `version` is above 1 (unknown version) | +| `PST_DOWNGRADE` | `version` is 0 (below the lowest accepted version), or lower than the version already used in this session | +| `PST_BAD_TYPE` | `type` is 0 or above 16 | +| `PST_WRONG_SIDE` | A Pi-only type from the Spark, or the reverse | +| `PST_BAD_LENGTH` | Fewer than 224 bytes, more than 1024 bytes, `payload_len` above 800, or fewer payload bytes than `payload_len` | +| `PST_TRAILING_BYTES` | More payload bytes than `payload_len` (and the total is at most 1024) | +| `PST_RESERVED_NONZERO` | Any reserved byte is non-zero | +| `PST_NO_CAUSE` | `cause_id` is all zero | +| `PST_NO_TASK` | `task_id` or `idempotence_key` is all zero | +| `PST_NO_OBJECTIVE` | A `request` whose `objective_id` is all zero (added in C3: Draft v0 stated the rule but named no code) | +| `PST_DIGEST_MISMATCH` | `payload_digest` does not match the payload | +| `PST_BAD_EFFECT_CLASS` | `effect_class` above 2 | +| `PST_SUBJECT_MISMATCH` | `subject_id` differs from the subject bound to this session | +| `PST_BAD_ORDER` | A message the session rules (section 10.2) do not allow in the task's current state | +| `PST_SECOND_FINAL` | A second `completed`, `failed` or `cancelled` for one task | +| `PST_ORDINAL_GAP` | An `ordinal` higher than the next expected one for that task and side | +| `PST_ORDINAL_REPEAT` | An `ordinal` lower than the next expected one for that task and side | +| `PST_IDEMPOTENCE_CONFLICT` | An `idempotence_key` reused for another task, or a known task repeated with another key or payload digest | +| `PST_UNKNOWN_TASK` | A message other than `request` for a task the session has no `request` for | +| `PST_CONTEXT_MISMATCH` | A copied field differs from the task's `request` (section 10.3, step 5) | +| `PST_SESSION_FULL` | A new task beyond the receiver's task limit | +| `PST_BAD_RECORDING` | A recorded session file (section 10.4) that does not parse; test vectors only | +| `PST_BAD_TOOL_HEAD` | A `tool_call_request` payload that is not exactly the 36-byte head, or whose canonical length is 0 or above 102400 (section 11.2) | +| `PST_TOOL_CHUNK_SIZE` | A `tool_call_chunk` that is not exactly 800 bytes, or exactly the bytes still missing when fewer than 800 are left; this covers extra bytes past the end of the request (section 11.3) | +| `PST_TOOL_DIGEST_MISMATCH` | The joined tool-call bytes do not have the SHA-256 the head names (section 11.3) | +| `PST_TOOL_INCOMPLETE` | A Spark message other than `failed` or `cancelled` for a tool-call task whose bytes are not all in and checked (section 11.3) | +| `PST_NOT_TOOL_TASK` | A `tool_call_chunk` for a task opened by `request`: an ordinary task never carries a tool-call payload (section 11.1) | + +A receiver that gets work with no cause id refuses it (`PST_NO_CAUSE`); it does not mint one. The cause id is minted once, where the outside request first enters AIEN (on the Pi, at the user's turn), per the causal id join spec. + +## 8. Exactly once has limits + +1. A transport acknowledgement is not "done". M6-A delivers a message once; it says nothing about whether the work ran. +2. A repeated `request` with the same `idempotence_key` and the same `task_id` is recognised as the same request and does not start a second task. +3. When the link drops while an effect is in flight, the Spark reports `uncertain_after_disconnect`. It does not report `failed` or `cancelled` when it does not know. +4. An effect whose outcome is unknown is reconciled against the Spark effect ledger (OPEN, DONE, NOT_DONE, UNRESOLVED) before anything is retried. A possibly committed effect is never sent again on the strength of a retry alone. +5. A local model's routing choice on the Pi grants nothing. Model output is never an authorization. + +## 9. No capability, no permission + +No message type, field or value in PST1 grants a capability, a permission, an approval or an identity. `waiting_for_approval` asks; it does not decide. Approvals come from the Spark approval desk and are not carried as PST1 fields. The ALLEN subject stays the authority on the Pi. + +## 10. Session rules (C5) + +A message can be well formed and still be a lie in its place: "completed" for a task that was never accepted, a second final answer, a missing text chunk, a completion claimed by the Pi. This section says which message may follow which inside one M6-B session. A receiver checks every message against it, after the single-message checks of section 4.1, and refuses at the first broken step. A refusal changes no task state. + +Scope of this first cut (aien-protocols-mv#32): the normal life of a task (request, accepted, optionally queued, running, text chunks, completed) and the failed and cancelled endings, the Pi's `cancel_request` and `resume_request`, and repeated requests. `waiting_for_approval`, `uncertain_after_disconnect`, `resume_snapshot` and `receipt_reference` are refused with `PST_BAD_ORDER` in a session until their rules are written (open question 5). + +### 10.1 Who may send what + +The side comes from the transport (section 3, rule 1), never from a PST1 field. The Pi sends only `request` (1), `cancel_request` (13), `resume_request` (14), `tool_call_request` (15) and `tool_call_chunk` (16). The Spark sends every other type. Anything else is `PST_WRONG_SIDE`; this is how a completion or an approval claimed by the Pi is refused. + +### 10.2 Allowed sequence for one task + +| Type | Sent by | Allowed when the task is | Task becomes | +|---|---|---|---| +| `request` (new `task_id`) | Pi | (no task yet) | REQUESTED | +| `request` (known `task_id`, same `idempotence_key` and `payload_digest`) | Pi | any state | unchanged: a recognised repeat (section 8, item 2) | +| `accepted` | Spark | REQUESTED | ACCEPTED | +| `queued` | Spark | ACCEPTED | QUEUED | +| `running` | Spark | ACCEPTED or QUEUED | RUNNING | +| `text_chunk` | Spark | RUNNING | RUNNING | +| `completed` | Spark | RUNNING | FINAL | +| `failed`, `cancelled` | Spark | REQUESTED, ACCEPTED, QUEUED or RUNNING | FINAL | +| `cancel_request`, `resume_request` | Pi | any state | unchanged | +| `tool_call_request` (new `task_id`) | Pi | (no task yet) | COLLECTING (section 11) | +| `tool_call_request` (known `task_id`, same `idempotence_key` and `payload_digest`) | Pi | any state | unchanged: a recognised repeat | +| `tool_call_chunk` | Pi | COLLECTING, task opened by `tool_call_request` | COLLECTING, or REQUESTED once the last chunk is in and its digest matches | +| `failed`, `cancelled` | Spark | COLLECTING | FINAL | + +So a normal task reads: `request`, `accepted`, (`queued`), `running`, `text_chunk` any number of times, `completed`. Tasks of one session may interleave; each task follows its own row. + +### 10.3 Check order for one message in a session + +1. The single-message checks (section 4.1). +2. Side (10.1): `PST_WRONG_SIDE`. +3. Subject: the first message of the session binds its `subject_id`; any later different `subject_id` is `PST_SUBJECT_MISMATCH`. +4. Task: a `request` or `tool_call_request` with a new `task_id` whose `idempotence_key` already belongs to another task is `PST_IDEMPOTENCE_CONFLICT`. A `request` or `tool_call_request` for a known `task_id` with a different `idempotence_key`, `payload_digest` or opening type is `PST_IDEMPOTENCE_CONFLICT`. Any other type naming a `task_id` the session has no `request` for is `PST_UNKNOWN_TASK` (this covers a `resume_request` for an unknown task). A new task beyond the receiver's limit is `PST_SESSION_FULL`; the reference checker allows 16 tasks per session. +5. Context: `cause_id`, `origin_run_id`, `objective_id`, `parent_task_id`, `idempotence_key` and `effect_class` must equal the task's `request`: `PST_CONTEXT_MISMATCH`. A recognised repeat of the `request` stops here and changes nothing. +6. Ordinal: per task and per side, the first message carries 0 and each next one carries one more. Higher than expected is `PST_ORDINAL_GAP` (a message, for example a text chunk, was skipped); lower is `PST_ORDINAL_REPEAT`. +7. Tool-call body (section 11.3), for a `tool_call_chunk` or a Spark message on a COLLECTING task. +8. Order (10.2): a final type (`completed`, `failed`, `cancelled`) after FINAL is `PST_SECOND_FINAL`; any other step not allowed by the table is `PST_BAD_ORDER`. + +Version inside a session: the first message binds the version; a later lower version is `PST_DOWNGRADE` and a later higher one `PST_BAD_VERSION`. While version 1 is the only accepted version this cannot happen past step 1, so the reference checker has no separate check for it yet. + +### 10.4 Recording format (test vectors only) + +A recorded session (`vectors/sessions/*.pss`) is the 4 bytes `PSS1`, then for each delivered message in delivery order: 1 byte side (1 Pi, 2 Spark), 2 bytes big-endian length, the message bytes. This is a test container, not a wire format. A recording that does not parse is refused with `PST_BAD_RECORDING`. The verdict line is `ok steps=N tasks=T` or `refuse CODE step=N`, where step N is the 1-based message position. + +## 11. Tool-call tasks (C6) + +When the model asks to run a tool, the task carries the tool request in INTERPLANE's agreed form, byte for byte, so the Pi and the Spark hash the same bytes. Ordinary chat never uses this path. Tracking: aien-protocols-mv#33. + +Ground truth: aien-dev/interplane-mv at commit `83df0f074b2c572473cd535c89f767df48933f4a`. INTERPLANE's canonical form is RFC 8785 canonical JSON, and its digest is `sha256:` followed by the lower-case hex SHA-256 of those bytes (`rust/crates/interplane-core/src/jcs.rs`, `canonicalize` and `digest_bytes`). The carried value is one INTERPLANE `tool_request` payload (`kind` `tool_request`, `rust/crates/interplane-core/src/types.rs`), canonicalized by interplane-core. + +### 11.1 Which tasks are tool calls + +1. The message that opens a task fixes its kind for the life of the task. `request` (1) opens an ordinary task. `tool_call_request` (15) opens a tool-call task. +2. Only a tool-call task carries `tool_call_chunk` (16) messages. A `tool_call_chunk` for a task opened by `request` is refused with `PST_NOT_TOOL_TASK`: an ordinary task never carries a tool-call payload. +3. A tool call is never read out of an ordinary task's text. A receiver does not parse a `request` payload as INTERPLANE, even when it looks like JSON. A repeat of the opening message with the other opening type is `PST_IDEMPOTENCE_CONFLICT` (section 10.3, step 4). + +### 11.2 The head (`tool_call_request` payload) + +The payload of a `tool_call_request` is exactly 36 bytes, and nothing else: + +| Offset | Size | Field | Allowed values | +|---|---|---|---| +| 0 | 32 | `interplane_digest` | SHA-256 of the INTERPLANE canonical request bytes: the 32 bytes whose lower-case hex is the part of its `sha256:` digest after the prefix | +| 32 | 4 | `canonical_len` | u32, big-endian; 1 to 102400 | + +A head of any other length (an extra field, a missing length) or a `canonical_len` of 0 or above 102400 is refused with `PST_BAD_TOOL_HEAD` (section 4.1, step 13). 102400 is 128 chunks of 800 bytes; it is above INTERPLANE's 65536-byte argument limit (`spec/CORE.md`), leaving room for the rest of the request. A longer request cannot travel as one tool-call task. The header's `objective_id` must not be all zero, as for `request`. + +### 11.3 The chunks and the check + +1. The canonical bytes follow in `tool_call_chunk` messages from the Pi, Pi-side ordinals 1, 2, 3 and on (the head carries ordinal 0). Each chunk payload is the next piece of the canonical bytes, in order, with nothing added: every chunk is exactly 800 bytes except the last, which is exactly the bytes still missing. So one request always gives the same chunks. A chunk of any other size is refused with `PST_TOOL_CHUNK_SIZE`; this covers a short chunk and a last chunk with bytes past the end of the request. +2. The chunks are sent even when the request is shorter than 800 bytes (then there is one chunk). The request bytes are never put into the head. +3. When the joined bytes reach `canonical_len`, the receiver computes their SHA-256 and compares it with `interplane_digest`. A difference (a changed byte, a head naming another request) is refused with `PST_TOOL_DIGEST_MISMATCH`. Each chunk's own `payload_digest` (section 4) is checked first, as for any message; it covers that chunk only. +4. While the bytes are not all in and checked, the task is COLLECTING. A Spark message other than `failed` or `cancelled` for a COLLECTING task is refused with `PST_TOOL_INCOMPLETE`: the Spark does not accept, queue or run a tool call it has not received in full. A truncated request (the Pi stops early) therefore never reaches `accepted`. The Spark may end a COLLECTING task with `failed` or `cancelled`. +5. After the check passes, the task is REQUESTED and follows section 10.2 like any other. A further `tool_call_chunk` is refused with `PST_BAD_ORDER`. +6. The checked bytes are handed to INTERPLANE unchanged. PST1 checks bytes, length and digest only; it does not parse JSON. Whether the bytes are a valid, canonical INTERPLANE request is decided by interplane-core on the Spark, not by PST1. + +### 11.4 No authority moves + +Carrying a tool request moves no permission. INTERPLANE core "executes nothing and authorizes nothing" (`rust/crates/interplane-core/src/lib.rs`, line 3), and neither does PST1 (section 9). Approval of the tool call stays with the existing Spark approval desk and with AIENOS authority (the ALLEN subject on the Pi). A `tool_call_request`, its `effect_class` and its chunks are a claim about what the model asked for, never an approval. + +### 11.5 Vectors + +The carried request is `vectors/interplane-tool-request.json` (1743 bytes, digest `sha256:78dbef7ee689b20ad9ae530fd7fa8417fb671778667b27f910484156776990d6`), written by `tools/interplane-request` (interplane-core at the commit above) and embedded in `tools/pst_verify.c`, which refuses to generate vectors if the embedded bytes no longer have that digest. + +| Vector | Verdict | +|---|---| +| `ok-tool-call-request.pst`, `ok-tool-call-chunk.pst` | accepted single messages (the head, the first chunk) | +| `bad-tool-head-extra-field.pst`, `bad-tool-head-short.pst`, `bad-tool-head-zero-length.pst`, `bad-tool-head-over-limit.pst` | `PST_BAD_TOOL_HEAD` | +| `bad-tool-request-no-objective.pst` | `PST_NO_OBJECTIVE` | +| `sessions/ok-tool-call.pss` | the head, three chunks (800, 800, 143), then `accepted`, `running`, `completed` | +| `sessions/ok-tool-call-failed-while-collecting.pss` | the Spark ends an incomplete tool call with `failed` | +| `sessions/bad-tool-digest-mismatch.pss` | the head names another digest: `PST_TOOL_DIGEST_MISMATCH` | +| `sessions/bad-tool-altered-byte.pss` | one byte of the second chunk changed: `PST_TOOL_DIGEST_MISMATCH` | +| `sessions/bad-tool-extra-bytes.pss` | the last chunk has one byte past the request: `PST_TOOL_CHUNK_SIZE` | +| `sessions/bad-tool-short-chunk.pss` | a first chunk of 799 bytes: `PST_TOOL_CHUNK_SIZE` | +| `sessions/bad-tool-chunk-after-complete.pss` | a chunk after the request is complete: `PST_BAD_ORDER` | +| `sessions/bad-tool-truncated.pss` | `accepted` with the last chunk missing: `PST_TOOL_INCOMPLETE` | +| `sessions/bad-tool-payload-in-chat-task.pss` | a chat task carries a tool-call chunk: `PST_NOT_TOOL_TASK` | + +The Rust reader (`crates/aien-pi-spark-task`, `tests/tool_call.rs`) reads the same files and must print the same verdict line for every tool session, and its joined bytes must equal `interplane-tool-request.json` byte for byte. + +## 12. Open questions + +These are stated plainly so the C3 vectors and the neighbouring lanes can settle them. None is decided here. + +1. Task id width (16 bytes here) and whether it should instead be derived from the cause id. UNVERIFIED. +2. Whether `resume_snapshot` needs its own payload layout, or a task-kind byte inside the payload. To be fixed by G3 and C5. +3. The aienos lane (aienos-mv#398) must confirm it can carry 1024-byte messages end to end and agree the framing. +4. Whether big-endian stays (section 6, item 3). +5. Session rules for `waiting_for_approval`, `uncertain_after_disconnect`, `resume_snapshot` and `receipt_reference` (section 10). Until then a session refuses them with `PST_BAD_ORDER`. +6. Whether a tool-call task should carry the full INTERPLANE envelope instead of the `tool_request` payload alone (section 11). The payload was chosen because the envelope's source and destination repeat facts the transport proves (section 3). To settle with aien-dev/interplane-mv#101 before merge. +7. Whether the 102400-byte tool-call limit (section 11.2) is right for real tool requests. Chosen without a measurement. diff --git a/specs/pi-spark-task/tools/check-vectors.sh b/specs/pi-spark-task/tools/check-vectors.sh new file mode 100755 index 0000000..50639a4 --- /dev/null +++ b/specs/pi-spark-task/tools/check-vectors.sh @@ -0,0 +1,67 @@ +#!/bin/bash +# check-vectors.sh: build the PST1 reference checker and check the vectors. +# +# Usage: check-vectors.sh [CC] (default CC: cc) +# +# 1. Builds tools/pst_verify.c with warnings as errors (C99, libc only). +# 2. Regenerates the vectors into a scratch directory (pst_verify +# --make-vectors) and requires them byte-identical to vectors/, so a stale +# or hand-edited vector fails here. +# 3. Runs every vectors/expected.txt and vectors/sessions/expected.txt line +# (re-encoding every accepted message, which must give the same bytes), +# plus an ASan/UBSan build when the compiler supports it. +# 4. Runs the seeded random session test twice (same seed, same output). +# 5. Runs tools/mutate-verifier.sh: every check must be caught by a vector. +# Host-only check: no hardware. Shell and C only. Found by the PROTO-C-VECTORS +# gate (tests/gates/run.sh c-vectors) because its name matches check-*.sh. +set -eu +export LC_ALL=C +here=$(cd "$(dirname "$0")" && pwd) +vec="$here/../vectors" +CC=${1:-cc} +tmp=$(mktemp -d) +trap 'rm -rf "$tmp"' EXIT + +"$CC" -std=c99 -O2 -Wall -Wextra -Werror -pedantic -o "$tmp/pst_verify" "$here/pst_verify.c" + +mkdir -p "$tmp/regen/sessions" +"$tmp/pst_verify" --make-vectors "$tmp/regen" +ignore="-x .crumb -x .crumb.local -x .gitattributes" +if ! diff -r $ignore "$vec" "$tmp/regen" >/dev/null; then + echo "PST1_VECTORS_STALE: vectors/ differs from pst_verify --make-vectors output" >&2 + diff -rq $ignore "$vec" "$tmp/regen" >&2 || true + exit 1 +fi +echo "PST1_VECTORS_REGEN identical" + +"$tmp/pst_verify" --corpus "$vec" + +if "$CC" -std=c99 -O1 -g -fsanitize=address,undefined -fno-sanitize-recover=all \ + -o "$tmp/pst_verify_san" "$here/pst_verify.c" 2>/dev/null; then + "$tmp/pst_verify_san" --corpus "$vec" | sed 's/^PST1_CONFORMANCE impl=c/PST1_CONFORMANCE impl=c-asan-ubsan/' + test "${PIPESTATUS[0]}" -eq 0 +else + echo "PST1_SANITIZER NOT_RUN (compiler lacks -fsanitize=address,undefined)" +fi + + +# Seeded random sessions (spec section 10, aien-protocols-mv#32 item 4): +# reorder, drop and duplicate records of every accepted session. Each result +# is accepted or refused with a code; the same seed must give the same counts +# and the same digest of all verdict lines on two runs and under ASan/UBSan. +seed=${PST1_FUZZ_SEED:-20261016} +count=${PST1_FUZZ_COUNT:-20000} +"$tmp/pst_verify" --session-fuzz "$seed" "$count" "$vec"/sessions/ok-*.pss >"$tmp/fuzz1" +"$tmp/pst_verify" --session-fuzz "$seed" "$count" "$vec"/sessions/ok-*.pss >"$tmp/fuzz2" +cat "$tmp/fuzz1" +cmp -s "$tmp/fuzz1" "$tmp/fuzz2" || { echo "PST1_SESSION_FUZZ_NONDETERMINISTIC" >&2; exit 1; } +if [ -x "$tmp/pst_verify_san" ]; then + "$tmp/pst_verify_san" --session-fuzz "$seed" "$count" "$vec"/sessions/ok-*.pss >"$tmp/fuzz3" + cmp -s "$tmp/fuzz1" "$tmp/fuzz3" || { echo "PST1_SESSION_FUZZ_SANITIZER_DIFFERS" >&2; exit 1; } + echo "PST1_SESSION_FUZZ repeat=identical sanitizer=identical" +else + echo "PST1_SESSION_FUZZ repeat=identical sanitizer=NOT_RUN" +fi + +bash "$here/mutate-verifier.sh" "$CC" +echo "PST1_VECTORS_PASS" diff --git a/specs/pi-spark-task/tools/interplane-request/Cargo.lock b/specs/pi-spark-task/tools/interplane-request/Cargo.lock new file mode 100644 index 0000000..aa12d33 --- /dev/null +++ b/specs/pi-spark-task/tools/interplane-request/Cargo.lock @@ -0,0 +1,260 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "interplane-core" +version = "0.3.0" +source = "git+https://github.com/aien-dev/interplane-mv?rev=83df0f074b2c572473cd535c89f767df48933f4a#83df0f074b2c572473cd535c89f767df48933f4a" +dependencies = [ + "regex", + "serde", + "serde_json", + "sha2", + "thiserror", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "pst1-interplane-request" +version = "0.0.0" +dependencies = [ + "interplane-core", + "serde_json", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/specs/pi-spark-task/tools/interplane-request/Cargo.toml b/specs/pi-spark-task/tools/interplane-request/Cargo.toml new file mode 100644 index 0000000..fe679a0 --- /dev/null +++ b/specs/pi-spark-task/tools/interplane-request/Cargo.toml @@ -0,0 +1,19 @@ +# Produces the one INTERPLANE canonical tool request that the PST1 tool-call +# vectors carry (SPEC.md section 11). Not a workspace member and not part of +# any runtime: it is run by hand when the vector request changes. +# +# cargo run --manifest-path specs/pi-spark-task/tools/interplane-request/Cargo.toml -- OUT +# +# writes the canonical bytes to OUT and prints the INTERPLANE `sha256:` digest. +[package] +name = "pst1-interplane-request" +version = "0.0.0" +edition = "2021" +license = "AGPL-3.0-or-later" +publish = false + +[workspace] + +[dependencies] +interplane-core = { git = "https://github.com/aien-dev/interplane-mv", rev = "83df0f074b2c572473cd535c89f767df48933f4a" } +serde_json = "1.0" diff --git a/specs/pi-spark-task/tools/interplane-request/src/main.rs b/specs/pi-spark-task/tools/interplane-request/src/main.rs new file mode 100644 index 0000000..a245758 --- /dev/null +++ b/specs/pi-spark-task/tools/interplane-request/src/main.rs @@ -0,0 +1,67 @@ +//! Writes the INTERPLANE canonical tool request carried by the PST1 tool-call +//! vectors (specs/pi-spark-task/SPEC.md section 11) and prints its digest. +//! +//! The request is built as a JSON value, checked to parse as an INTERPLANE +//! `tool_request` payload, and written as interplane-core's RFC 8785 canonical +//! bytes. It is longer than one PST1 payload (800 bytes) on purpose, so the +//! vectors need three chunks. +use std::process::ExitCode; + +use interplane_core::{canonicalize, digest_bytes, Payload}; +use serde_json::{json, Value}; + +fn request() -> Value { + let text = "Find every receipt from the last week that mentions the garden \ + hose, the rain barrel or the drip line. Summarise each one in a single \ + plain sentence: what was bought, where, and for how much. Leave out card \ + numbers and addresses. If two receipts look like the same purchase, say \ + so instead of counting it twice.\n"; + json!({ + "kind": "tool_request", + "request_id": "pst1-c6-vector-1", + "tool": {"namespace": "aien.receipts", "name": "search"}, + "arguments": { + "query": "garden hose OR rain barrel OR drip line", + "since_days": 7, + "limit": 25, + "fields": ["merchant", "date", "total", "items"], + "redact": ["card_number", "address"], + "instructions": text.repeat(4), + "locale": "en-GB", + "currency_hint": "\u{a3}", + "note": "caf\u{e9} \u{2615} \u{1f327}" + }, + "provenance": { + "dialect": "openai", + "parser_version": "1.0.0", + "model": "pi-local-router", + "source_turn": 7, + "source_call_id": "call_pst1_c6" + } + }) +} + +fn main() -> ExitCode { + let Some(out) = std::env::args().nth(1) else { + eprintln!("usage: pst1-interplane-request OUT"); + return ExitCode::from(2); + }; + let v = request(); + if !matches!(Payload::from_value(&v), Ok(Payload::ToolRequest(_))) { + eprintln!("not an INTERPLANE tool_request"); + return ExitCode::from(1); + } + let canon = canonicalize(&v); + let again: Value = serde_json::from_str(&canon).expect("canonical text parses"); + assert_eq!(canonicalize(&again), canon, "canonical form is stable"); + if let Err(e) = std::fs::write(&out, canon.as_bytes()) { + eprintln!("cannot write {out}: {e}"); + return ExitCode::from(2); + } + println!( + "bytes={} digest={}", + canon.len(), + digest_bytes(canon.as_bytes()) + ); + ExitCode::SUCCESS +} diff --git a/specs/pi-spark-task/tools/mutate-verifier.sh b/specs/pi-spark-task/tools/mutate-verifier.sh new file mode 100755 index 0000000..748d90d --- /dev/null +++ b/specs/pi-spark-task/tools/mutate-verifier.sh @@ -0,0 +1,30 @@ +#!/bin/bash +# mutate-verifier.sh: show that every check in pst_verify.c is exercised by +# the vectors. Builds one checker per check with that check disabled +# (-DPST_MUTANT=K) and requires the vectors to report at least one miss. +# A mutant the vectors do not notice is a SURVIVOR and fails this script. +# +# Usage: mutate-verifier.sh [CC] +set -eu +export LC_ALL=C +here=$(cd "$(dirname "$0")" && pwd) +vec="$here/../vectors" +CC=${1:-cc} +tmp=$(mktemp -d) +trap 'rm -rf "$tmp"' EXIT +names=$(sed -n '/CHK_MAX_TOTAL = 1/,/CHK_LAST/p' "$here/pst_verify.c" | sed 's|/\*.*\*/||' | tr -d ' \n' | sed 's/CHK_MAX_TOTAL=1/CHK_MAX_TOTAL/; s/,CHK_LAST.*//' | tr ',' ' ') +test -n "$names" || { echo "cannot read the check list" >&2; exit 2; } +k=0 killed=0 survived=0 +for name in $names; do + k=$((k + 1)) + "$CC" -std=c99 -O1 -w -DPST_MUTANT=$k -o "$tmp/m$k" "$here/pst_verify.c" + if "$tmp/m$k" --corpus "$vec" >"$tmp/out$k" 2>&1; then + echo "SURVIVOR $k $name" + survived=$((survived + 1)) + else + echo "killed $k $name: $(grep -c 'MISMATCH' "$tmp/out$k") vector(s) differ" + killed=$((killed + 1)) + fi +done +echo "PST1_VERIFIER_MUTANTS total=$k killed=$killed survived=$survived" +test "$survived" -eq 0 && test "$k" -gt 0 diff --git a/specs/pi-spark-task/tools/pst_verify.c b/specs/pi-spark-task/tools/pst_verify.c new file mode 100644 index 0000000..e5cc3cc --- /dev/null +++ b/specs/pi-spark-task/tools/pst_verify.c @@ -0,0 +1,1097 @@ +/* pst_verify.c: reference checker for PST1, the Pi-Spark task message. + * Spec: ../SPEC.md (contract 0.1.0, wire version 1): sections 4 and 7 for one + * message, section 10 for a recorded session, section 11 for tool-call tasks. + * + * Self-contained C99: its own SHA-256 (FIPS 180-4), libc only, no heap + * anywhere (static buffers), no clock. The decoder pst_decode() is a pure + * function of one read-only buffer; the encoder pst_encode() is a pure + * function of one message struct. It exists to pin the format with vectors, + * not to be linked into a runtime. + * + * Usage: + * pst_verify FILE print one verdict line + * pst_verify --corpus DIR check every DIR/expected.txt line, re-encode + * every accepted message and require the same + * bytes, then every DIR/sessions/expected.txt line; + * print PST1_CONFORMANCE impl=c pass=N fail=M + * pst_verify --session FILE check one recorded session (spec section 10) + * pst_verify --make-vectors DIR write the vector files, DIR/expected.txt, + * DIR/sessions/ (the directory must exist) and + * DIR/interplane-tool-request.json, the INTERPLANE + * canonical request the tool-call vectors carry + * pst_verify --session-fuzz SEED COUNT FILE... + * COUNT seeded reorderings, drops and duplications + * of the given sessions; prints the verdict counts + * and one digest of all verdict lines + * + * Verdict line (the format expected.txt pins): + * ok type=T version=V cause=H64 origin=H64 objective=H64 subject=H64 + * parent=H32 task=H32 idem=H32 ordinal=N effect=E len=L digest=H64 + * refuse CODE (CODE is a name from SPEC.md section 7) + * (one line; Hn is n lower-case hex digits). + * Session verdict line: ok steps=N tasks=T, or refuse CODE step=N. + * + * Exit status: 0 on accept / all corpus lines agree, 1 otherwise, 2 on usage + * or I/O error. + * + * Mutation hooks: building with -DPST_MUTANT=K disables check K (the CHK_* + * numbers below). tools/mutate-verifier.sh builds every mutant and requires + * the vectors to fail each one, which shows every check is exercised. + */ +#include +#include +#include +#include + +#ifndef PST_MUTANT +#define PST_MUTANT 0 +#endif +#define CHECK(k) (PST_MUTANT != (k)) + +enum { + CHK_MAX_TOTAL = 1, CHK_MAGIC, CHK_DOWNGRADE, CHK_VERSION, CHK_TYPE, + CHK_RESERVED0, CHK_RESERVED1, CHK_PAYLOAD_SHORT, CHK_TRAILING, CHK_EFFECT, + CHK_CAUSE, CHK_TASK, CHK_IDEM, CHK_OBJECTIVE, CHK_DIGEST, CHK_TOOL_HEAD_LEN, CHK_TOOL_HEAD_BOUND, + /* session rules (spec section 10.3) */ + CHK_S_SIDE, CHK_S_SUBJECT, CHK_S_IDEM_OTHER, CHK_S_IDEM_SAME, CHK_S_UNKNOWN_TASK, + CHK_S_CONTEXT, CHK_S_REPEAT_REQUEST, CHK_S_GAP, CHK_S_REPEAT, CHK_S_SECOND_FINAL, + CHK_S_ORDER, + /* tool-call tasks (spec section 11) */ + CHK_S_NOT_TOOL, CHK_S_TOOL_CHUNK_SIZE, CHK_S_TOOL_DIGEST, CHK_S_TOOL_INCOMPLETE, CHK_LAST +}; + +/* ---- refusal codes (spec section 7) ------------------------------------- */ +enum { + PST_OK = 0, PST_BAD_MAGIC, PST_BAD_VERSION, PST_DOWNGRADE, PST_BAD_TYPE, + PST_WRONG_SIDE, PST_BAD_LENGTH, PST_TRAILING_BYTES, PST_RESERVED_NONZERO, + PST_NO_CAUSE, PST_NO_TASK, PST_NO_OBJECTIVE, PST_DIGEST_MISMATCH, + PST_BAD_EFFECT_CLASS, PST_SUBJECT_MISMATCH, PST_BAD_ORDER, PST_SECOND_FINAL, + PST_ORDINAL_GAP, PST_ORDINAL_REPEAT, PST_IDEMPOTENCE_CONFLICT, PST_UNKNOWN_TASK, + PST_CONTEXT_MISMATCH, PST_SESSION_FULL, PST_BAD_RECORDING, PST_BAD_TOOL_HEAD, + PST_TOOL_CHUNK_SIZE, PST_TOOL_DIGEST_MISMATCH, PST_TOOL_INCOMPLETE, PST_NOT_TOOL_TASK, PST_CODE_COUNT +}; +static const char *const code_names[PST_CODE_COUNT] = { + "OK", "PST_BAD_MAGIC", "PST_BAD_VERSION", "PST_DOWNGRADE", "PST_BAD_TYPE", + "PST_WRONG_SIDE", "PST_BAD_LENGTH", "PST_TRAILING_BYTES", "PST_RESERVED_NONZERO", + "PST_NO_CAUSE", "PST_NO_TASK", "PST_NO_OBJECTIVE", "PST_DIGEST_MISMATCH", + "PST_BAD_EFFECT_CLASS", "PST_SUBJECT_MISMATCH", "PST_BAD_ORDER", "PST_SECOND_FINAL", + "PST_ORDINAL_GAP", "PST_ORDINAL_REPEAT", "PST_IDEMPOTENCE_CONFLICT", "PST_UNKNOWN_TASK", + "PST_CONTEXT_MISMATCH", "PST_SESSION_FULL", "PST_BAD_RECORDING", "PST_BAD_TOOL_HEAD", + "PST_TOOL_CHUNK_SIZE", "PST_TOOL_DIGEST_MISMATCH", "PST_TOOL_INCOMPLETE", "PST_NOT_TOOL_TASK" +}; + +/* ---- SHA-256 ------------------------------------------------------------ */ +typedef struct { uint32_t h[8]; uint64_t n; uint8_t b[64]; uint32_t used; } sha256; + +static const uint32_t K256[64] = { + 0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5, + 0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174, + 0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da, + 0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967, + 0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85, + 0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070, + 0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3, + 0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2 +}; +#define ROR(x, r) (((x) >> (r)) | ((x) << (32 - (r)))) + +static void sha_block(sha256 *s, const uint8_t *p) { + uint32_t w[64], a, b, c, d, e, f, g, h; + for (int i = 0; i < 16; i++) + w[i] = (uint32_t)p[4*i] << 24 | (uint32_t)p[4*i+1] << 16 | (uint32_t)p[4*i+2] << 8 | p[4*i+3]; + for (int i = 16; i < 64; i++) { + uint32_t s0 = ROR(w[i-15], 7) ^ ROR(w[i-15], 18) ^ (w[i-15] >> 3); + uint32_t s1 = ROR(w[i-2], 17) ^ ROR(w[i-2], 19) ^ (w[i-2] >> 10); + w[i] = w[i-16] + s0 + w[i-7] + s1; + } + a = s->h[0]; b = s->h[1]; c = s->h[2]; d = s->h[3]; + e = s->h[4]; f = s->h[5]; g = s->h[6]; h = s->h[7]; + for (int i = 0; i < 64; i++) { + uint32_t t1 = h + (ROR(e, 6) ^ ROR(e, 11) ^ ROR(e, 25)) + ((e & f) ^ (~e & g)) + K256[i] + w[i]; + uint32_t t2 = (ROR(a, 2) ^ ROR(a, 13) ^ ROR(a, 22)) + ((a & b) ^ (a & c) ^ (b & c)); + h = g; g = f; f = e; e = d + t1; d = c; c = b; b = a; a = t1 + t2; + } + s->h[0] += a; s->h[1] += b; s->h[2] += c; s->h[3] += d; + s->h[4] += e; s->h[5] += f; s->h[6] += g; s->h[7] += h; +} +static void sha_init(sha256 *s) { + static const uint32_t iv[8] = { 0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a, + 0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19 }; + memcpy(s->h, iv, sizeof iv); s->n = 0; s->used = 0; +} +static void sha_update(sha256 *s, const void *data, size_t len) { + const uint8_t *p = data; + s->n += len; + while (len) { + uint32_t k = 64 - s->used; + if (k > len) k = (uint32_t)len; + memcpy(s->b + s->used, p, k); + s->used += k; p += k; len -= k; + if (s->used == 64) { sha_block(s, s->b); s->used = 0; } + } +} +static void sha_final(sha256 *s, uint8_t out[32]) { + uint64_t bits = s->n * 8; + uint8_t pad = 0x80, z = 0, l[8]; + sha_update(s, &pad, 1); + while (s->used != 56) sha_update(s, &z, 1); + for (int i = 0; i < 8; i++) l[i] = (uint8_t)(bits >> (56 - 8 * i)); + sha_update(s, l, 8); + for (int i = 0; i < 8; i++) { + out[4*i] = (uint8_t)(s->h[i] >> 24); out[4*i+1] = (uint8_t)(s->h[i] >> 16); + out[4*i+2] = (uint8_t)(s->h[i] >> 8); out[4*i+3] = (uint8_t)s->h[i]; + } +} +static void sha_once(const void *p, size_t n, uint8_t out[32]) { + sha256 s; sha_init(&s); sha_update(&s, p, n); sha_final(&s, out); +} + +/* ---- big-endian helpers -------------------------------------------------- */ +static uint16_t g16(const uint8_t *p) { return (uint16_t)(p[0] << 8 | p[1]); } +static uint32_t g32(const uint8_t *p) { return (uint32_t)p[0] << 24 | (uint32_t)p[1] << 16 | (uint32_t)p[2] << 8 | p[3]; } +static void p16(uint8_t *p, uint16_t v) { p[0] = (uint8_t)(v >> 8); p[1] = (uint8_t)v; } +static void p32(uint8_t *p, uint32_t v) { p[0] = (uint8_t)(v >> 24); p[1] = (uint8_t)(v >> 16); p[2] = (uint8_t)(v >> 8); p[3] = (uint8_t)v; } +static int all_zero(const uint8_t *p, size_t n) { while (n--) if (*p++) return 0; return 1; } + +/* ---- the format (spec section 4) ---------------------------------------- */ +#define PST_HDR 224u +#define PST_MAX_PAY 800u +#define PST_MAX_MSG 1024u +#define PST_VERSION 1u +#define PST_MAX_TYPE 16u +#define T_REQUEST 1u +#define T_TOOL_REQ 15u /* tool_call_request (spec section 11) */ +#define T_TOOL_CHUNK 16u /* tool_call_chunk */ +#define PST_TOOL_HEAD 36u /* INTERPLANE digest (32) + canonical length (4) */ +#define PST_TOOL_MAX 102400u /* 128 chunks of 800 bytes */ + +enum { + O_MAGIC = 0, O_VERSION = 4, O_TYPE = 5, O_RES0 = 6, O_CAUSE = 8, O_ORIGIN = 40, + O_OBJECTIVE = 72, O_SUBJECT = 104, O_PARENT = 136, O_TASK = 152, O_IDEM = 168, + O_ORDINAL = 184, O_EFFECT = 188, O_RES1 = 189, O_PLEN = 190, O_DIGEST = 192 +}; + +typedef struct { + uint8_t version, type; + uint8_t cause[32], origin[32], objective[32], subject[32]; + uint8_t parent[16], task[16], idem[16]; + uint32_t ordinal; + uint8_t effect; + uint16_t payload_len; + uint8_t digest[32]; + const uint8_t *payload; /* points into the decoded buffer */ +} pst_msg; + +/* Decode and check one message (spec section 4.1 check order). Reads only + * b[0..n); writes only *m. Returns PST_OK or the first refusal code. */ +static int pst_decode(const uint8_t *b, size_t n, pst_msg *m) { + size_t body; + uint8_t d[32]; + + memset(m, 0, sizeof *m); + /* 1. length bounds (the short bound is not a mutation point: it guards every read) */ + if (n < PST_HDR) return PST_BAD_LENGTH; + if (CHECK(CHK_MAX_TOTAL) && n > PST_MAX_MSG) return PST_BAD_LENGTH; + /* 2. magic */ + if (CHECK(CHK_MAGIC) && memcmp(b + O_MAGIC, "PST1", 4) != 0) return PST_BAD_MAGIC; + /* 3. version */ + if (CHECK(CHK_DOWNGRADE) && b[O_VERSION] < PST_VERSION) return PST_DOWNGRADE; + if (CHECK(CHK_VERSION) && b[O_VERSION] > PST_VERSION) return PST_BAD_VERSION; + /* 4. type */ + if (CHECK(CHK_TYPE) && (b[O_TYPE] == 0 || b[O_TYPE] > PST_MAX_TYPE)) return PST_BAD_TYPE; + /* 5. reserved */ + if (CHECK(CHK_RESERVED0) && !all_zero(b + O_RES0, 2)) return PST_RESERVED_NONZERO; + if (CHECK(CHK_RESERVED1) && b[O_RES1] != 0) return PST_RESERVED_NONZERO; + /* 6, 7. payload length against the bytes present */ + m->payload_len = g16(b + O_PLEN); + body = n - PST_HDR; + if (CHECK(CHK_PAYLOAD_SHORT) && body < m->payload_len) return PST_BAD_LENGTH; + if (CHECK(CHK_TRAILING) && body > m->payload_len) return PST_TRAILING_BYTES; + /* 8..11. field rules */ + if (CHECK(CHK_EFFECT) && b[O_EFFECT] > 2) return PST_BAD_EFFECT_CLASS; + if (CHECK(CHK_CAUSE) && all_zero(b + O_CAUSE, 32)) return PST_NO_CAUSE; + if (CHECK(CHK_TASK) && all_zero(b + O_TASK, 16)) return PST_NO_TASK; + if (CHECK(CHK_IDEM) && all_zero(b + O_IDEM, 16)) return PST_NO_TASK; + if (CHECK(CHK_OBJECTIVE) && (b[O_TYPE] == T_REQUEST || b[O_TYPE] == T_TOOL_REQ) && all_zero(b + O_OBJECTIVE, 32)) + return PST_NO_OBJECTIVE; + /* 12. payload digest (over the bytes present, so a mutant never reads past n) */ + sha_once(b + PST_HDR, body < m->payload_len ? body : m->payload_len, d); + if (CHECK(CHK_DIGEST) && memcmp(d, b + O_DIGEST, 32) != 0) return PST_DIGEST_MISMATCH; + /* 13. tool-call head (spec section 11.2): exactly 36 bytes, length 1..102400 */ + if (b[O_TYPE] == T_TOOL_REQ) { + if (CHECK(CHK_TOOL_HEAD_LEN) && m->payload_len != PST_TOOL_HEAD) return PST_BAD_TOOL_HEAD; + if (body >= PST_TOOL_HEAD && CHECK(CHK_TOOL_HEAD_BOUND)) { + uint32_t len = g32(b + PST_HDR + 32); + if (len == 0 || len > PST_TOOL_MAX) return PST_BAD_TOOL_HEAD; + } + } + + m->version = b[O_VERSION]; + m->type = b[O_TYPE]; + memcpy(m->cause, b + O_CAUSE, 32); + memcpy(m->origin, b + O_ORIGIN, 32); + memcpy(m->objective, b + O_OBJECTIVE, 32); + memcpy(m->subject, b + O_SUBJECT, 32); + memcpy(m->parent, b + O_PARENT, 16); + memcpy(m->task, b + O_TASK, 16); + memcpy(m->idem, b + O_IDEM, 16); + m->ordinal = g32(b + O_ORDINAL); + m->effect = b[O_EFFECT]; + memcpy(m->digest, b + O_DIGEST, 32); + m->payload = b + PST_HDR; + return PST_OK; +} + +/* Encode one message. Writes the fields exactly as given (the digest is not + * recomputed, so a bad digest can be encoded on purpose). Returns the byte + * count, or 0 if it does not fit in cap or the payload is over the cap. */ +static size_t pst_encode(const pst_msg *m, uint8_t *out, size_t cap) { + size_t n = PST_HDR + (size_t)m->payload_len; + if (m->payload_len > PST_MAX_PAY || n > cap) return 0; + memset(out, 0, PST_HDR); + memcpy(out + O_MAGIC, "PST1", 4); + out[O_VERSION] = m->version; + out[O_TYPE] = m->type; + memcpy(out + O_CAUSE, m->cause, 32); + memcpy(out + O_ORIGIN, m->origin, 32); + memcpy(out + O_OBJECTIVE, m->objective, 32); + memcpy(out + O_SUBJECT, m->subject, 32); + memcpy(out + O_PARENT, m->parent, 16); + memcpy(out + O_TASK, m->task, 16); + memcpy(out + O_IDEM, m->idem, 16); + p32(out + O_ORDINAL, m->ordinal); + out[O_EFFECT] = m->effect; + p16(out + O_PLEN, m->payload_len); + memcpy(out + O_DIGEST, m->digest, 32); + if (m->payload_len) memcpy(out + PST_HDR, m->payload, m->payload_len); + return n; +} + +/* ---- session rules (spec section 10) --------------------------------------- */ +#define SIDE_PI 1u +#define SIDE_SPARK 2u +#define MAX_TASKS 16u +/* ST_COLLECTING: a tool-call task whose canonical bytes are not all in yet (section 11.3). */ +enum { ST_COLLECTING = 1, ST_REQUESTED, ST_ACCEPTED, ST_QUEUED, ST_RUNNING, ST_FINAL }; + +typedef struct { + uint8_t task[16], idem[16], req_digest[32]; + uint8_t cause[32], origin[32], objective[32], parent[16], effect; + int state; + uint64_t next_ordinal[3]; /* indexed by side; [0] unused */ + uint8_t opener; /* T_REQUEST (chat) or T_TOOL_REQ (tool call) */ + uint8_t tool_digest[32]; /* from the tool-call head */ + uint32_t tool_len, tool_got; + sha256 tool_sha; /* running SHA-256 of the chunks so far */ +} task_slot; + +typedef struct { int code; unsigned long step, tasks; } session_verdict; + +static int side_of(uint8_t type) { + return type == 1 || type == 13 || type == 14 || type == T_TOOL_REQ || type == T_TOOL_CHUNK ? SIDE_PI : SIDE_SPARK; +} +static int is_opener(uint8_t type) { return type == T_REQUEST || type == T_TOOL_REQ; } + +static int same_context(const task_slot *t, const pst_msg *m) { + return memcmp(t->cause, m->cause, 32) == 0 && memcmp(t->origin, m->origin, 32) == 0 && + memcmp(t->objective, m->objective, 32) == 0 && memcmp(t->parent, m->parent, 16) == 0 && + memcmp(t->idem, m->idem, 16) == 0 && t->effect == m->effect; +} + +/* Allowed step for one task (spec section 10.2). Returns the new state, or + * 0 if the type is not allowed in state s. */ +static int next_state(int s, uint8_t type) { + switch (type) { + case 2: return s == ST_REQUESTED ? ST_ACCEPTED : 0; + case 3: return s == ST_ACCEPTED ? ST_QUEUED : 0; + case 4: return s == ST_ACCEPTED || s == ST_QUEUED ? ST_RUNNING : 0; + case 5: return s == ST_RUNNING ? ST_RUNNING : 0; + case 7: return s == ST_RUNNING ? ST_FINAL : 0; + case 8: case 9: return s != ST_FINAL ? ST_FINAL : 0; + case 13: case 14: return s; + default: return 0; /* types 6, 10, 11, 12: no session rule yet */ + } +} + +static int srefuse(session_verdict *v, int code, unsigned long step) { v->code = code; v->step = step; return code; } + +/* Check one recorded session (spec section 10.4 container). Reads only + * b[0..n); keeps its task table on the stack. Returns PST_OK or the first + * refusal code, with the 1-based step in v->step. */ +static int session_check(const uint8_t *b, size_t n, session_verdict *v) { + task_slot tasks[MAX_TASKS]; + unsigned ntasks = 0; + uint8_t subject[32]; + size_t o = 4; + unsigned long step = 0; + + memset(v, 0, sizeof *v); + memset(tasks, 0, sizeof tasks); + if (n < 4 || memcmp(b, "PSS1", 4) != 0) return srefuse(v, PST_BAD_RECORDING, 0); + while (o < n) { + pst_msg m; + task_slot *t = NULL; + unsigned side, len, i; + int code, ns, repeat = 0; + + step++; + /* the container (a guard, not a protocol rule) */ + if (n - o < 3) return srefuse(v, PST_BAD_RECORDING, step); + side = b[o]; + len = g16(b + o + 1); + if ((side != SIDE_PI && side != SIDE_SPARK) || n - o - 3 < len) return srefuse(v, PST_BAD_RECORDING, step); + /* 1. the single-message checks */ + code = pst_decode(b + o + 3, len, &m); + o += 3 + (size_t)len; + if (code != PST_OK) return srefuse(v, code, step); + /* 2. side */ + if (CHECK(CHK_S_SIDE) && side_of(m.type) != (int)side) return srefuse(v, PST_WRONG_SIDE, step); + /* 3. subject */ + if (step == 1) memcpy(subject, m.subject, 32); + else if (CHECK(CHK_S_SUBJECT) && memcmp(subject, m.subject, 32) != 0) return srefuse(v, PST_SUBJECT_MISMATCH, step); + /* 4. task */ + for (i = 0; i < ntasks; i++) + if (memcmp(tasks[i].task, m.task, 16) == 0) { t = &tasks[i]; break; } + if (is_opener(m.type) && !t) { + for (i = 0; i < ntasks; i++) + if (CHECK(CHK_S_IDEM_OTHER) && memcmp(tasks[i].idem, m.idem, 16) == 0) + return srefuse(v, PST_IDEMPOTENCE_CONFLICT, step); + if (ntasks == MAX_TASKS) return srefuse(v, PST_SESSION_FULL, step); + t = &tasks[ntasks++]; + memcpy(t->task, m.task, 16); memcpy(t->idem, m.idem, 16); memcpy(t->req_digest, m.digest, 32); + memcpy(t->cause, m.cause, 32); memcpy(t->origin, m.origin, 32); + memcpy(t->objective, m.objective, 32); memcpy(t->parent, m.parent, 16); + t->effect = m.effect; + t->opener = m.type; + t->state = ST_REQUESTED; + if (m.type == T_TOOL_REQ && m.payload_len >= PST_TOOL_HEAD) { /* section 11.3: collect the bytes first */ + memcpy(t->tool_digest, m.payload, 32); + t->tool_len = g32(m.payload + 32); + sha_init(&t->tool_sha); + t->state = ST_COLLECTING; + } + } else if (is_opener(m.type)) { + repeat = 1; + if (CHECK(CHK_S_IDEM_SAME) && (memcmp(t->idem, m.idem, 16) != 0 || memcmp(t->req_digest, m.digest, 32) != 0 || + t->opener != m.type)) + return srefuse(v, PST_IDEMPOTENCE_CONFLICT, step); + } else if (!t) { + if (CHECK(CHK_S_UNKNOWN_TASK)) return srefuse(v, PST_UNKNOWN_TASK, step); + continue; /* mutant only: ignore the message */ + } + /* 5. context; a recognised repeat of the request stops here */ + if (CHECK(CHK_S_CONTEXT) && !same_context(t, &m)) return srefuse(v, PST_CONTEXT_MISMATCH, step); + if (repeat && CHECK(CHK_S_REPEAT_REQUEST)) continue; + /* 6. ordinal, per task and side */ + if (CHECK(CHK_S_GAP) && m.ordinal > t->next_ordinal[side]) return srefuse(v, PST_ORDINAL_GAP, step); + if (CHECK(CHK_S_REPEAT) && m.ordinal < t->next_ordinal[side]) return srefuse(v, PST_ORDINAL_REPEAT, step); + t->next_ordinal[side] = (uint64_t)m.ordinal + 1; + /* 7. tool-call body (section 11.3), then order */ + if (is_opener(m.type)) continue; /* the new task is REQUESTED, or COLLECTING */ + if (m.type == T_TOOL_CHUNK && (t->opener == T_TOOL_REQ || CHECK(CHK_S_NOT_TOOL))) { + uint32_t left = t->tool_len - t->tool_got, want = left < PST_MAX_PAY ? left : PST_MAX_PAY; + uint8_t d[32]; + if (t->opener != T_TOOL_REQ) return srefuse(v, PST_NOT_TOOL_TASK, step); + if (t->state != ST_COLLECTING) { + if (CHECK(CHK_S_ORDER)) return srefuse(v, PST_BAD_ORDER, step); + continue; /* mutant only */ + } + if (CHECK(CHK_S_TOOL_CHUNK_SIZE) && m.payload_len != want) return srefuse(v, PST_TOOL_CHUNK_SIZE, step); + sha_update(&t->tool_sha, m.payload, m.payload_len); + t->tool_got += m.payload_len; + if (t->tool_got != t->tool_len) continue; /* more chunks to come */ + sha_final(&t->tool_sha, d); + if (CHECK(CHK_S_TOOL_DIGEST) && memcmp(d, t->tool_digest, 32) != 0) return srefuse(v, PST_TOOL_DIGEST_MISMATCH, step); + t->state = ST_REQUESTED; /* the whole request is in and matches its digest */ + continue; + } + if (CHECK(CHK_S_TOOL_INCOMPLETE) && t->state == ST_COLLECTING && side == SIDE_SPARK && m.type != 8 && m.type != 9) + return srefuse(v, PST_TOOL_INCOMPLETE, step); + ns = next_state(t->state, m.type); + if (!ns) { + if (CHECK(CHK_S_SECOND_FINAL) && t->state == ST_FINAL && (m.type == 7 || m.type == 8 || m.type == 9)) + return srefuse(v, PST_SECOND_FINAL, step); + if (CHECK(CHK_S_ORDER)) return srefuse(v, PST_BAD_ORDER, step); + continue; /* mutant only: keep the state */ + } + t->state = ns; + } + v->step = step; + v->tasks = ntasks; + return v->code = PST_OK; +} + +/* ---- verdict line ---------------------------------------------------------- */ +static char *hexw(char *o, const uint8_t *p, size_t n) { + static const char hx[] = "0123456789abcdef"; + for (size_t i = 0; i < n; i++) { *o++ = hx[p[i] >> 4]; *o++ = hx[p[i] & 15]; } + *o = 0; + return o; +} +static void verdict_line(int code, const pst_msg *m, char *buf, size_t cap) { + char c[65], o[65], ob[65], s[65], pa[33], t[33], k[33], d[65]; + if (code != PST_OK) { + snprintf(buf, cap, "refuse %s", code > 0 && code < PST_CODE_COUNT ? code_names[code] : "PST_UNKNOWN_CODE"); + return; + } + hexw(c, m->cause, 32); hexw(o, m->origin, 32); hexw(ob, m->objective, 32); hexw(s, m->subject, 32); + hexw(pa, m->parent, 16); hexw(t, m->task, 16); hexw(k, m->idem, 16); hexw(d, m->digest, 32); + snprintf(buf, cap, "ok type=%u version=%u cause=%s origin=%s objective=%s subject=%s parent=%s task=%s idem=%s ordinal=%lu effect=%u len=%u digest=%s", + m->type, m->version, c, o, ob, s, pa, t, k, (unsigned long)m->ordinal, m->effect, m->payload_len, d); +} +static void session_line(const session_verdict *v, char *buf, size_t cap) { + if (v->code == PST_OK) snprintf(buf, cap, "ok steps=%lu tasks=%lu", v->step, v->tasks); + else snprintf(buf, cap, "refuse %s step=%lu", v->code > 0 && v->code < PST_CODE_COUNT ? code_names[v->code] : "PST_UNKNOWN_CODE", v->step); +} + +/* ---- file I/O (outside the decoder) --------------------------------------- */ +#define FILE_CAP 65536u +static uint8_t file_buf[FILE_CAP]; + +/* Reads the whole file into file_buf. Returns 0, or -1 on I/O error or a + * file larger than FILE_CAP (no vector is that large). */ +static int slurp(const char *path, size_t *n) { + FILE *f = fopen(path, "rb"); + size_t k; + if (!f) return -1; + k = fread(file_buf, 1, FILE_CAP, f); + if (k == FILE_CAP && fgetc(f) != EOF) { fclose(f); return -1; } + fclose(f); + *n = k; + return 0; +} + +static int check_file(const char *path, char *line, size_t cap, int *roundtrip_ok) { + static uint8_t again[PST_MAX_MSG]; + pst_msg m; + size_t n, k; + int code; + if (slurp(path, &n)) { fprintf(stderr, "cannot read %s\n", path); return -1; } + code = pst_decode(file_buf, n, &m); + verdict_line(code, &m, line, cap); + *roundtrip_ok = 1; + if (code == PST_OK) { + k = pst_encode(&m, again, sizeof again); + *roundtrip_ok = k == n && memcmp(again, file_buf, n) == 0; + } + return code; +} + +static void rstrip(char *s) { size_t n = strlen(s); while (n && (s[n-1] == '\n' || s[n-1] == '\r')) s[--n] = 0; } + +static int corpus(const char *dir) { + char path[4096], line[1024], got[1024]; + unsigned pass = 0, fail = 0; + FILE *f; + + snprintf(path, sizeof path, "%s/expected.txt", dir); + if (!(f = fopen(path, "r"))) { fprintf(stderr, "cannot read %s\n", path); return 2; } + while (fgets(line, sizeof line, f)) { + char *sp; + int rt; + rstrip(line); + if (!line[0] || line[0] == '#') continue; + if (!(sp = strchr(line, ' '))) { fprintf(stderr, "bad line: %s\n", line); fail++; continue; } + *sp = 0; + snprintf(path, sizeof path, "%s/%s", dir, line); + if (check_file(path, got, sizeof got, &rt) < 0) { fail++; continue; } + if (strcmp(got, sp + 1) != 0) { fail++; printf("MISMATCH %s\n expected: %s\n got: %s\n", line, sp + 1, got); } + else if (!rt) { fail++; printf("ROUNDTRIP_MISMATCH %s\n", line); } + else pass++; + } + fclose(f); + + /* recorded sessions (spec section 10), when the directory has them */ + snprintf(path, sizeof path, "%s/sessions/expected.txt", dir); + if ((f = fopen(path, "r"))) { + while (fgets(line, sizeof line, f)) { + char *sp; + size_t n; + session_verdict v; + rstrip(line); + if (!line[0] || line[0] == '#') continue; + if (!(sp = strchr(line, ' '))) { fprintf(stderr, "bad line: %s\n", line); fail++; continue; } + *sp = 0; + snprintf(path, sizeof path, "%s/sessions/%s", dir, line); + if (slurp(path, &n)) { fprintf(stderr, "cannot read %s\n", path); fail++; continue; } + session_check(file_buf, n, &v); + session_line(&v, got, sizeof got); + if (strcmp(got, sp + 1) != 0) { fail++; printf("MISMATCH sessions/%s\n expected: %s\n got: %s\n", line, sp + 1, got); } + else pass++; + } + fclose(f); + } + printf("PST1_CONFORMANCE impl=c pass=%u fail=%u\n", pass, fail); + return fail || !pass ? 1 : 0; +} + +/* ---- seeded random sessions (reorder, drop, duplicate) -------------------- */ +#define FUZZ_FILES 8u +#define FUZZ_RECS 64u +static uint8_t fuzz_src[FUZZ_FILES][8192]; +static size_t fuzz_len[FUZZ_FILES]; +static uint8_t fuzz_out[8192 + PST_MAX_MSG + 3]; + +static uint64_t splitmix(uint64_t *s) { + uint64_t z = (*s += 0x9E3779B97F4A7C15ull); + z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull; + z = (z ^ (z >> 27)) * 0x94D049BB133111EBull; + return z ^ (z >> 31); +} + +/* Record boundaries of a well-formed recording; returns the count. */ +static unsigned records(const uint8_t *b, size_t n, size_t *off, size_t *len) { + size_t o = 4; + unsigned k = 0; + while (o + 3 <= n && k < FUZZ_RECS) { + size_t l = 3 + (size_t)g16(b + o + 1); + if (l > n - o) break; + off[k] = o; len[k] = l; k++; + o += l; + } + return k; +} + +static int session_fuzz(uint64_t seed, unsigned long count, int nfiles, char **files) { + static const char *const ops[3] = { "reorder", "drop", "duplicate" }; + unsigned long by_op[3] = { 0, 0, 0 }, ok = 0, refused = 0, i; + uint64_t rng = seed; + sha256 all; + uint8_t d[32]; + char hx[65], line[128]; + + if (nfiles < 1 || nfiles > (int)FUZZ_FILES) { fprintf(stderr, "need 1 to %u files\n", FUZZ_FILES); return 2; } + for (int k = 0; k < nfiles; k++) { + size_t n; + if (slurp(files[k], &n) || n > sizeof fuzz_src[k]) { fprintf(stderr, "cannot read %s\n", files[k]); return 2; } + memcpy(fuzz_src[k], file_buf, n); + fuzz_len[k] = n; + } + sha_init(&all); + for (i = 0; i < count; i++) { + size_t off[FUZZ_RECS], len[FUZZ_RECS], o = 4; + unsigned f = (unsigned)(splitmix(&rng) % (uint64_t)nfiles), nr, op, a, b2, r; + const uint8_t *src = fuzz_src[f]; + session_verdict v; + + nr = records(src, fuzz_len[f], off, len); + if (nr < 2) { fprintf(stderr, "%s: fewer than 2 records\n", files[f]); return 2; } + op = (unsigned)(splitmix(&rng) % 3); + a = (unsigned)(splitmix(&rng) % nr); + b2 = (unsigned)(splitmix(&rng) % (nr - 1)); + if (b2 >= a) b2++; /* b2 != a */ + memcpy(fuzz_out, "PSS1", 4); + for (r = 0; r < nr; r++) { + unsigned take = r; + if (op == 0) take = r == a ? b2 : r == b2 ? a : r; /* swap a and b2 */ + if (op == 1 && r == a) continue; /* drop a */ + memcpy(fuzz_out + o, src + off[take], len[take]); o += len[take]; + if (op == 2 && r == b2) { memcpy(fuzz_out + o, src + off[a], len[a]); o += len[a]; } /* copy of a after b2 */ + } + session_check(fuzz_out, o, &v); + session_line(&v, line, sizeof line); + if (v.code == PST_OK) ok++; else refused++; + by_op[op]++; + sha_update(&all, line, strlen(line)); + sha_update(&all, "\n", 1); + } + sha_final(&all, d); + hexw(hx, d, 32); + printf("PST1_SESSION_FUZZ seed=%llu count=%lu %s=%lu %s=%lu %s=%lu ok=%lu refused=%lu verdicts=%s\n", + (unsigned long long)seed, count, ops[0], by_op[0], ops[1], by_op[1], ops[2], by_op[2], ok, refused, hx); + return 0; +} + +/* ---- vector generator ------------------------------------------------------ */ +/* Every vector starts from one well-formed message and changes one thing. The + * expected line for an accepted vector is built from the generator's own + * struct, not from pst_decode, so the decoder is checked against the intent. */ +static uint8_t gen_payload[PST_MAX_PAY + 8]; + +static void fill(uint8_t *p, size_t n, uint8_t seed) { for (size_t i = 0; i < n; i++) p[i] = (uint8_t)(seed + 7 * i); } + +static void base(pst_msg *m, uint8_t type, const char *text) { + size_t len = strlen(text); + memset(m, 0, sizeof *m); + m->version = PST_VERSION; + m->type = type; + fill(m->cause, 32, 0xC1); + fill(m->origin, 32, 0x0A); + fill(m->objective, 32, 0x0B); + fill(m->subject, 32, 0x5B); + fill(m->task, 16, 0x7A); + fill(m->idem, 16, 0x1D); + m->ordinal = type == T_REQUEST ? 0 : 1; + m->effect = 1; + memcpy(gen_payload, text, len); + m->payload = gen_payload; + m->payload_len = (uint16_t)len; + sha_once(gen_payload, len, m->digest); +} + +static FILE *gen_expected; +static int gen_fail; + +static void emit(const char *dir, const char *name, const uint8_t *b, size_t n, const char *expect) { + char path[4096]; + FILE *f; + snprintf(path, sizeof path, "%s/%s", dir, name); + if (!(f = fopen(path, "wb")) || fwrite(b, 1, n, f) != n || fclose(f) != 0) { + fprintf(stderr, "cannot write %s\n", path); + gen_fail = 1; + return; + } + fprintf(gen_expected, "%s %s\n", name, expect); +} + +static void emit_ok(const char *dir, const char *name, const pst_msg *m) { + static uint8_t out[PST_MAX_MSG]; + char line[1024]; + size_t n = pst_encode(m, out, sizeof out); + verdict_line(PST_OK, m, line, sizeof line); + emit(dir, name, out, n, line); +} + +static void emit_bad(const char *dir, const char *name, const pst_msg *m, int at, int value, long extra, const char *code) { + static uint8_t out[PST_MAX_MSG + 64]; + char line[128]; + size_t n = pst_encode(m, out, sizeof out); + if (at >= 0) out[at] = (uint8_t)value; + if (extra < 0) n -= (size_t)(-extra); /* drop bytes from the end */ + else for (long i = 0; i < extra; i++) out[n++] = (uint8_t)(0xE0 + i); + snprintf(line, sizeof line, "refuse %s", code); + emit(dir, name, out, n, line); +} + +/* ---- tool-call vectors (spec section 11) ---------------------------------- */ +/* The one INTERPLANE canonical tool request the vectors carry: RFC 8785 bytes + * written by interplane-core canonicalize() at aien-dev/interplane-mv commit + * 83df0f074b2c572473cd535c89f767df48933f4a, using + * tools/interplane-request (1743 bytes, so three chunks: 800, 800, 143). + * INTERPLANE digest: + * sha256:78dbef7ee689b20ad9ae530fd7fa8417fb671778667b27f910484156776990d6 */ +static const char IPR_REQ[] = + "{\"arguments\":{\"currency_hint\":\"\302\243\",\"fields\":[\"merchant\",\"date\",\"total" + "\",\"items\"],\"instructions\":\"Find every receipt from the last week that mentions the " + "garden hose, the rain barrel or the drip line. Summarise each one in a single plain sente" + "nce: what was bought, where, and for how much. Leave out card numbers and addresses. If t" + "wo receipts look like the same purchase, say so instead of counting it twice.\\nFind ever" + "y receipt from the last week that mentions the garden hose, the rain barrel or the drip l" + "ine. Summarise each one in a single plain sentence: what was bought, where, and for how m" + "uch. Leave out card numbers and addresses. If two receipts look like the same purchase, s" + "ay so instead of counting it twice.\\nFind every receipt from the last week that mentions" + " the garden hose, the rain barrel or the drip line. Summarise each one in a single plain " + "sentence: what was bought, where, and for how much. Leave out card numbers and addresses." + " If two receipts look like the same purchase, say so instead of counting it twice.\\nFind" + " every receipt from the last week that mentions the garden hose, the rain barrel or the d" + "rip line. Summarise each one in a single plain sentence: what was bought, where, and for " + "how much. Leave out card numbers and addresses. If two receipts look like the same purcha" + "se, say so instead of counting it twice.\\n\",\"limit\":25,\"locale\":\"en-GB\",\"note\":" + "\"caf\303\251 \342\230\225 \360\237\214\247\",\"query\":\"garden hose OR rain barrel OR d" + "rip line\",\"redact\":[\"card_number\",\"address\"],\"since_days\":7},\"kind\":\"tool_req" + "uest\",\"provenance\":{\"dialect\":\"openai\",\"model\":\"pi-local-router\",\"parser_vers" + "ion\":\"1.0.0\",\"source_call_id\":\"call_pst1_c6\",\"source_turn\":7},\"request_id\":\"p" + "st1-c6-vector-1\",\"tool\":{\"name\":\"search\",\"namespace\":\"aien.receipts\"}}"; +static const char IPR_DIGEST_HEX[] = "78dbef7ee689b20ad9ae530fd7fa8417fb671778667b27f910484156776990d6"; +#define IPR_LEN (sizeof IPR_REQ - 1) + +/* Writes a file that has no expected.txt line (the carried request itself). */ +static void emit_raw(const char *dir, const char *name, const uint8_t *b, size_t n) { + char path[4096]; + FILE *f; + snprintf(path, sizeof path, "%s/%s", dir, name); + if (!(f = fopen(path, "wb")) || fwrite(b, 1, n, f) != n || fclose(f) != 0) { + fprintf(stderr, "cannot write %s\n", path); + gen_fail = 1; + } +} + +/* Sets m's payload to p[0..n) (copied into gen_payload) and its digest. */ +static void set_payload(pst_msg *m, const uint8_t *p, size_t n) { + memmove(gen_payload, p, n); + m->payload = gen_payload; + m->payload_len = (uint16_t)n; + sha_once(gen_payload, n, m->digest); +} + +/* A tool-call head: the INTERPLANE digest, the canonical length, then `extra` + * further bytes (only for refusal vectors). */ +static void set_tool_head(pst_msg *m, const uint8_t digest[32], uint32_t len, size_t extra) { + uint8_t h[PST_TOOL_HEAD + 8]; + memcpy(h, digest, 32); + p32(h + 32, len); + for (size_t i = 0; i < extra; i++) h[PST_TOOL_HEAD + i] = (uint8_t)(0x03 + i); + set_payload(m, h, PST_TOOL_HEAD + extra); +} + +static uint8_t ipr_digest[32]; + +/* Computes the INTERPLANE digest of IPR_REQ and checks it against the pinned + * value, so the embedded bytes cannot drift from what interplane-core wrote. */ +static int ipr_init(void) { + char hx[65]; + sha_once(IPR_REQ, IPR_LEN, ipr_digest); + hexw(hx, ipr_digest, 32); + if (strcmp(hx, IPR_DIGEST_HEX) != 0) { fprintf(stderr, "embedded INTERPLANE request digest drifted\n"); return -1; } + return 0; +} + +/* ---- recorded-session generator (spec section 10.4) ---------------------- */ +static uint8_t sess[16384]; +static size_t sess_n; + +static void s_begin(void) { memcpy(sess, "PSS1", 4); sess_n = 4; } + +/* One message of task number tn (task id and idempotence key derive from tn). */ +static void mk(pst_msg *m, uint8_t type, unsigned tn, uint32_t ordinal, const char *text) { + base(m, type, text); + fill(m->task, 16, (uint8_t)(0x7A + 16 * tn)); + fill(m->idem, 16, (uint8_t)(0x1D + 16 * tn)); + m->task[15] ^= (uint8_t)tn; /* keeps task 16 apart from task 0 */ + m->idem[15] ^= (uint8_t)tn; + m->ordinal = ordinal; +} + +static void s_add(unsigned side, const pst_msg *m) { + size_t n = pst_encode(m, sess + sess_n + 3, sizeof sess - sess_n - 3); + if (!n) { gen_fail = 1; return; } + sess[sess_n] = (uint8_t)side; + p16(sess + sess_n + 1, (uint16_t)n); + sess_n += 3 + n; +} + +/* Shorthand: build and add one message. */ +static void s_msg(unsigned side, uint8_t type, unsigned tn, uint32_t ordinal, const char *text) { + pst_msg m; + mk(&m, type, tn, ordinal, text); + s_add(side, &m); +} + +static void s_emit(const char *dir, const char *name, const char *expect) { + char sub[4096]; + snprintf(sub, sizeof sub, "%s/sessions", dir); + emit(sub, name, sess, sess_n, expect); +} + +#define PI SIDE_PI +#define SP SIDE_SPARK +static const char RESULT32[] = "result digest stand-in: 32 bytes"; /* 32 bytes of payload */ + +/* request, accepted, running: the opening of a normal task (Spark ordinals 0, 1). */ +static void s_open(unsigned tn) { + s_msg(PI, 1, tn, 0, "Write a short poem about rain."); + s_msg(SP, 2, tn, 0, ""); + s_msg(SP, 4, tn, 1, ""); +} + +/* Tool-call task tn: the head (ordinal 0), then chunks carrying canonical bytes. */ +static void s_tool_open(unsigned tn, const uint8_t digest[32]) { + pst_msg m; + mk(&m, T_TOOL_REQ, tn, 0, ""); + set_tool_head(&m, digest, (uint32_t)IPR_LEN, 0); + s_add(SIDE_PI, &m); +} +static void s_tool_chunk(unsigned tn, uint32_t ordinal, const uint8_t *p, size_t n) { + pst_msg m; + mk(&m, T_TOOL_CHUNK, tn, ordinal, ""); + set_payload(&m, p, n); + s_add(SIDE_PI, &m); +} +/* All of p[0..n) in 800-byte chunks, ordinals 1, 2, ... */ +static void s_tool_chunks(unsigned tn, const uint8_t *p, size_t n) { + uint32_t ord = 1; + for (size_t at = 0; at < n; at += PST_MAX_PAY, ord++) + s_tool_chunk(tn, ord, p + at, n - at < PST_MAX_PAY ? n - at : PST_MAX_PAY); +} + +static int make_sessions(const char *dir) { + char path[4096]; + pst_msg m; + snprintf(path, sizeof path, "%s/sessions/expected.txt", dir); + if (!(gen_expected = fopen(path, "w"))) { fprintf(stderr, "cannot write %s\n", path); return 2; } + fprintf(gen_expected, + "# PST1 recorded sessions. Spec: ../../SPEC.md section 10 (rules) and 10.4 (container).\n" + "# Line: ok steps=N tasks=T | refuse step=N (1-based message position)\n" + "# Generated by tools/pst_verify.c --make-vectors; do not edit by hand.\n"); + + /* accepted sessions */ + s_begin(); s_open(0); + s_msg(SP, 5, 0, 2, "Rain on the "); s_msg(SP, 5, 0, 3, "tin roof, "); s_msg(SP, 5, 0, 4, "soft and steady."); + s_msg(SP, 7, 0, 5, RESULT32); + s_emit(dir, "ok-normal-life.pss", "ok steps=7 tasks=1"); + + s_begin(); + s_msg(PI, 1, 0, 0, "Index the new receipts."); + s_msg(PI, 1, 1, 0, "Rebuild the map."); + s_msg(SP, 2, 0, 0, ""); + s_msg(SP, 8, 1, 0, "busy"); + s_msg(SP, 3, 0, 1, ""); + s_msg(PI, 13, 0, 1, ""); + s_msg(SP, 9, 0, 2, ""); + s_msg(PI, 14, 0, 2, ""); + s_emit(dir, "ok-two-tasks-queued-cancelled.pss", "ok steps=8 tasks=2"); + + s_begin(); + s_msg(PI, 1, 0, 0, "Write a short poem about rain."); + s_msg(SP, 2, 0, 0, ""); + s_msg(PI, 1, 0, 0, "Write a short poem about rain."); /* the Pi sends the same request again */ + s_msg(SP, 4, 0, 1, ""); + s_msg(SP, 7, 0, 2, RESULT32); + s_emit(dir, "ok-repeated-request.pss", "ok steps=5 tasks=1"); + + /* refused sessions: the six of the frozen first cut, then the other rules */ + s_begin(); + s_msg(PI, 1, 0, 0, "Write a short poem about rain."); + s_msg(SP, 7, 0, 0, RESULT32); + s_emit(dir, "bad-completed-before-accepted.pss", "refuse PST_BAD_ORDER step=2"); + + s_begin(); s_open(0); + s_msg(SP, 7, 0, 2, RESULT32); s_msg(SP, 8, 0, 3, "late failure"); + s_emit(dir, "bad-second-final.pss", "refuse PST_SECOND_FINAL step=5"); + + s_begin(); s_open(0); + s_msg(SP, 5, 0, 2, "Rain on the "); s_msg(SP, 5, 0, 4, "soft and steady."); + s_emit(dir, "bad-chunk-skipped.pss", "refuse PST_ORDINAL_GAP step=5"); + + s_begin(); s_open(0); + s_msg(SP, 5, 0, 2, "Rain on the "); s_msg(SP, 5, 0, 2, "Rain on the "); + s_emit(dir, "bad-chunk-repeated.pss", "refuse PST_ORDINAL_REPEAT step=5"); + + s_begin(); + s_msg(PI, 1, 0, 0, "Write a short poem about rain."); + mk(&m, 2, 0, 0, ""); m.subject[0] ^= 0xFF; s_add(SP, &m); + s_emit(dir, "bad-subject-change.pss", "refuse PST_SUBJECT_MISMATCH step=2"); + + s_begin(); + s_msg(PI, 1, 0, 0, "Write a short poem about rain."); + s_msg(SP, 2, 0, 0, ""); + s_msg(PI, 1, 0, 0, "Write a long poem about snow."); /* same task and key, other payload */ + s_emit(dir, "bad-idempotence-key-other-digest.pss", "refuse PST_IDEMPOTENCE_CONFLICT step=3"); + + s_begin(); + s_msg(PI, 1, 0, 0, "Write a short poem about rain."); + mk(&m, 1, 1, 0, "Write a short poem about rain."); fill(m.idem, 16, 0x1D); s_add(PI, &m); /* task 1, key of task 0 */ + s_emit(dir, "bad-idempotence-key-other-task.pss", "refuse PST_IDEMPOTENCE_CONFLICT step=2"); + + s_begin(); s_open(0); + s_msg(PI, 7, 0, 1, RESULT32); + s_emit(dir, "bad-completed-by-pi.pss", "refuse PST_WRONG_SIDE step=4"); + + s_begin(); s_open(0); + s_msg(PI, 6, 0, 1, RESULT32); + s_emit(dir, "bad-approval-by-pi.pss", "refuse PST_WRONG_SIDE step=4"); + + s_begin(); + s_msg(PI, 1, 0, 0, "Write a short poem about rain."); + s_msg(SP, 2, 0, 0, ""); + s_msg(PI, 14, 1, 0, ""); + s_emit(dir, "bad-resume-unknown-task.pss", "refuse PST_UNKNOWN_TASK step=3"); + + s_begin(); + s_msg(PI, 1, 0, 0, "Write a short poem about rain."); + s_msg(SP, 2, 0, 0, ""); + mk(&m, 4, 0, 1, ""); m.cause[5] ^= 0x01; s_add(SP, &m); + s_emit(dir, "bad-context-change.pss", "refuse PST_CONTEXT_MISMATCH step=3"); + + s_begin(); s_open(0); + s_msg(SP, 7, 0, 2, RESULT32); s_msg(SP, 5, 0, 3, "one more line"); + s_emit(dir, "bad-chunk-after-final.pss", "refuse PST_BAD_ORDER step=5"); + + s_begin(); s_open(0); + s_msg(SP, 6, 0, 2, RESULT32); + s_emit(dir, "bad-approval-rule-not-yet-defined.pss", "refuse PST_BAD_ORDER step=4"); + + s_begin(); + s_msg(PI, 1, 0, 0, "Write a short poem about rain."); + mk(&m, 2, 0, 0, ""); s_add(SP, &m); + sess[sess_n - (PST_HDR - O_MAGIC)] = 'X'; /* break the magic of the accepted message */ + s_emit(dir, "bad-message-in-session.pss", "refuse PST_BAD_MAGIC step=2"); + + s_begin(); + for (unsigned tn = 0; tn <= MAX_TASKS; tn++) s_msg(PI, 1, tn, 0, "Count to three."); + s_emit(dir, "bad-session-full.pss", "refuse PST_SESSION_FULL step=17"); + + s_begin(); + s_msg(PI, 1, 0, 0, "Write a short poem about rain."); + sess[sess_n++] = 3; /* a side byte that is neither Pi nor Spark */ + sess[sess_n++] = 0; sess[sess_n++] = 0; + s_emit(dir, "bad-recording.pss", "refuse PST_BAD_RECORDING step=2"); + + /* tool-call tasks (spec section 11): one canonical INTERPLANE request in three chunks */ + { + static uint8_t buf[IPR_LEN + 8]; + uint8_t dg[32]; + + s_begin(); + s_tool_open(0, ipr_digest); s_tool_chunks(0, (const uint8_t *)IPR_REQ, IPR_LEN); + s_msg(SP, 2, 0, 0, ""); s_msg(SP, 4, 0, 1, ""); s_msg(SP, 7, 0, 2, RESULT32); + s_emit(dir, "ok-tool-call.pss", "ok steps=7 tasks=1"); + + s_begin(); + s_tool_open(0, ipr_digest); s_tool_chunk(0, 1, (const uint8_t *)IPR_REQ, PST_MAX_PAY); + s_msg(SP, 8, 0, 0, "tool request incomplete"); /* the Spark may end it unread */ + s_emit(dir, "ok-tool-call-failed-while-collecting.pss", "ok steps=3 tasks=1"); + + memcpy(dg, ipr_digest, 32); dg[0] ^= 0x01; + s_begin(); + s_tool_open(0, dg); s_tool_chunks(0, (const uint8_t *)IPR_REQ, IPR_LEN); + s_emit(dir, "bad-tool-digest-mismatch.pss", "refuse PST_TOOL_DIGEST_MISMATCH step=4"); + + memcpy(buf, IPR_REQ, IPR_LEN); buf[1000] ^= 0x20; /* one byte in the second chunk */ + s_begin(); + s_tool_open(0, ipr_digest); s_tool_chunks(0, buf, IPR_LEN); + s_emit(dir, "bad-tool-altered-byte.pss", "refuse PST_TOOL_DIGEST_MISMATCH step=4"); + + memcpy(buf, IPR_REQ, IPR_LEN); buf[IPR_LEN] = ' '; /* one byte past the canonical end */ + s_begin(); + s_tool_open(0, ipr_digest); + s_tool_chunk(0, 1, buf, PST_MAX_PAY); s_tool_chunk(0, 2, buf + PST_MAX_PAY, PST_MAX_PAY); + s_tool_chunk(0, 3, buf + 2 * PST_MAX_PAY, IPR_LEN - 2 * PST_MAX_PAY + 1); + s_emit(dir, "bad-tool-extra-bytes.pss", "refuse PST_TOOL_CHUNK_SIZE step=4"); + + s_begin(); + s_tool_open(0, ipr_digest); s_tool_chunk(0, 1, (const uint8_t *)IPR_REQ, PST_MAX_PAY - 1); + s_emit(dir, "bad-tool-short-chunk.pss", "refuse PST_TOOL_CHUNK_SIZE step=2"); + + s_begin(); + s_tool_open(0, ipr_digest); s_tool_chunks(0, (const uint8_t *)IPR_REQ, IPR_LEN); + s_tool_chunk(0, 4, (const uint8_t *)" ", 1); /* nothing may follow the last chunk */ + s_emit(dir, "bad-tool-chunk-after-complete.pss", "refuse PST_BAD_ORDER step=5"); + + s_begin(); + s_tool_open(0, ipr_digest); + s_tool_chunk(0, 1, (const uint8_t *)IPR_REQ, PST_MAX_PAY); + s_tool_chunk(0, 2, (const uint8_t *)IPR_REQ + PST_MAX_PAY, PST_MAX_PAY); + s_msg(SP, 2, 0, 0, ""); /* accepted with the last 143 bytes missing */ + s_emit(dir, "bad-tool-truncated.pss", "refuse PST_TOOL_INCOMPLETE step=4"); + + s_begin(); + s_msg(PI, 1, 0, 0, "Search my receipts for the garden hose."); + s_tool_chunk(0, 1, (const uint8_t *)IPR_REQ, PST_MAX_PAY); + s_emit(dir, "bad-tool-payload-in-chat-task.pss", "refuse PST_NOT_TOOL_TASK step=2"); + } + + if (fclose(gen_expected) != 0) gen_fail = 1; + return gen_fail ? 2 : 0; +} + +static int make_vectors(const char *dir) { + char path[4096]; + pst_msg m; + if (ipr_init()) return 2; + snprintf(path, sizeof path, "%s/expected.txt", dir); + if (!(gen_expected = fopen(path, "w"))) { fprintf(stderr, "cannot write %s\n", path); return 2; } + fprintf(gen_expected, + "# PST1 single-message vectors. Spec: ../SPEC.md (wire version 1), sections 4 and 7.\n" + "# Line: , verdict line as printed by tools/pst_verify.c:\n" + "# ok type=T version=V cause=H64 origin=H64 objective=H64 subject=H64 parent=H32\n" + "# task=H32 idem=H32 ordinal=N effect=E len=L digest=H64 (one line)\n" + "# refuse \n" + "# Generated by tools/pst_verify.c --make-vectors; do not edit by hand.\n"); + + /* accepted */ + base(&m, 1, "Summarise the last three receipts in plain words."); + emit_ok(dir, "ok-request.pst", &m); + base(&m, 2, ""); + emit_ok(dir, "ok-accepted-empty.pst", &m); + base(&m, 5, ""); + memset(gen_payload, 'x', PST_MAX_PAY); + m.payload_len = PST_MAX_PAY; m.ordinal = 7; m.effect = 0; + fill(m.parent, 16, 0x9E); + sha_once(gen_payload, PST_MAX_PAY, m.digest); + emit_ok(dir, "ok-text-chunk-1024.pst", &m); + base(&m, 14, ""); + m.effect = 2; m.ordinal = 0xFFFFFFFFu; + emit_ok(dir, "ok-resume-request-max-ordinal.pst", &m); + + /* refused: one rule each, in check order */ + base(&m, 1, "hello"); + emit_bad(dir, "bad-length-short-header.pst", &m, -1, 0, -(long)(5 + 1), "PST_BAD_LENGTH"); + emit_bad(dir, "bad-length-empty-file.pst", &m, -1, 0, -(long)(5 + PST_HDR), "PST_BAD_LENGTH"); + base(&m, 5, ""); + memset(gen_payload, 'y', PST_MAX_PAY); + m.payload_len = PST_MAX_PAY; + sha_once(gen_payload, PST_MAX_PAY, m.digest); + emit_bad(dir, "bad-length-over-1024.pst", &m, -1, 0, 1, "PST_BAD_LENGTH"); + base(&m, 1, "hello"); + emit_bad(dir, "bad-magic.pst", &m, O_MAGIC + 3, '2', 0, "PST_BAD_MAGIC"); + emit_bad(dir, "bad-version-unknown.pst", &m, O_VERSION, 2, 0, "PST_BAD_VERSION"); + emit_bad(dir, "bad-version-downgrade.pst", &m, O_VERSION, 0, 0, "PST_DOWNGRADE"); + emit_bad(dir, "bad-type-zero.pst", &m, O_TYPE, 0, 0, "PST_BAD_TYPE"); + emit_bad(dir, "bad-type-unknown.pst", &m, O_TYPE, 0xFF, 0, "PST_BAD_TYPE"); + emit_bad(dir, "bad-reserved0.pst", &m, O_RES0 + 1, 1, 0, "PST_RESERVED_NONZERO"); + emit_bad(dir, "bad-reserved1.pst", &m, O_RES1, 0x80, 0, "PST_RESERVED_NONZERO"); + emit_bad(dir, "bad-length-mismatch.pst", &m, -1, 0, -2, "PST_BAD_LENGTH"); + emit_bad(dir, "bad-payload-len-over-800.pst", &m, O_PLEN, 0x04, 0, "PST_BAD_LENGTH"); + emit_bad(dir, "bad-trailing-byte.pst", &m, -1, 0, 1, "PST_TRAILING_BYTES"); + emit_bad(dir, "bad-effect-class.pst", &m, O_EFFECT, 3, 0, "PST_BAD_EFFECT_CLASS"); + memset(m.cause, 0, 32); + emit_bad(dir, "bad-no-cause.pst", &m, -1, 0, 0, "PST_NO_CAUSE"); + base(&m, 1, "hello"); + memset(m.task, 0, 16); + emit_bad(dir, "bad-no-task-id.pst", &m, -1, 0, 0, "PST_NO_TASK"); + base(&m, 1, "hello"); + memset(m.idem, 0, 16); + emit_bad(dir, "bad-no-idempotence-key.pst", &m, -1, 0, 0, "PST_NO_TASK"); + base(&m, 1, "hello"); + memset(m.objective, 0, 32); + emit_bad(dir, "bad-request-no-objective.pst", &m, -1, 0, 0, "PST_NO_OBJECTIVE"); + base(&m, 1, "hello"); + m.digest[31] ^= 1; + emit_bad(dir, "bad-digest.pst", &m, -1, 0, 0, "PST_DIGEST_MISMATCH"); + + /* tool-call messages (spec section 11): the head, one chunk, and the head refusals */ + emit_raw(dir, "interplane-tool-request.json", (const uint8_t *)IPR_REQ, IPR_LEN); + base(&m, T_TOOL_REQ, ""); + set_tool_head(&m, ipr_digest, (uint32_t)IPR_LEN, 0); + emit_ok(dir, "ok-tool-call-request.pst", &m); + base(&m, T_TOOL_CHUNK, ""); + set_payload(&m, (const uint8_t *)IPR_REQ, PST_MAX_PAY); + emit_ok(dir, "ok-tool-call-chunk.pst", &m); + base(&m, T_TOOL_REQ, ""); + set_tool_head(&m, ipr_digest, (uint32_t)IPR_LEN, 4); /* a fifth field, e.g. a chunk count */ + emit_bad(dir, "bad-tool-head-extra-field.pst", &m, -1, 0, 0, "PST_BAD_TOOL_HEAD"); + base(&m, T_TOOL_REQ, ""); + set_payload(&m, ipr_digest, 32); /* the digest without the length */ + emit_bad(dir, "bad-tool-head-short.pst", &m, -1, 0, 0, "PST_BAD_TOOL_HEAD"); + base(&m, T_TOOL_REQ, ""); + set_tool_head(&m, ipr_digest, 0, 0); + emit_bad(dir, "bad-tool-head-zero-length.pst", &m, -1, 0, 0, "PST_BAD_TOOL_HEAD"); + base(&m, T_TOOL_REQ, ""); + set_tool_head(&m, ipr_digest, PST_TOOL_MAX + 1, 0); + emit_bad(dir, "bad-tool-head-over-limit.pst", &m, -1, 0, 0, "PST_BAD_TOOL_HEAD"); + base(&m, T_TOOL_REQ, ""); + set_tool_head(&m, ipr_digest, (uint32_t)IPR_LEN, 0); + memset(m.objective, 0, 32); + emit_bad(dir, "bad-tool-request-no-objective.pst", &m, -1, 0, 0, "PST_NO_OBJECTIVE"); + + if (fclose(gen_expected) != 0) gen_fail = 1; + return gen_fail ? 2 : make_sessions(dir); +} + +int main(int argc, char **argv) { + char out[1024]; + int rt; + if (argc == 2 && argv[1][0] != '-') { + int code = check_file(argv[1], out, sizeof out, &rt); + if (code < 0) return 2; + puts(out); + return code == PST_OK && rt ? 0 : 1; + } + if (argc == 3 && strcmp(argv[1], "--corpus") == 0) return corpus(argv[2]); + if (argc == 3 && strcmp(argv[1], "--make-vectors") == 0) return make_vectors(argv[2]); + if (argc == 3 && strcmp(argv[1], "--session") == 0) { + session_verdict v; + size_t n; + if (slurp(argv[2], &n)) { fprintf(stderr, "cannot read %s\n", argv[2]); return 2; } + session_check(file_buf, n, &v); + session_line(&v, out, sizeof out); + puts(out); + return v.code == PST_OK ? 0 : 1; + } + if (argc >= 5 && strcmp(argv[1], "--session-fuzz") == 0) + return session_fuzz(strtoull(argv[2], NULL, 10), strtoul(argv[3], NULL, 10), argc - 4, argv + 4); + fprintf(stderr, "usage: pst_verify FILE | --session FILE | --corpus DIR | --make-vectors DIR\n" + " | --session-fuzz SEED COUNT SESSION_FILE...\n"); + return 2; +} diff --git a/specs/pi-spark-task/vectors/.gitattributes b/specs/pi-spark-task/vectors/.gitattributes new file mode 100644 index 0000000..c4c02e6 --- /dev/null +++ b/specs/pi-spark-task/vectors/.gitattributes @@ -0,0 +1,3 @@ +*.pst binary +*.pss binary +*.json binary diff --git a/specs/pi-spark-task/vectors/bad-digest.pst b/specs/pi-spark-task/vectors/bad-digest.pst new file mode 100644 index 0000000..8737c84 Binary files /dev/null and b/specs/pi-spark-task/vectors/bad-digest.pst differ diff --git a/specs/pi-spark-task/vectors/bad-effect-class.pst b/specs/pi-spark-task/vectors/bad-effect-class.pst new file mode 100644 index 0000000..5982fa8 Binary files /dev/null and b/specs/pi-spark-task/vectors/bad-effect-class.pst differ diff --git a/specs/pi-spark-task/vectors/bad-length-empty-file.pst b/specs/pi-spark-task/vectors/bad-length-empty-file.pst new file mode 100644 index 0000000..e69de29 diff --git a/specs/pi-spark-task/vectors/bad-length-mismatch.pst b/specs/pi-spark-task/vectors/bad-length-mismatch.pst new file mode 100644 index 0000000..846f7f2 Binary files /dev/null and b/specs/pi-spark-task/vectors/bad-length-mismatch.pst differ diff --git a/specs/pi-spark-task/vectors/bad-length-over-1024.pst b/specs/pi-spark-task/vectors/bad-length-over-1024.pst new file mode 100644 index 0000000..4c05252 Binary files /dev/null and b/specs/pi-spark-task/vectors/bad-length-over-1024.pst differ diff --git a/specs/pi-spark-task/vectors/bad-length-short-header.pst b/specs/pi-spark-task/vectors/bad-length-short-header.pst new file mode 100644 index 0000000..29fc12f Binary files /dev/null and b/specs/pi-spark-task/vectors/bad-length-short-header.pst differ diff --git a/specs/pi-spark-task/vectors/bad-magic.pst b/specs/pi-spark-task/vectors/bad-magic.pst new file mode 100644 index 0000000..519369b Binary files /dev/null and b/specs/pi-spark-task/vectors/bad-magic.pst differ diff --git a/specs/pi-spark-task/vectors/bad-no-cause.pst b/specs/pi-spark-task/vectors/bad-no-cause.pst new file mode 100644 index 0000000..971e0e5 Binary files /dev/null and b/specs/pi-spark-task/vectors/bad-no-cause.pst differ diff --git a/specs/pi-spark-task/vectors/bad-no-idempotence-key.pst b/specs/pi-spark-task/vectors/bad-no-idempotence-key.pst new file mode 100644 index 0000000..e958e0d Binary files /dev/null and b/specs/pi-spark-task/vectors/bad-no-idempotence-key.pst differ diff --git a/specs/pi-spark-task/vectors/bad-no-task-id.pst b/specs/pi-spark-task/vectors/bad-no-task-id.pst new file mode 100644 index 0000000..e882c8b Binary files /dev/null and b/specs/pi-spark-task/vectors/bad-no-task-id.pst differ diff --git a/specs/pi-spark-task/vectors/bad-payload-len-over-800.pst b/specs/pi-spark-task/vectors/bad-payload-len-over-800.pst new file mode 100644 index 0000000..630f57a Binary files /dev/null and b/specs/pi-spark-task/vectors/bad-payload-len-over-800.pst differ diff --git a/specs/pi-spark-task/vectors/bad-request-no-objective.pst b/specs/pi-spark-task/vectors/bad-request-no-objective.pst new file mode 100644 index 0000000..b471c1d Binary files /dev/null and b/specs/pi-spark-task/vectors/bad-request-no-objective.pst differ diff --git a/specs/pi-spark-task/vectors/bad-reserved0.pst b/specs/pi-spark-task/vectors/bad-reserved0.pst new file mode 100644 index 0000000..9d1a3bf Binary files /dev/null and b/specs/pi-spark-task/vectors/bad-reserved0.pst differ diff --git a/specs/pi-spark-task/vectors/bad-reserved1.pst b/specs/pi-spark-task/vectors/bad-reserved1.pst new file mode 100644 index 0000000..dbb6b8d Binary files /dev/null and b/specs/pi-spark-task/vectors/bad-reserved1.pst differ diff --git a/specs/pi-spark-task/vectors/bad-tool-head-extra-field.pst b/specs/pi-spark-task/vectors/bad-tool-head-extra-field.pst new file mode 100644 index 0000000..6b0b8c7 Binary files /dev/null and b/specs/pi-spark-task/vectors/bad-tool-head-extra-field.pst differ diff --git a/specs/pi-spark-task/vectors/bad-tool-head-over-limit.pst b/specs/pi-spark-task/vectors/bad-tool-head-over-limit.pst new file mode 100644 index 0000000..4eaa70c Binary files /dev/null and b/specs/pi-spark-task/vectors/bad-tool-head-over-limit.pst differ diff --git a/specs/pi-spark-task/vectors/bad-tool-head-short.pst b/specs/pi-spark-task/vectors/bad-tool-head-short.pst new file mode 100644 index 0000000..59b8e9e Binary files /dev/null and b/specs/pi-spark-task/vectors/bad-tool-head-short.pst differ diff --git a/specs/pi-spark-task/vectors/bad-tool-head-zero-length.pst b/specs/pi-spark-task/vectors/bad-tool-head-zero-length.pst new file mode 100644 index 0000000..44249e0 Binary files /dev/null and b/specs/pi-spark-task/vectors/bad-tool-head-zero-length.pst differ diff --git a/specs/pi-spark-task/vectors/bad-tool-request-no-objective.pst b/specs/pi-spark-task/vectors/bad-tool-request-no-objective.pst new file mode 100644 index 0000000..579285b Binary files /dev/null and b/specs/pi-spark-task/vectors/bad-tool-request-no-objective.pst differ diff --git a/specs/pi-spark-task/vectors/bad-trailing-byte.pst b/specs/pi-spark-task/vectors/bad-trailing-byte.pst new file mode 100644 index 0000000..4a957d0 Binary files /dev/null and b/specs/pi-spark-task/vectors/bad-trailing-byte.pst differ diff --git a/specs/pi-spark-task/vectors/bad-type-unknown.pst b/specs/pi-spark-task/vectors/bad-type-unknown.pst new file mode 100644 index 0000000..400b0bb Binary files /dev/null and b/specs/pi-spark-task/vectors/bad-type-unknown.pst differ diff --git a/specs/pi-spark-task/vectors/bad-type-zero.pst b/specs/pi-spark-task/vectors/bad-type-zero.pst new file mode 100644 index 0000000..98cded0 Binary files /dev/null and b/specs/pi-spark-task/vectors/bad-type-zero.pst differ diff --git a/specs/pi-spark-task/vectors/bad-version-downgrade.pst b/specs/pi-spark-task/vectors/bad-version-downgrade.pst new file mode 100644 index 0000000..dafe08c Binary files /dev/null and b/specs/pi-spark-task/vectors/bad-version-downgrade.pst differ diff --git a/specs/pi-spark-task/vectors/bad-version-unknown.pst b/specs/pi-spark-task/vectors/bad-version-unknown.pst new file mode 100644 index 0000000..3fc9c4a Binary files /dev/null and b/specs/pi-spark-task/vectors/bad-version-unknown.pst differ diff --git a/specs/pi-spark-task/vectors/expected.txt b/specs/pi-spark-task/vectors/expected.txt new file mode 100644 index 0000000..112bcd8 --- /dev/null +++ b/specs/pi-spark-task/vectors/expected.txt @@ -0,0 +1,36 @@ +# PST1 single-message vectors. Spec: ../SPEC.md (wire version 1), sections 4 and 7. +# Line: , verdict line as printed by tools/pst_verify.c: +# ok type=T version=V cause=H64 origin=H64 objective=H64 subject=H64 parent=H32 +# task=H32 idem=H32 ordinal=N effect=E len=L digest=H64 (one line) +# refuse +# Generated by tools/pst_verify.c --make-vectors; do not edit by hand. +ok-request.pst ok type=1 version=1 cause=c1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939a origin=0a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3 objective=0b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4 subject=5b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d34 parent=00000000000000000000000000000000 task=7a81888f969da4abb2b9c0c7ced5dce3 idem=1d242b323940474e555c636a71787f86 ordinal=0 effect=1 len=49 digest=e57392a27132b97e2cbfaa4b04ad3446cab722297cf48ce22c7c2fb787940cc6 +ok-accepted-empty.pst ok type=2 version=1 cause=c1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939a origin=0a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3 objective=0b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4 subject=5b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d34 parent=00000000000000000000000000000000 task=7a81888f969da4abb2b9c0c7ced5dce3 idem=1d242b323940474e555c636a71787f86 ordinal=1 effect=1 len=0 digest=e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 +ok-text-chunk-1024.pst ok type=5 version=1 cause=c1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939a origin=0a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3 objective=0b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4 subject=5b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d34 parent=9ea5acb3bac1c8cfd6dde4ebf2f90007 task=7a81888f969da4abb2b9c0c7ced5dce3 idem=1d242b323940474e555c636a71787f86 ordinal=7 effect=0 len=800 digest=20885ae2150992180a94350ef60c6d8a1599899bcd2752d3392f8ad591ddd8b1 +ok-resume-request-max-ordinal.pst ok type=14 version=1 cause=c1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939a origin=0a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3 objective=0b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4 subject=5b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d34 parent=00000000000000000000000000000000 task=7a81888f969da4abb2b9c0c7ced5dce3 idem=1d242b323940474e555c636a71787f86 ordinal=4294967295 effect=2 len=0 digest=e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 +bad-length-short-header.pst refuse PST_BAD_LENGTH +bad-length-empty-file.pst refuse PST_BAD_LENGTH +bad-length-over-1024.pst refuse PST_BAD_LENGTH +bad-magic.pst refuse PST_BAD_MAGIC +bad-version-unknown.pst refuse PST_BAD_VERSION +bad-version-downgrade.pst refuse PST_DOWNGRADE +bad-type-zero.pst refuse PST_BAD_TYPE +bad-type-unknown.pst refuse PST_BAD_TYPE +bad-reserved0.pst refuse PST_RESERVED_NONZERO +bad-reserved1.pst refuse PST_RESERVED_NONZERO +bad-length-mismatch.pst refuse PST_BAD_LENGTH +bad-payload-len-over-800.pst refuse PST_BAD_LENGTH +bad-trailing-byte.pst refuse PST_TRAILING_BYTES +bad-effect-class.pst refuse PST_BAD_EFFECT_CLASS +bad-no-cause.pst refuse PST_NO_CAUSE +bad-no-task-id.pst refuse PST_NO_TASK +bad-no-idempotence-key.pst refuse PST_NO_TASK +bad-request-no-objective.pst refuse PST_NO_OBJECTIVE +bad-digest.pst refuse PST_DIGEST_MISMATCH +ok-tool-call-request.pst ok type=15 version=1 cause=c1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939a origin=0a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3 objective=0b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4 subject=5b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d34 parent=00000000000000000000000000000000 task=7a81888f969da4abb2b9c0c7ced5dce3 idem=1d242b323940474e555c636a71787f86 ordinal=1 effect=1 len=36 digest=0d9b1b17a5d6dbf515598cc2c0a6c39c08cd36cbfca891ada1577d4a292d851c +ok-tool-call-chunk.pst ok type=16 version=1 cause=c1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939a origin=0a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3 objective=0b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4 subject=5b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d34 parent=00000000000000000000000000000000 task=7a81888f969da4abb2b9c0c7ced5dce3 idem=1d242b323940474e555c636a71787f86 ordinal=1 effect=1 len=800 digest=133abdc089835151b303f53823d95d43aca90c866052d4a702e4d9636cafae87 +bad-tool-head-extra-field.pst refuse PST_BAD_TOOL_HEAD +bad-tool-head-short.pst refuse PST_BAD_TOOL_HEAD +bad-tool-head-zero-length.pst refuse PST_BAD_TOOL_HEAD +bad-tool-head-over-limit.pst refuse PST_BAD_TOOL_HEAD +bad-tool-request-no-objective.pst refuse PST_NO_OBJECTIVE diff --git a/specs/pi-spark-task/vectors/interplane-tool-request.json b/specs/pi-spark-task/vectors/interplane-tool-request.json new file mode 100644 index 0000000..32d044f Binary files /dev/null and b/specs/pi-spark-task/vectors/interplane-tool-request.json differ diff --git a/specs/pi-spark-task/vectors/ok-accepted-empty.pst b/specs/pi-spark-task/vectors/ok-accepted-empty.pst new file mode 100644 index 0000000..92bd349 Binary files /dev/null and b/specs/pi-spark-task/vectors/ok-accepted-empty.pst differ diff --git a/specs/pi-spark-task/vectors/ok-request.pst b/specs/pi-spark-task/vectors/ok-request.pst new file mode 100644 index 0000000..685b258 Binary files /dev/null and b/specs/pi-spark-task/vectors/ok-request.pst differ diff --git a/specs/pi-spark-task/vectors/ok-resume-request-max-ordinal.pst b/specs/pi-spark-task/vectors/ok-resume-request-max-ordinal.pst new file mode 100644 index 0000000..5daa99c Binary files /dev/null and b/specs/pi-spark-task/vectors/ok-resume-request-max-ordinal.pst differ diff --git a/specs/pi-spark-task/vectors/ok-text-chunk-1024.pst b/specs/pi-spark-task/vectors/ok-text-chunk-1024.pst new file mode 100644 index 0000000..9ad7129 Binary files /dev/null and b/specs/pi-spark-task/vectors/ok-text-chunk-1024.pst differ diff --git a/specs/pi-spark-task/vectors/ok-tool-call-chunk.pst b/specs/pi-spark-task/vectors/ok-tool-call-chunk.pst new file mode 100644 index 0000000..76e79ae Binary files /dev/null and b/specs/pi-spark-task/vectors/ok-tool-call-chunk.pst differ diff --git a/specs/pi-spark-task/vectors/ok-tool-call-request.pst b/specs/pi-spark-task/vectors/ok-tool-call-request.pst new file mode 100644 index 0000000..74ea2c5 Binary files /dev/null and b/specs/pi-spark-task/vectors/ok-tool-call-request.pst differ diff --git a/specs/pi-spark-task/vectors/sessions/bad-approval-by-pi.pss b/specs/pi-spark-task/vectors/sessions/bad-approval-by-pi.pss new file mode 100644 index 0000000..09a4eae Binary files /dev/null and b/specs/pi-spark-task/vectors/sessions/bad-approval-by-pi.pss differ diff --git a/specs/pi-spark-task/vectors/sessions/bad-approval-rule-not-yet-defined.pss b/specs/pi-spark-task/vectors/sessions/bad-approval-rule-not-yet-defined.pss new file mode 100644 index 0000000..d113eb6 Binary files /dev/null and b/specs/pi-spark-task/vectors/sessions/bad-approval-rule-not-yet-defined.pss differ diff --git a/specs/pi-spark-task/vectors/sessions/bad-chunk-after-final.pss b/specs/pi-spark-task/vectors/sessions/bad-chunk-after-final.pss new file mode 100644 index 0000000..3d423c9 Binary files /dev/null and b/specs/pi-spark-task/vectors/sessions/bad-chunk-after-final.pss differ diff --git a/specs/pi-spark-task/vectors/sessions/bad-chunk-repeated.pss b/specs/pi-spark-task/vectors/sessions/bad-chunk-repeated.pss new file mode 100644 index 0000000..122e789 Binary files /dev/null and b/specs/pi-spark-task/vectors/sessions/bad-chunk-repeated.pss differ diff --git a/specs/pi-spark-task/vectors/sessions/bad-chunk-skipped.pss b/specs/pi-spark-task/vectors/sessions/bad-chunk-skipped.pss new file mode 100644 index 0000000..391d13f Binary files /dev/null and b/specs/pi-spark-task/vectors/sessions/bad-chunk-skipped.pss differ diff --git a/specs/pi-spark-task/vectors/sessions/bad-completed-before-accepted.pss b/specs/pi-spark-task/vectors/sessions/bad-completed-before-accepted.pss new file mode 100644 index 0000000..84c19de Binary files /dev/null and b/specs/pi-spark-task/vectors/sessions/bad-completed-before-accepted.pss differ diff --git a/specs/pi-spark-task/vectors/sessions/bad-completed-by-pi.pss b/specs/pi-spark-task/vectors/sessions/bad-completed-by-pi.pss new file mode 100644 index 0000000..8d1a644 Binary files /dev/null and b/specs/pi-spark-task/vectors/sessions/bad-completed-by-pi.pss differ diff --git a/specs/pi-spark-task/vectors/sessions/bad-context-change.pss b/specs/pi-spark-task/vectors/sessions/bad-context-change.pss new file mode 100644 index 0000000..3c2a3bc Binary files /dev/null and b/specs/pi-spark-task/vectors/sessions/bad-context-change.pss differ diff --git a/specs/pi-spark-task/vectors/sessions/bad-idempotence-key-other-digest.pss b/specs/pi-spark-task/vectors/sessions/bad-idempotence-key-other-digest.pss new file mode 100644 index 0000000..d9e5207 Binary files /dev/null and b/specs/pi-spark-task/vectors/sessions/bad-idempotence-key-other-digest.pss differ diff --git a/specs/pi-spark-task/vectors/sessions/bad-idempotence-key-other-task.pss b/specs/pi-spark-task/vectors/sessions/bad-idempotence-key-other-task.pss new file mode 100644 index 0000000..e901d6f Binary files /dev/null and b/specs/pi-spark-task/vectors/sessions/bad-idempotence-key-other-task.pss differ diff --git a/specs/pi-spark-task/vectors/sessions/bad-message-in-session.pss b/specs/pi-spark-task/vectors/sessions/bad-message-in-session.pss new file mode 100644 index 0000000..324f328 Binary files /dev/null and b/specs/pi-spark-task/vectors/sessions/bad-message-in-session.pss differ diff --git a/specs/pi-spark-task/vectors/sessions/bad-recording.pss b/specs/pi-spark-task/vectors/sessions/bad-recording.pss new file mode 100644 index 0000000..7a60da6 Binary files /dev/null and b/specs/pi-spark-task/vectors/sessions/bad-recording.pss differ diff --git a/specs/pi-spark-task/vectors/sessions/bad-resume-unknown-task.pss b/specs/pi-spark-task/vectors/sessions/bad-resume-unknown-task.pss new file mode 100644 index 0000000..fd77f2c Binary files /dev/null and b/specs/pi-spark-task/vectors/sessions/bad-resume-unknown-task.pss differ diff --git a/specs/pi-spark-task/vectors/sessions/bad-second-final.pss b/specs/pi-spark-task/vectors/sessions/bad-second-final.pss new file mode 100644 index 0000000..148ff2b Binary files /dev/null and b/specs/pi-spark-task/vectors/sessions/bad-second-final.pss differ diff --git a/specs/pi-spark-task/vectors/sessions/bad-session-full.pss b/specs/pi-spark-task/vectors/sessions/bad-session-full.pss new file mode 100644 index 0000000..78122aa Binary files /dev/null and b/specs/pi-spark-task/vectors/sessions/bad-session-full.pss differ diff --git a/specs/pi-spark-task/vectors/sessions/bad-subject-change.pss b/specs/pi-spark-task/vectors/sessions/bad-subject-change.pss new file mode 100644 index 0000000..3b92aaf Binary files /dev/null and b/specs/pi-spark-task/vectors/sessions/bad-subject-change.pss differ diff --git a/specs/pi-spark-task/vectors/sessions/bad-tool-altered-byte.pss b/specs/pi-spark-task/vectors/sessions/bad-tool-altered-byte.pss new file mode 100644 index 0000000..b1c07b7 Binary files /dev/null and b/specs/pi-spark-task/vectors/sessions/bad-tool-altered-byte.pss differ diff --git a/specs/pi-spark-task/vectors/sessions/bad-tool-chunk-after-complete.pss b/specs/pi-spark-task/vectors/sessions/bad-tool-chunk-after-complete.pss new file mode 100644 index 0000000..4b9aa75 Binary files /dev/null and b/specs/pi-spark-task/vectors/sessions/bad-tool-chunk-after-complete.pss differ diff --git a/specs/pi-spark-task/vectors/sessions/bad-tool-digest-mismatch.pss b/specs/pi-spark-task/vectors/sessions/bad-tool-digest-mismatch.pss new file mode 100644 index 0000000..5bd1636 Binary files /dev/null and b/specs/pi-spark-task/vectors/sessions/bad-tool-digest-mismatch.pss differ diff --git a/specs/pi-spark-task/vectors/sessions/bad-tool-extra-bytes.pss b/specs/pi-spark-task/vectors/sessions/bad-tool-extra-bytes.pss new file mode 100644 index 0000000..c869347 Binary files /dev/null and b/specs/pi-spark-task/vectors/sessions/bad-tool-extra-bytes.pss differ diff --git a/specs/pi-spark-task/vectors/sessions/bad-tool-payload-in-chat-task.pss b/specs/pi-spark-task/vectors/sessions/bad-tool-payload-in-chat-task.pss new file mode 100644 index 0000000..02354e4 Binary files /dev/null and b/specs/pi-spark-task/vectors/sessions/bad-tool-payload-in-chat-task.pss differ diff --git a/specs/pi-spark-task/vectors/sessions/bad-tool-short-chunk.pss b/specs/pi-spark-task/vectors/sessions/bad-tool-short-chunk.pss new file mode 100644 index 0000000..8798847 Binary files /dev/null and b/specs/pi-spark-task/vectors/sessions/bad-tool-short-chunk.pss differ diff --git a/specs/pi-spark-task/vectors/sessions/bad-tool-truncated.pss b/specs/pi-spark-task/vectors/sessions/bad-tool-truncated.pss new file mode 100644 index 0000000..7c51c1a Binary files /dev/null and b/specs/pi-spark-task/vectors/sessions/bad-tool-truncated.pss differ diff --git a/specs/pi-spark-task/vectors/sessions/expected.txt b/specs/pi-spark-task/vectors/sessions/expected.txt new file mode 100644 index 0000000..84bb84c --- /dev/null +++ b/specs/pi-spark-task/vectors/sessions/expected.txt @@ -0,0 +1,31 @@ +# PST1 recorded sessions. Spec: ../../SPEC.md section 10 (rules) and 10.4 (container). +# Line: ok steps=N tasks=T | refuse step=N (1-based message position) +# Generated by tools/pst_verify.c --make-vectors; do not edit by hand. +ok-normal-life.pss ok steps=7 tasks=1 +ok-two-tasks-queued-cancelled.pss ok steps=8 tasks=2 +ok-repeated-request.pss ok steps=5 tasks=1 +bad-completed-before-accepted.pss refuse PST_BAD_ORDER step=2 +bad-second-final.pss refuse PST_SECOND_FINAL step=5 +bad-chunk-skipped.pss refuse PST_ORDINAL_GAP step=5 +bad-chunk-repeated.pss refuse PST_ORDINAL_REPEAT step=5 +bad-subject-change.pss refuse PST_SUBJECT_MISMATCH step=2 +bad-idempotence-key-other-digest.pss refuse PST_IDEMPOTENCE_CONFLICT step=3 +bad-idempotence-key-other-task.pss refuse PST_IDEMPOTENCE_CONFLICT step=2 +bad-completed-by-pi.pss refuse PST_WRONG_SIDE step=4 +bad-approval-by-pi.pss refuse PST_WRONG_SIDE step=4 +bad-resume-unknown-task.pss refuse PST_UNKNOWN_TASK step=3 +bad-context-change.pss refuse PST_CONTEXT_MISMATCH step=3 +bad-chunk-after-final.pss refuse PST_BAD_ORDER step=5 +bad-approval-rule-not-yet-defined.pss refuse PST_BAD_ORDER step=4 +bad-message-in-session.pss refuse PST_BAD_MAGIC step=2 +bad-session-full.pss refuse PST_SESSION_FULL step=17 +bad-recording.pss refuse PST_BAD_RECORDING step=2 +ok-tool-call.pss ok steps=7 tasks=1 +ok-tool-call-failed-while-collecting.pss ok steps=3 tasks=1 +bad-tool-digest-mismatch.pss refuse PST_TOOL_DIGEST_MISMATCH step=4 +bad-tool-altered-byte.pss refuse PST_TOOL_DIGEST_MISMATCH step=4 +bad-tool-extra-bytes.pss refuse PST_TOOL_CHUNK_SIZE step=4 +bad-tool-short-chunk.pss refuse PST_TOOL_CHUNK_SIZE step=2 +bad-tool-chunk-after-complete.pss refuse PST_BAD_ORDER step=5 +bad-tool-truncated.pss refuse PST_TOOL_INCOMPLETE step=4 +bad-tool-payload-in-chat-task.pss refuse PST_NOT_TOOL_TASK step=2 diff --git a/specs/pi-spark-task/vectors/sessions/ok-normal-life.pss b/specs/pi-spark-task/vectors/sessions/ok-normal-life.pss new file mode 100644 index 0000000..bbf506c Binary files /dev/null and b/specs/pi-spark-task/vectors/sessions/ok-normal-life.pss differ diff --git a/specs/pi-spark-task/vectors/sessions/ok-repeated-request.pss b/specs/pi-spark-task/vectors/sessions/ok-repeated-request.pss new file mode 100644 index 0000000..d0095e5 Binary files /dev/null and b/specs/pi-spark-task/vectors/sessions/ok-repeated-request.pss differ diff --git a/specs/pi-spark-task/vectors/sessions/ok-tool-call-failed-while-collecting.pss b/specs/pi-spark-task/vectors/sessions/ok-tool-call-failed-while-collecting.pss new file mode 100644 index 0000000..8fde2b9 Binary files /dev/null and b/specs/pi-spark-task/vectors/sessions/ok-tool-call-failed-while-collecting.pss differ diff --git a/specs/pi-spark-task/vectors/sessions/ok-tool-call.pss b/specs/pi-spark-task/vectors/sessions/ok-tool-call.pss new file mode 100644 index 0000000..28a9c2f Binary files /dev/null and b/specs/pi-spark-task/vectors/sessions/ok-tool-call.pss differ diff --git a/specs/pi-spark-task/vectors/sessions/ok-two-tasks-queued-cancelled.pss b/specs/pi-spark-task/vectors/sessions/ok-two-tasks-queued-cancelled.pss new file mode 100644 index 0000000..95864a6 Binary files /dev/null and b/specs/pi-spark-task/vectors/sessions/ok-two-tasks-queued-cancelled.pss differ