interplane.Get Omega
Read in your language

interplane-mv

INTERPLANE: open interoperability protocol between AI models and agent runtimes. Models express intent. Runtimes retain authority.

Brought by drakestapleton

branch main Branches Tags History

interplane-mv / provenance / src / modelturn.rs

340 lines · 14297 bytes Raw Blame History
1//! Who authored the proposal: the `model_turn` and `generation` records.
2//!
3//! The approved write path never calls the model, so the content of an effect only comes from the
4//! loaded model if the model produced the tool-call text UPSTREAM, in the same trace. This module
5//! checks that claim as far as the retained bytes allow and says exactly what stays unproven.
6//!
7//! `effect.proposal_origin`:
8//! - `scripted_turn`: the INTERPLANE model turn was written by the harness. The link "this model
9//! produced this effect" is missing: `link:model_turn`.
10//! - `model_generation/2`: `model_turn` (the exact text the dialect parsed, plus the id the daemon
11//! returned in `TurnFinished.generation_record`) and `ledger_generation` (the DAEMON'S OWN record
12//! of that generation, exported with `ComposeRecall`, see sovereign-core
13//! docs/DAEMON_GENERATION_RECORD.md) are retained. Checked: the record is a verified `effect`
14//! note whose text is one JSON object with `generation == 1`, `v == 1` and no links; its
15//! model and tokenizer digests are the exported files; its output digest is the digest of the
16//! model turn text; the text re-parses, with the real `aien_legacy` dialect, into the trace's
17//! request; its daemon pid/start are the daemon that served the effect; it precedes the effect's
18//! replay claim in the ledger. Nothing is missing then, but see "Does not prove" in the doc:
19//! the hash-then-load gap, no signature, and a same-user process could append a record.
20//! - `model_generation/1` (a record written by the run driver) is superseded and refused.
21//!
22//! Reads and compares only. It never authorizes or executes anything.
23
24use super::{fail, s, Archive, Call, Fail};
25use crate::gojson::sha256_hex;
26use interplane_lenshift::{DialectRegistry, ParseContext};
27use serde_json::{json, Value};
28
29pub const SCRIPTED: &str = "scripted_turn";
30pub const GENERATED: &str = "model_generation/2";
31pub const SUPERSEDED: &str = "model_generation/1";
32pub const MISSING_MODEL_TURN: &str = "link:model_turn";
33
34/// Missing links implied by the effect's declared origin. A pure function of the manifest and the
35/// retained `generation` record, so the completeness label can be compared before the deeper checks.
36pub fn implied_missing(_a: &Archive, m: &Value) -> Vec<String> {
37 let Some(e) = m.get("effect").filter(|e| e.is_object()) else {
38 return vec![];
39 };
40 match s(e, &["binding"]) {
41 Some(crate::binding::LEDGER_BINDING) => match s(e, &["proposal_origin"]) {
42 Some(SCRIPTED) => vec![MISSING_MODEL_TURN.into()],
43 Some(GENERATED) => vec![],
44 _ => vec![],
45 },
46 // The loose receipt names no request, trace or author: the model link is missing there too.
47 Some(crate::binding::RECEIPT_BINDING) => vec![MISSING_MODEL_TURN.into()],
48 _ => vec![],
49 }
50}
51
52/// Checks for `proposal_origin = model_generation/2`.
53pub fn check(a: &Archive, t: &Value, call: Option<&Call>) -> Result<(), Fail> {
54 let Some(call) = call else {
55 return fail(
56 "missing_record",
57 "interplane_trace (model_generation/2 needs it)",
58 );
59 };
60 let Some(turn) = a.json("model_turn")? else {
61 return fail("missing_record", "model_turn (not retained)");
62 };
63 if !a.has("ledger_generation") {
64 return fail("missing_record_entry", "ledger_generation");
65 }
66 let (Some(text), Some(model), Some(dialect)) = (
67 s(&turn, &["input"]),
68 s(&turn, &["model"]),
69 s(&turn, &["dialect"]),
70 ) else {
71 return fail("malformed_companion", "model_turn.input/model/dialect");
72 };
73 if dialect != "aien_legacy" {
74 return fail(
75 "unsupported_binding",
76 format!("model_turn.dialect={dialect}"),
77 );
78 }
79 // 1. The daemon's own record of the generation.
80 let Some(rec) = a.json("ledger_generation")? else {
81 return fail("missing_record", "ledger_generation (not retained)");
82 };
83 let bad = |what: &str| -> Result<(), Fail> {
84 fail("binding_mismatch", format!("ledger_generation.{what}"))
85 };
86 let Some(id) = rec.get("id").and_then(Value::as_u64) else {
87 return bad("id");
88 };
89 if rec.get("verified") != Some(&Value::Bool(true)) {
90 return bad("verified");
91 }
92 if s(&rec, &["note"]) != Some("effect") {
93 return bad("note");
94 }
95 // "Empty links": the view carries four fixed slots, all zero.
96 if !matches!(rec.get("links").and_then(Value::as_array),
97 Some(l) if l.iter().all(|x| x.as_u64() == Some(0)))
98 {
99 return bad("links (must be empty)");
100 }
101 // Strict parse: the note text is exactly one JSON object.
102 let Some(g) = rec
103 .get("text")
104 .and_then(Value::as_str)
105 .and_then(|t| crate::strict::parse(t.as_bytes()))
106 .filter(Value::is_object)
107 else {
108 return bad("text (not one JSON object)");
109 };
110 if g.get("generation").and_then(Value::as_u64) != Some(1)
111 || g.get("v").and_then(Value::as_u64) != Some(1)
112 {
113 return bad("generation/v marker");
114 }
115 // The id the daemon returned to the client is the record that is retained.
116 if turn.get("generation_record_id").and_then(Value::as_u64) != Some(id) {
117 return fail(
118 "binding_mismatch",
119 "model_turn.generation_record_id != ledger_generation.id",
120 );
121 }
122 // The digest the record carries is the digest of the very text the dialect parsed.
123 if s(&g, &["output_text_sha256"]) != Some(sha256_hex(text.as_bytes()).as_str()) {
124 return fail(
125 "binding_mismatch",
126 "generation record output_text_sha256 != sha256(model_turn.input)",
127 );
128 }
129 // The model and tokenizer the daemon says it held are the exported files.
130 if s(&g, &["model_sha256"]) != Some(a.sha("export_weights")?) {
131 return fail(
132 "binding_mismatch",
133 "generation record model_sha256 != export_weights",
134 );
135 }
136 if s(&g, &["tokenizer_sha256"]) != Some(a.sha("export_tokenizer")?) {
137 return fail(
138 "binding_mismatch",
139 "generation record tokenizer_sha256 != export_tokenizer",
140 );
141 }
142 match s(&g, &["finish_reason"]) {
143 Some("eos") | Some("max_tokens") => {}
144 other => {
145 return fail(
146 "binding_mismatch",
147 format!(
148 "generation record finish_reason={}",
149 other.unwrap_or("absent")
150 ),
151 )
152 }
153 }
154 if g.get("output_tokens").and_then(Value::as_u64).unwrap_or(0) == 0 {
155 return fail("binding_mismatch", "generation record output_tokens");
156 }
157 for k in ["prompt_ids_sha256", "output_token_ids_sha256"] {
158 match s(&g, &[k]) {
159 Some(h) if h.len() == 64 && h.bytes().all(|b| b.is_ascii_hexdigit()) => {}
160 _ => return fail("binding_mismatch", format!("generation record {k}")),
161 }
162 }
163 // The daemon that wrote it is the daemon that served the effect.
164 let run = a.json("daemon_run")?.unwrap_or(Value::Null);
165 let d = g.get("daemon").unwrap_or(&Value::Null);
166 if d.get("pid") != run.get("pid") || d.get("start_ticks") != run.get("start_ticks") {
167 return fail(
168 "binding_mismatch",
169 "generation record daemon pid/start vs daemon_run",
170 );
171 }
172 // The generation precedes the effect: before the replay claim of the approved write.
173 let claim = a.json("ledger_claim")?.unwrap_or(Value::Null);
174 match claim.get("id").and_then(Value::as_u64) {
175 Some(c) if id < c => {}
176 _ => {
177 return fail(
178 "binding_mismatch",
179 "generation record does not precede the effect's replay claim",
180 )
181 }
182 }
183 // 3. The real dialect turns that text into this trace's request.
184 let (Some(tid), Some(rid)) = (s(t, &["trace_id"]), s(t, &["request_id"])) else {
185 return fail("malformed_companion", "interplane.trace_id/request_id");
186 };
187 if s(&turn, &["trace_id"]) != Some(tid) {
188 return fail("binding_mismatch", "model_turn.trace_id");
189 }
190 let registry = DialectRegistry::with_defaults();
191 let Ok(d) = registry.get("aien_legacy") else {
192 return fail("unsupported_binding", "aien_legacy dialect unavailable");
193 };
194 let parsed = d.parse(
195 &json!(text),
196 &ParseContext {
197 trace_id: tid.into(),
198 turn: turn.get("turn").and_then(Value::as_u64).unwrap_or(0),
199 model: model.into(),
200 },
201 );
202 if parsed.intents.len() != 1 || !parsed.rejected.is_empty() || parsed.partial {
203 return fail(
204 "binding_mismatch",
205 format!(
206 "model_turn parses to {} request(s), {} rejected",
207 parsed.intents.len(),
208 parsed.rejected.len()
209 ),
210 );
211 }
212 let i = &parsed.intents[0];
213 if i.request_id != rid {
214 return fail(
215 "binding_mismatch",
216 format!("model_turn request_id {} vs interplane {rid}", i.request_id),
217 );
218 }
219 if i.tool.name != call.tool {
220 return fail("binding_mismatch", "model_turn tool vs trace request");
221 }
222 if serde_json::to_value(&i.arguments).ok().as_ref() != Some(&call.args) {
223 return fail("binding_mismatch", "model_turn arguments vs trace request");
224 }
225 if let Some(sd) = call.req_payload["provenance"]["source_digest"].as_str() {
226 if i.provenance.source_digest.as_deref() != Some(sd) {
227 return fail(
228 "binding_mismatch",
229 "model_turn source_digest vs trace request",
230 );
231 }
232 }
233 // 4. The trace says the model sent it.
234 if s(&call.req_source, &["kind"]) != Some("model")
235 || s(&call.req_source, &["id"]) != Some(model)
236 {
237 return fail(
238 "binding_mismatch",
239 "trace request source vs model_turn.model",
240 );
241 }
242 check_turn_record(a)?;
243 Ok(())
244}
245
246fn is_rfc3339_utc(x: &str) -> bool {
247 let b = x.as_bytes();
248 b.len() == 20
249 && b[19] == b'Z'
250 && [4, 7].iter().all(|&i| b[i] == b'-')
251 && b[10] == b'T'
252 && [13, 16].iter().all(|&i| b[i] == b':')
253 && b.iter()
254 .enumerate()
255 .all(|(i, c)| [4, 7, 10, 13, 16, 19].contains(&i) || c.is_ascii_digit())
256}
257
258/// `model-turn/2`: the retained model turn names the exact request and response bytes, the model
259/// and the weights digest, the backend and the times, and each one is compared with what the
260/// bundle retains. Runs only for a turn that declares `record: "model-turn/2"`; a turn without
261/// the marker keeps the older, weaker checks above and is not read as carrying these links.
262/// Compared, never trusted: the request bytes are the harness's own (the daemon's record holds
263/// only the token-id digest of the prompt, which this offline check cannot recompute), and the
264/// backend line is the daemon's log line quoted by the harness.
265fn check_turn_record(a: &Archive) -> Result<(), Fail> {
266 let Some(turn) = a.json("model_turn")? else {
267 return fail("missing_record", "model_turn (not retained)");
268 };
269 if s(&turn, &["record"]) != Some("model-turn/2") {
270 return Ok(());
271 }
272 let bad =
273 |what: &str| -> Result<(), Fail> { fail("binding_mismatch", format!("model_turn.{what}")) };
274 let hex64 = |x: Option<&str>| {
275 x.is_some_and(|h| h.len() == 64 && h.bytes().all(|b| b.is_ascii_hexdigit()))
276 };
277 // Request bytes: the retained record is exactly the bytes whose digest the turn names.
278 if s(&turn, &["request_record"]) != Some("model_request") {
279 return bad("request_record");
280 }
281 if !a.has("model_request") {
282 return fail("missing_record_entry", "model_request");
283 }
284 let Some(req) = a.bytes("model_request")? else {
285 return fail("missing_record", "model_request (not retained)");
286 };
287 let req_sha = sha256_hex(req);
288 if !hex64(s(&turn, &["request_sha256"])) || s(&turn, &["request_sha256"]) != Some(&req_sha) {
289 return bad("request_sha256 != sha256(model_request)");
290 }
291 if a.sha("model_request")? != req_sha {
292 return bad("request_sha256 != record digest");
293 }
294 // The request is a messages array that really asks for something (not an empty shell).
295 match crate::strict::parse(req) {
296 Some(Value::Array(m)) if !m.is_empty() => {}
297 _ => return bad("model_request (not a non-empty messages array)"),
298 }
299 // Response bytes: the exact text the dialect parsed.
300 let Some(text) = s(&turn, &["input"]) else {
301 return bad("input");
302 };
303 if s(&turn, &["response_sha256"]) != Some(sha256_hex(text.as_bytes()).as_str()) {
304 return bad("response_sha256 != sha256(input)");
305 }
306 // Weights: the digest the turn names is the exported file the daemon's record also names.
307 if s(&turn, &["weights_sha256"]) != Some(a.sha("export_weights")?) {
308 return bad("weights_sha256 != export_weights");
309 }
310 for k in ["model_id", "backend"] {
311 if s(&turn, &[k]).is_none_or(str::is_empty) {
312 return bad(k);
313 }
314 }
315 // The backend line is quoted from the load log the bundle retains.
316 let backend = s(&turn, &["backend"]).unwrap_or("");
317 let log = a
318 .bytes("aien_load_log")?
319 .map(|b| String::from_utf8_lossy(b).into_owned())
320 .unwrap_or_default();
321 if !log.lines().any(|l| l.trim() == backend) {
322 return bad("backend (not a line of aien_load_log)");
323 }
324 // Times: well formed, ordered, and the model finished before the request was admitted.
325 let (Some(t0), Some(t1)) = (
326 s(&turn, &["stream_started"]),
327 s(&turn, &["stream_finished"]),
328 ) else {
329 return bad("stream_started/stream_finished");
330 };
331 if !is_rfc3339_utc(t0) || !is_rfc3339_utc(t1) || t0 > t1 {
332 return bad("stream_started/stream_finished (order or form)");
333 }
334 let trace = a.json("interplane_trace")?.unwrap_or(Value::Null);
335 match trace.get(0).and_then(|e| s(e, &["timestamp"])) {
336 Some(req_t) if t1 <= req_t => {}
337 _ => return bad("stream_finished is after the trace request"),
338 }
339 Ok(())
340}