polyc-facts 2026.9.0

Shared semantic-fold library: decode-to-fact functions reused by every consumer that reads the event log, so a payment receipt or a tool call means the same thing everywhere it's read.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
//! The approval-event fold — the SINGLE definition of "how does this
//! `approval_response`'s embedded signature read", shared by every consumer
//! that classifies one (`forensics::classify_response_signature`,
//! `trace::response_signature_evidence`, and the `polyc-query` `approvals`
//! typed table), so none can drift on which responses they call verified,
//! genuinely invalid, or a legacy record this build can no longer re-verify.
//!
//! Mirrors `crates/facts/src/receipts.rs`'s module shape: this file owns the
//! fold, never the decode primitives underneath it — every JSON field pull
//! and every signature check routes through `polyc_crypto::approval`'s
//! existing encoders/decoders
//! ([`polyc_crypto::approval::decode_request_fields`],
//! [`polyc_crypto::approval::decode_request_reason`],
//! [`polyc_crypto::approval::decode_request_sandbox_mode`],
//! [`polyc_crypto::approval::decode_response_minimal`],
//! [`polyc_crypto::approval::decode_response_full`],
//! [`polyc_crypto::approval::verify_signed_response_pinned`]) — this module
//! adds only the mechanical "which of these fields exist" plumbing those
//! primitives don't already assemble into one fact.
//!
//! # Different posture from [`crate::receipts`]
//!
//! [`crate::receipts::verified_receipts`] DROPS a payment receipt that fails
//! signature verification — a receipt that doesn't verify never counts, full
//! stop. An `approval_response` is different: the `/approvals` audit surface
//! (`crates/control-plane/src/forensics.rs`'s `collect_approvals`) is
//! explicitly a forensic record of what was DECIDED, including a decision
//! whose signature turns out to be forged or tampered — that is exactly the
//! audit signal the surface exists to show, tagged `INVALID` rather than
//! silently hidden. [`fold_approval_event`] therefore returns a fact for
//! every structurally-decodable `approval_response`/`approval_request`
//! regardless of its signature status; only a payload so malformed it can't
//! even yield a `request_id` (and, for a response, an `approved` decision)
//! decodes to `None`. Redaction of the richer response fields for a
//! non-maintainer query scope is the query layer's job
//! (`crates/query/src/decode/approvals.rs`), not this fold's — this fold
//! returns everything it can recover.

use polyc_crypto::approval;
use polyc_eventlog_model::Event;
use polyc_proto::kinds;

/// How an `approval_response`'s embedded signature reads.
///
/// The shared classification [`classify_response_signature`] computes, and
/// the single enum `forensics::classify_response_signature`/
/// `trace::response_signature_evidence` both now read through instead of
/// each independently re-deriving it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ApprovalSignatureStatus {
    /// Verifies against the embedded key under the current schema AND that
    /// key is a member of the deployment's trusted-signer allow-list.
    Verified,
    /// A current-schema record (carries the `tool_name` call-identity
    /// binding) whose signature does NOT verify, or verifies against a key
    /// outside the trusted-signer allow-list — a genuine tamper/forgery
    /// signal.
    Invalid,
    /// A pre-binding (call-id-only) record — carries a `request_id` but no
    /// `tool_name` — this build can no longer re-verify. Not a tamper
    /// signal, just un-reverifiable.
    LegacyUnverifiable,
}

/// Classify an `approval_response` payload's embedded signature: verified,
/// genuinely invalid, or a legacy-schema record this build no longer
/// re-verifies.
///
/// Pinned to `trusted_signers` (`#845`): a current-schema record self-signed
/// with a key that is not the deployment's own reads [`Invalid`](ApprovalSignatureStatus::Invalid),
/// not [`Verified`](ApprovalSignatureStatus::Verified) — see
/// [`polyc_crypto::approval::verify_signed_response_pinned`]. A record that
/// fails that pinned verification is then told apart from a legitimately
/// pre-binding legacy record by the same heuristic every consumer used to
/// duplicate independently: the current schema binds the call identity by
/// covering `tool_name` in the signature (`#141`/`#370`), so a payload that
/// carries a `request_id` but no `tool_name` predates that binding and was
/// never expected to re-verify under it.
#[must_use]
pub fn classify_response_signature(
    payload: &[u8],
    trusted_signers: &[Vec<u8>],
) -> ApprovalSignatureStatus {
    if approval::verify_signed_response_pinned(payload, trusted_signers).is_some() {
        return ApprovalSignatureStatus::Verified;
    }
    let is_legacy = serde_json::from_slice::<serde_json::Value>(payload)
        .ok()
        .is_some_and(|v| v.get("request_id").is_some() && v.get("tool_name").is_none());
    if is_legacy {
        ApprovalSignatureStatus::LegacyUnverifiable
    } else {
        ApprovalSignatureStatus::Invalid
    }
}

/// A decoded `approval_request` event — every field
/// [`polyc_crypto::approval::request_payload`] writes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ApprovalRequestFact {
    /// The model's tool-call id, stable for the lifetime of the turn.
    pub request_id: String,
    /// The tool being gated.
    pub tool_name: String,
    /// The proposed tool arguments, as JSON text.
    pub args_json: String,
    /// The OVERRIDE explanation for why the call is gated — empty for an
    /// ordinary gated call ([`polyc_crypto::approval::request_payload`]'s own
    /// doc).
    pub reason: String,
    /// The sandbox/permission mode the harness was running under when it
    /// paused this call.
    pub sandbox_mode: String,
}

/// A decoded `approval_response` event.
///
/// Every field the fold could recover, structurally decoded regardless of
/// whether the signature verifies (see the module docs' "Different posture"
/// section). `None` on every response-only field means the payload was the
/// pre-binding legacy shape (or otherwise failed
/// [`polyc_crypto::approval::decode_response_full`]'s full-schema decode) —
/// [`request_id`](Self::request_id), [`approved`](Self::approved), and
/// [`signature_status`](Self::signature_status) are the only fields every
/// structurally-decodable response carries.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ApprovalResponseFact {
    /// The tool-call id this response answers.
    pub request_id: String,
    /// Whether the request was approved.
    pub approved: bool,
    /// Free-form human-supplied reason, when the full schema decoded.
    pub response_reason: Option<String>,
    /// How this response's embedded signature reads — see
    /// [`ApprovalSignatureStatus`].
    pub signature_status: ApprovalSignatureStatus,
    /// The embedded signer public key, when the full schema decoded and
    /// carried a non-empty `signed_by`.
    pub signer_public_key: Option<Vec<u8>>,
    /// The approver's edit to the proposed args (empty string, not absent,
    /// when the approver did not edit), when the full schema decoded.
    pub modified_args_json: Option<String>,
    /// Whether the approval is remembered for the rest of the session,
    /// when the full schema decoded.
    pub approved_for_session: Option<bool>,
    /// The caller identity the (session) approval is scoped to, when the
    /// full schema decoded.
    pub caller: Option<String>,
    /// The identity that actually resolved this decision (`#1025`), when
    /// the full schema decoded — empty string, not absent, when no
    /// distinct approver was recorded.
    pub approver: Option<String>,
    /// The sandbox/permission mode the paused turn ran under, when the
    /// full schema decoded.
    pub sandbox_mode: Option<String>,
    /// Context the approver attached to inject before the tool runs, when
    /// the full schema decoded.
    pub injected_context: Option<String>,
    /// The bound tool name (POLY-25/POLY-33), when the full schema decoded.
    /// A response binds its own `tool_name` the same way a request does
    /// (`#141`/`#370`'s call-identity binding) — this reuses the request
    /// side's `tool_name` column rather than adding a second one.
    pub tool_name: Option<String>,
    /// Whether this response mints or revokes a routine tool grant
    /// (POLY-25), when the full schema decoded. See
    /// [`polyc_crypto::approval::VerifiedResponse::routine_grant`].
    pub routine_grant: Option<bool>,
    /// The granted tool's descriptor hash (POLY-25), when the full schema
    /// decoded — empty when [`Self::routine_grant`] is not `Some(true)`. See
    /// [`polyc_crypto::approval::VerifiedResponse::tool_descriptor_hash`].
    pub tool_descriptor_hash: Option<String>,
    /// The grant's scope (POLY-25) — `"tool"`, `"blanket_below_high"`, or
    /// `"blanket_all"` — when the full schema decoded, empty when
    /// [`Self::routine_grant`] is not `Some(true)`. See
    /// [`polyc_crypto::approval::VerifiedResponse::grant_scope`].
    pub grant_scope: Option<String>,
}

/// One event folded into either half of the approval request/response pair.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ApprovalFact {
    /// Folded from an `approval_request` event.
    Request(ApprovalRequestFact),
    /// Folded from an `approval_response` event.
    Response(ApprovalResponseFact),
}

/// Fold one event into an [`ApprovalFact`].
///
/// `None` if it is not an `approval_request`/`approval_response` event, or
/// its payload is too malformed to yield even the minimal identity a fact
/// needs (a `request_id` for either kind, plus `approved` for a response).
///
/// `approval_deferred` is deliberately OUT OF SCOPE (v1): the `/approvals`
/// endpoint this fold backs never surfaces a defer, and no pinned-verify
/// primitive exists for it (`polyc_crypto::approval::verify_deferred` is
/// unpinned) — adding it here would be fact-model plumbing with no consumer.
#[must_use]
pub fn fold_approval_event(event: &Event, trusted_signers: &[Vec<u8>]) -> Option<ApprovalFact> {
    let (base, _turn_id) = kinds::parse(&event.kind);
    if base == kinds::APPROVAL_REQUEST {
        fold_approval_request(&event.payload).map(ApprovalFact::Request)
    } else if base == kinds::APPROVAL_RESPONSE {
        fold_approval_response(&event.payload, trusted_signers).map(ApprovalFact::Response)
    } else {
        None
    }
}

/// Fold an `approval_request` payload — `None` only if
/// [`polyc_crypto::approval::decode_request_fields`] can't recover all three
/// of `request_id`/`tool_name`/`args_json` (the call-identity a v2
/// `approval_response` must sign to bind to this request).
fn fold_approval_request(payload: &[u8]) -> Option<ApprovalRequestFact> {
    let (request_id, tool_name, args_json) = approval::decode_request_fields(payload)?;
    Some(ApprovalRequestFact {
        request_id,
        tool_name,
        args_json,
        reason: approval::decode_request_reason(payload),
        sandbox_mode: approval::decode_request_sandbox_mode(payload),
    })
}

/// Fold an `approval_response` payload — `None` only if
/// [`polyc_crypto::approval::decode_response_minimal`] can't recover even
/// `request_id`+`approved` (a structurally-malformed payload). Every other
/// field comes from [`polyc_crypto::approval::decode_response_full`], which
/// requires the full current-schema field set (including `tool_name`) to
/// succeed — absent for the pre-binding legacy shape, so every
/// response-only field on the returned fact stays `None` for a legacy
/// record, matching the module docs' "Different posture" section: the row
/// is still returned (via `decode_response_minimal`), just with nothing
/// beyond its identity and classification.
fn fold_approval_response(
    payload: &[u8],
    trusted_signers: &[Vec<u8>],
) -> Option<ApprovalResponseFact> {
    let (request_id, approved) = approval::decode_response_minimal(payload)?;
    let signature_status = classify_response_signature(payload, trusted_signers);
    let full = approval::decode_response_full(payload);
    let signer_public_key = full.as_ref().and_then(|d| {
        if d.signer_pk_hex.is_empty() {
            None
        } else {
            polyc_crypto::hex::decode(&d.signer_pk_hex)
        }
    });
    Some(ApprovalResponseFact {
        request_id,
        approved,
        response_reason: full.as_ref().map(|d| d.reason.clone()),
        signature_status,
        signer_public_key,
        modified_args_json: full.as_ref().map(|d| d.modified_args_json.clone()),
        approved_for_session: full.as_ref().map(|d| d.approved_for_session),
        caller: full.as_ref().map(|d| d.caller.clone()),
        approver: full.as_ref().map(|d| d.approver.clone()),
        sandbox_mode: full.as_ref().map(|d| d.sandbox_mode.clone()),
        injected_context: full.as_ref().map(|d| d.injected_context.clone()),
        tool_name: full.as_ref().map(|d| d.tool_name.clone()),
        routine_grant: full.as_ref().map(|d| d.routine_grant),
        tool_descriptor_hash: full.as_ref().map(|d| d.tool_descriptor_hash.clone()),
        grant_scope: full.as_ref().map(|d| d.grant_scope.clone()),
    })
}

#[cfg(test)]
mod tests {
    #![allow(clippy::pedantic, clippy::nursery, missing_docs, clippy::unwrap_used)]

    use polyc_crypto::approval::{ApprovalSigner, response_payload};

    use super::*;

    fn request_event(request_id: &str, tool_name: &str, args_json: &str) -> Event {
        Event::new(
            kinds::APPROVAL_REQUEST.to_owned(),
            approval::request_payload(
                request_id,
                tool_name,
                args_json,
                "default",
                "",
                &[],
                "",
                "",
                "",
                &[],
                false,
            ),
        )
    }

    #[allow(clippy::too_many_arguments)]
    fn response_bytes(
        request_id: &str,
        tool_name: &str,
        args_json: &str,
        approved: bool,
        caller: &str,
        reason: &str,
        signer: &ApprovalSigner,
    ) -> Vec<u8> {
        response_payload(
            request_id,
            tool_name,
            args_json,
            "",
            approved,
            false,
            &[],
            caller,
            "",
            "",
            reason,
            "",
            "conv-1",
            "nonce-1",
            "",
            signer,
        )
        .0
    }

    #[test]
    fn fold_approval_event_decodes_a_request() {
        let event = request_event("call-1", "rm", r#"{"path":"/tmp"}"#);
        let fact = fold_approval_event(&event, &[]).expect("request decodes");
        match fact {
            ApprovalFact::Request(req) => {
                assert_eq!(req.request_id, "call-1");
                assert_eq!(req.tool_name, "rm");
                assert_eq!(req.args_json, r#"{"path":"/tmp"}"#);
            }
            ApprovalFact::Response(_) => panic!("expected Request"),
        }
    }

    /// The contrast with [`crate::receipts`]'s drop test: a response signed
    /// by a key OUTSIDE `trusted_signers` is internally consistent but
    /// untrusted — [`crate::receipts::verified_receipts`] would drop this,
    /// but the approval fold keeps the row, tagged `Invalid`, as the audit
    /// signal the `/approvals` surface exists to show.
    #[test]
    fn fold_approval_event_keeps_an_untrusted_signer_response_tagged_invalid() {
        let trusted = ApprovalSigner::from_seed(1);
        let untrusted = ApprovalSigner::from_seed(2);
        let bytes = response_bytes(
            "call-1",
            "rm",
            r#"{"path":"/tmp"}"#,
            true,
            "caller-1",
            "ok",
            &untrusted,
        );
        let event = Event::new(kinds::APPROVAL_RESPONSE.to_owned(), bytes);
        let fact = fold_approval_event(&event, &[trusted.public_key_bytes()])
            .expect("a structurally valid response always folds to a row");
        match fact {
            ApprovalFact::Response(resp) => {
                assert_eq!(resp.signature_status, ApprovalSignatureStatus::Invalid);
                assert!(
                    resp.approved,
                    "the row is still present with its claimed fields"
                );
                assert_eq!(resp.caller.as_deref(), Some("caller-1"));
            }
            ApprovalFact::Request(_) => panic!("expected Response"),
        }
    }

    #[test]
    fn fold_approval_event_verifies_a_trusted_signer_response() {
        let signer = ApprovalSigner::from_seed(3);
        let bytes = response_bytes(
            "call-2",
            "rm",
            r#"{"path":"/tmp"}"#,
            true,
            "caller-2",
            "ok",
            &signer,
        );
        let event = Event::new(kinds::APPROVAL_RESPONSE.to_owned(), bytes);
        let fact = fold_approval_event(&event, &[signer.public_key_bytes()]).expect("decodes");
        match fact {
            ApprovalFact::Response(resp) => {
                assert_eq!(resp.signature_status, ApprovalSignatureStatus::Verified);
                assert_eq!(
                    resp.signer_public_key.as_deref(),
                    Some(signer.public_key_bytes().as_slice())
                );
            }
            ApprovalFact::Request(_) => panic!("expected Response"),
        }
    }

    #[test]
    fn fold_approval_event_reads_a_legacy_response_with_only_identity_and_classification() {
        let legacy = br#"{"request_id":"call-3","approved":true,"reason":"ok"}"#.to_vec();
        let event = Event::new(kinds::APPROVAL_RESPONSE.to_owned(), legacy);
        let fact = fold_approval_event(&event, &[]).expect("legacy still decodes minimally");
        match fact {
            ApprovalFact::Response(resp) => {
                assert_eq!(resp.request_id, "call-3");
                assert!(resp.approved);
                assert_eq!(
                    resp.signature_status,
                    ApprovalSignatureStatus::LegacyUnverifiable
                );
                assert_eq!(resp.response_reason, None);
                assert_eq!(resp.signer_public_key, None);
                assert_eq!(resp.caller, None);
                assert_eq!(resp.tool_name, None);
                assert_eq!(resp.routine_grant, None);
                assert_eq!(resp.tool_descriptor_hash, None);
                assert_eq!(resp.grant_scope, None);
            }
            ApprovalFact::Request(_) => panic!("expected Response"),
        }
    }

    /// An ordinary (non-grant) response with the full schema decodes
    /// `routine_grant = Some(false)` and empty grant fields — `Some`, not
    /// `None`, since the full schema decoded; see the module doc's
    /// "Different posture" section.
    #[test]
    fn fold_approval_event_ordinary_response_has_no_grant_marker() {
        let signer = ApprovalSigner::from_seed(11);
        let bytes = response_bytes(
            "call-5",
            "rm",
            r#"{"path":"/tmp"}"#,
            true,
            "caller-5",
            "ok",
            &signer,
        );
        let event = Event::new(kinds::APPROVAL_RESPONSE.to_owned(), bytes);
        let fact = fold_approval_event(&event, &[signer.public_key_bytes()]).expect("decodes");
        match fact {
            ApprovalFact::Response(resp) => {
                assert_eq!(resp.tool_name.as_deref(), Some("rm"));
                assert_eq!(resp.routine_grant, Some(false));
                assert_eq!(resp.tool_descriptor_hash.as_deref(), Some(""));
                assert_eq!(resp.grant_scope.as_deref(), Some(""));
            }
            ApprovalFact::Request(_) => panic!("expected Response"),
        }
    }

    /// A `routine_grant`-marked response (POLY-25/POLY-33) decodes its
    /// marker, descriptor hash, and scope.
    #[test]
    fn fold_approval_event_decodes_a_routine_grant_response() {
        let signer = ApprovalSigner::from_seed(12);
        let (payload, ..) = polyc_crypto::approval::routine_grant_payload(
            "call-6",
            "fs_write",
            "{}",
            "",
            true,
            "owner-1",
            "",
            "default",
            "",
            &[],
            "conv-fire-1",
            "nonce-6",
            "",
            "hash-abc",
            "tool",
            &signer,
        );
        let event = Event::new(kinds::APPROVAL_RESPONSE.to_owned(), payload);
        let fact = fold_approval_event(&event, &[signer.public_key_bytes()]).expect("decodes");
        match fact {
            ApprovalFact::Response(resp) => {
                assert_eq!(resp.tool_name.as_deref(), Some("fs_write"));
                assert_eq!(resp.routine_grant, Some(true));
                assert_eq!(resp.tool_descriptor_hash.as_deref(), Some("hash-abc"));
                assert_eq!(resp.grant_scope.as_deref(), Some("tool"));
            }
            ApprovalFact::Request(_) => panic!("expected Response"),
        }
    }

    #[test]
    fn fold_approval_event_drops_a_structurally_malformed_response() {
        let event = Event::new(kinds::APPROVAL_RESPONSE.to_owned(), vec![0xFF, 0xFE]);
        assert_eq!(fold_approval_event(&event, &[]), None);
    }

    #[test]
    fn fold_approval_event_drops_a_structurally_malformed_request() {
        let event = Event::new(
            kinds::APPROVAL_REQUEST.to_owned(),
            br#"{"tool_name":"rm"}"#.to_vec(),
        );
        assert_eq!(fold_approval_event(&event, &[]), None);
    }

    #[test]
    fn fold_approval_event_ignores_unrelated_kinds() {
        let event = Event::new(kinds::USAGE.to_owned(), Vec::new());
        assert_eq!(fold_approval_event(&event, &[]), None);
    }
}