pointbreak 0.6.0

Durable terminal code review for changes humans and coding agents collaborate on together
Documentation
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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
use serde::{Deserialize, Serialize};

use super::kind::EventType;
use super::payload::{BodyContentType, EventPayload};
use super::type_code::type_code;
use crate::error::{Result, ShoreError};
use crate::model::{
    InputRequestId, InputRequestResponseId, ReviewTargetRef, RevisionId, TaskTargetRef, TrackId,
    WorkObjectId, WorkObjectType,
};

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum InputRequestReasonCode {
    AmbiguousState,
    UnsafeAction,
    StaleRevision,
    FailedGate,
    ExternalSideEffect,
    ConflictingEvent,
    MissingPermission,
    ManualDecisionRequired,
    InsufficientEvidence,
}

/// Every `InputRequestReasonCode` variant, in declaration order. Mirrors
/// `EventType::ALL`: the vocabulary round-trips are pinned in one place and a new
/// variant fails compilation until it is appended here and to the exhaustive match
/// below. Test-only, so the guard never ships in the production binary.
#[cfg(test)]
impl InputRequestReasonCode {
    pub(crate) const ALL: [InputRequestReasonCode; 9] = [
        Self::AmbiguousState,
        Self::UnsafeAction,
        Self::StaleRevision,
        Self::FailedGate,
        Self::ExternalSideEffect,
        Self::ConflictingEvent,
        Self::MissingPermission,
        Self::ManualDecisionRequired,
        Self::InsufficientEvidence,
    ];
}

/// Adding an `InputRequestReasonCode` variant breaks this match until the variant
/// is also appended to [`InputRequestReasonCode::ALL`]. Invoked from the tests so
/// it carries no runtime cost and trips no dead-code lint.
#[cfg(test)]
fn assert_reason_code_all_is_exhaustive(code: InputRequestReasonCode) {
    match code {
        InputRequestReasonCode::AmbiguousState
        | InputRequestReasonCode::UnsafeAction
        | InputRequestReasonCode::StaleRevision
        | InputRequestReasonCode::FailedGate
        | InputRequestReasonCode::ExternalSideEffect
        | InputRequestReasonCode::ConflictingEvent
        | InputRequestReasonCode::MissingPermission
        | InputRequestReasonCode::ManualDecisionRequired
        | InputRequestReasonCode::InsufficientEvidence => {}
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum InputRequestResponseOutcome {
    Approved,
    Rejected,
    Dismissed,
    Superseded,
    Abandoned,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct InputRequestOpenedPayload {
    pub input_request_id: InputRequestId,
    pub target: ReviewTargetRef,
    /// The task subject this request addresses (a task attempt or a checkpoint
    /// under it), when it is a task-domain request. Absent for the review-domain
    /// path (whose subject is `target`). The signed envelope carries only an
    /// opaque `subjectId`, so the full task subject a task-domain request
    /// addresses must live here; a review-shaped `target` alone cannot represent
    /// a task subject, and the attempt-vs-checkpoint distinction is load-bearing
    /// for agent-resumption freshness.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub task_target: Option<TaskTargetRef>,
    pub reason_code: InputRequestReasonCode,
    pub title: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub body: Option<String>,
    #[serde(default, skip_serializing_if = "BodyContentType::is_text_plain")]
    pub body_content_type: BodyContentType,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub body_artifact_path: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub body_byte_size: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub body_content_hash: Option<String>,
    /// Opaque fingerprint of the code state the requester observed when
    /// opening this input request. Compared as a string by downstream
    /// freshness rules; carries no semantics beyond `==` equality.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target_fingerprint: Option<String>,
}

pub(crate) fn decode_input_request_opened_payload(
    value: serde_json::Value,
) -> Result<InputRequestOpenedPayload> {
    if value.get("mode").is_some() {
        return Err(ShoreError::InvalidEvent {
            message: "input_request_opened payload mode is no longer supported; use envelope assertionMode"
                .to_owned(),
        });
    }

    Ok(serde_json::from_value(value)?)
}

impl InputRequestOpenedPayload {
    // The two idempotency-key constructors materialize one shared pattern:
    // `<type-code>:<work-object-identity-in-domain-appropriate-form>:<source_key>`.
    // Review-domain identity is `(revision_id, track_id)`; task-domain is the
    // domain-prefixed `work_object_id` (self-disambiguating, so no kind tag). Two
    // serializations of one pattern -- callers pick the constructor that matches
    // their work-object kind.

    pub fn idempotency_key(
        revision_id: &RevisionId,
        track_id: &TrackId,
        source_key: &str,
    ) -> String {
        format!(
            "{}:{}:{}:{}",
            type_code(EventType::InputRequestOpened),
            revision_id.as_str(),
            track_id.as_str(),
            source_key
        )
    }

    pub fn idempotency_key_for_work_object(
        work_object_id: &WorkObjectId,
        _work_object_type: WorkObjectType,
        source_key: &str,
    ) -> String {
        format!(
            "{}:{}:{}",
            type_code(EventType::InputRequestOpened),
            work_object_id.as_str(),
            source_key
        )
    }
}

impl EventPayload for InputRequestOpenedPayload {
    fn event_type(&self) -> EventType {
        EventType::InputRequestOpened
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct InputRequestRespondedPayload {
    pub input_request_response_id: InputRequestResponseId,
    pub input_request_id: InputRequestId,
    /// The revision the answered request addresses, threaded onto the payload so
    /// the review-domain subject is reconstructable without re-reading the
    /// opened request's envelope (the signed envelope now carries only an opaque
    /// `subjectId`). Absent for a task-domain response, whose subject is the
    /// parent task attempt (`work_object_id`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub revision_id: Option<RevisionId>,
    /// The task subject a task-domain response addresses (attempt or checkpoint),
    /// mirroring [`InputRequestOpenedPayload::task_target`]. Absent for the
    /// review-domain path (whose subject is `revision_id`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub task_target: Option<TaskTargetRef>,
    pub outcome: InputRequestResponseOutcome,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    #[serde(default, skip_serializing_if = "BodyContentType::is_text_plain")]
    pub reason_content_type: BodyContentType,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason_artifact_path: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason_byte_size: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason_content_hash: Option<String>,
    /// Opaque fingerprint of the code state the responder acted on. Compared
    /// as a string against the latest checkpoint's `checkpoint_fingerprint`
    /// by the agent-resumption projection; mismatch marks the resolution
    /// stale even when its target identity matches the latest checkpoint.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target_fingerprint: Option<String>,
}

impl InputRequestRespondedPayload {
    pub fn idempotency_key(input_request_id: &InputRequestId, source_key: &str) -> String {
        format!(
            "{}:{}:{}",
            type_code(EventType::InputRequestResponded),
            input_request_id.as_str(),
            source_key
        )
    }
}

impl EventPayload for InputRequestRespondedPayload {
    fn event_type(&self) -> EventType {
        EventType::InputRequestResponded
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::canonical_hash::{sha256_bytes_hex, sha256_json_prefixed};
    use crate::model::{JournalId, WorkObjectId, WorkObjectType};
    use crate::session::event::{EventTarget, ShoreEvent, Writer};

    #[test]
    fn reason_code_all_is_exhaustive_and_round_trips() {
        // Nine variants after the insufficient-evidence addition.
        assert_eq!(InputRequestReasonCode::ALL.len(), 9);
        // Uniqueness: a duplicated ALL entry must not hide an omitted variant.
        let unique: std::collections::BTreeSet<String> = InputRequestReasonCode::ALL
            .iter()
            .map(|code| serde_json::to_string(code).expect("serialize"))
            .collect();
        assert_eq!(unique.len(), InputRequestReasonCode::ALL.len());
        for code in InputRequestReasonCode::ALL {
            // Invoking the helper here is what keeps it exercised (no dead-code lint)
            // and makes a new variant fail compilation until both ALL and the match grow.
            assert_reason_code_all_is_exhaustive(code);
            let value = serde_json::to_value(code).expect("serialize");
            let parsed: InputRequestReasonCode =
                serde_json::from_value(value).expect("deserialize");
            assert_eq!(parsed, code);
        }
    }

    #[test]
    fn insufficient_evidence_reason_code_round_trips_on_the_wire() {
        let value = serde_json::to_value(InputRequestReasonCode::InsufficientEvidence)
            .expect("serialize reason code");
        assert_eq!(value, serde_json::json!("insufficient_evidence"));

        let parsed: InputRequestReasonCode =
            serde_json::from_value(serde_json::json!("insufficient_evidence"))
                .expect("deserialize reason code");
        assert_eq!(parsed, InputRequestReasonCode::InsufficientEvidence);
    }

    #[test]
    fn input_request_opened_idempotency_key_uses_new_review_domain_prefix() {
        let key = InputRequestOpenedPayload::idempotency_key(
            &RevisionId::new("ru-1"),
            &TrackId::new("human:kevin"),
            "source-1",
        );
        assert_eq!(
            key,
            format!(
                "{}:ru-1:human:kevin:source-1",
                type_code(EventType::InputRequestOpened)
            )
        );
    }

    #[test]
    fn input_request_opened_idempotency_key_for_work_object_uses_new_prefix() {
        let key = InputRequestOpenedPayload::idempotency_key_for_work_object(
            &WorkObjectId::new("task-attempt:sha256:abc"),
            WorkObjectType::TaskAttempt,
            "source-1",
        );
        assert_eq!(
            key,
            format!(
                "{}:task-attempt:sha256:abc:source-1",
                type_code(EventType::InputRequestOpened)
            )
        );
        assert!(
            !key.contains("task_attempt"),
            "the renamable kind discriminator must be dropped, got {key}"
        );
    }

    #[test]
    fn input_request_response_idempotency_key_uses_new_prefix() {
        let key = InputRequestRespondedPayload::idempotency_key(
            &InputRequestId::new("input-request:sha256:abc"),
            "response-source",
        );
        assert_eq!(
            key,
            format!(
                "{}:input-request:sha256:abc:response-source",
                type_code(EventType::InputRequestResponded)
            )
        );
    }

    #[test]
    fn idempotency_key_constructors_do_not_collide_on_shared_source_key() {
        let review = InputRequestOpenedPayload::idempotency_key(
            &RevisionId::new("shared"),
            &TrackId::new("track-a"),
            "source-1",
        );
        let task = InputRequestOpenedPayload::idempotency_key_for_work_object(
            &WorkObjectId::new("shared"),
            WorkObjectType::TaskAttempt,
            "source-1",
        );
        assert_ne!(review, task);
    }

    #[test]
    fn input_request_opened_payload_no_longer_serializes_mode() {
        let payload = opened_input_request_payload();
        let json = serde_json::to_value(&payload).unwrap();

        assert!(json.get("mode").is_none(), "{json}");
    }

    #[test]
    fn legacy_input_request_payload_mode_is_rejected() {
        let legacy = serde_json::json!({
            "inputRequestId": "input-request:sha256:abc",
            "target": {
                "kind": "review_unit",
                "reviewUnitId": "review-unit:sha256:ru"
            },
            "mode": "blocking",
            "reasonCode": "manual_decision_required",
            "title": "legacy"
        });

        let error = decode_input_request_opened_payload(legacy).unwrap_err();

        assert!(
            error
                .to_string()
                .contains("payload mode is no longer supported")
        );
    }

    #[test]
    fn input_request_opened_payload_skips_target_fingerprint_when_none() {
        let payload = opened_input_request_payload();
        let json = serde_json::to_value(&payload).unwrap();
        assert!(json.get("targetFingerprint").is_none());
    }

    #[test]
    fn input_request_opened_payload_round_trips_target_fingerprint() {
        let fp =
            "sha256:000000000000000000000000000000000000000000000000000000000000000b".to_owned();
        let payload = InputRequestOpenedPayload {
            target_fingerprint: Some(fp.clone()),
            ..opened_input_request_payload()
        };
        let json = serde_json::to_value(&payload).unwrap();
        assert_eq!(json["targetFingerprint"], fp);
        let round: InputRequestOpenedPayload = serde_json::from_value(json).unwrap();
        assert_eq!(round, payload);
    }

    #[test]
    fn input_request_responded_payload_skips_target_fingerprint_when_none() {
        let payload = InputRequestRespondedPayload {
            input_request_response_id: InputRequestResponseId::new(
                "input-request-response:sha256:r",
            ),
            input_request_id: InputRequestId::new("input-request:sha256:abc"),
            revision_id: None,
            task_target: None,
            outcome: InputRequestResponseOutcome::Approved,
            reason: None,
            reason_content_type: Default::default(),
            reason_artifact_path: None,
            reason_byte_size: None,
            reason_content_hash: None,
            target_fingerprint: None,
        };
        let json = serde_json::to_value(&payload).unwrap();
        assert!(json.get("targetFingerprint").is_none());
    }

    #[test]
    fn input_request_responded_payload_round_trips_target_fingerprint() {
        let fp =
            "sha256:000000000000000000000000000000000000000000000000000000000000000c".to_owned();
        let payload = InputRequestRespondedPayload {
            input_request_response_id: InputRequestResponseId::new(
                "input-request-response:sha256:r",
            ),
            input_request_id: InputRequestId::new("input-request:sha256:abc"),
            revision_id: None,
            task_target: None,
            outcome: InputRequestResponseOutcome::Approved,
            reason: None,
            reason_content_type: Default::default(),
            reason_artifact_path: None,
            reason_byte_size: None,
            reason_content_hash: None,
            target_fingerprint: Some(fp.clone()),
        };
        let json = serde_json::to_value(&payload).unwrap();
        assert_eq!(json["targetFingerprint"], fp);
        let round: InputRequestRespondedPayload = serde_json::from_value(json).unwrap();
        assert_eq!(round, payload);
    }

    #[test]
    fn input_request_opened_event_hashes_pin_new_wire_shape() {
        let revision_id = RevisionId::new("review-unit:sha256:unit");
        let track_id = TrackId::new("human:kevin");
        let target = ReviewTargetRef::Revision {
            revision_id: revision_id.clone(),
        };
        let payload = InputRequestOpenedPayload {
            input_request_id: InputRequestId::new("input-request:sha256:abc"),
            target: target.clone(),
            task_target: None,
            reason_code: InputRequestReasonCode::ManualDecisionRequired,
            title: "Need a decision".to_owned(),
            body: Some("Which path should win?".to_owned()),
            body_content_type: Default::default(),
            body_artifact_path: None,
            body_byte_size: Some(22),
            body_content_hash: Some("sha256:body".to_owned()),
            target_fingerprint: None,
        };
        let idempotency_key =
            InputRequestOpenedPayload::idempotency_key(&revision_id, &track_id, "source-1");

        let event = ShoreEvent::new(
            EventType::InputRequestOpened,
            idempotency_key.clone(),
            EventTarget::for_revision(
                JournalId::new("journal:default"),
                revision_id.clone(),
                Some(track_id.clone()),
            )
            .unwrap(),
            Writer::shore_local("test"),
            payload,
            "2026-05-20T00:00:00Z",
        )
        .unwrap();

        assert_eq!(
            event.event_id.as_str(),
            format!(
                "evt:sha256:{}",
                sha256_bytes_hex(idempotency_key.as_bytes())
            )
        );
        assert_eq!(
            event.payload_hash,
            sha256_json_prefixed(&serde_json::json!({
                "inputRequestId": "input-request:sha256:abc",
                "target": target,
                "reasonCode": "manual_decision_required",
                "title": "Need a decision",
                "body": "Which path should win?",
                "bodyByteSize": 22,
                "bodyContentHash": "sha256:body"
            }))
            .unwrap()
        );
        assert!(event.payload.get("interventionId").is_none());
        assert_eq!(event.payload["inputRequestId"], "input-request:sha256:abc");

        let legacy_payload_hash = sha256_json_prefixed(&serde_json::json!({
            "interventionId": "intervention:sha256:abc",
            "target": target,
            "mode": "blocking",
            "reasonCode": "manual_decision_required",
            "title": "Need a decision",
            "body": "Which path should win?",
            "bodyByteSize": 22,
            "bodyContentHash": "sha256:body"
        }))
        .unwrap();
        assert_ne!(event.payload_hash, legacy_payload_hash);
    }

    #[test]
    fn input_request_responded_event_hashes_pin_new_wire_shape() {
        let payload = InputRequestRespondedPayload {
            input_request_response_id: InputRequestResponseId::new(
                "input-request-response:sha256:def",
            ),
            input_request_id: InputRequestId::new("input-request:sha256:abc"),
            revision_id: None,
            task_target: None,
            outcome: InputRequestResponseOutcome::Approved,
            reason: Some("Approved locally".to_owned()),
            reason_content_type: Default::default(),
            reason_artifact_path: None,
            reason_byte_size: Some(16),
            reason_content_hash: Some("sha256:reason".to_owned()),
            target_fingerprint: None,
        };
        let idempotency_key = InputRequestRespondedPayload::idempotency_key(
            &InputRequestId::new("input-request:sha256:abc"),
            "response-source",
        );

        let event = ShoreEvent::new(
            EventType::InputRequestResponded,
            idempotency_key.clone(),
            EventTarget::for_revision(
                JournalId::new("journal:default"),
                RevisionId::new("review-unit:sha256:unit"),
                None,
            )
            .unwrap(),
            Writer::shore_local("test"),
            payload,
            "2026-05-20T00:00:01Z",
        )
        .unwrap();

        assert_eq!(
            event.event_id.as_str(),
            format!(
                "evt:sha256:{}",
                sha256_bytes_hex(idempotency_key.as_bytes())
            )
        );
        assert_eq!(
            event.payload_hash,
            sha256_json_prefixed(&serde_json::json!({
                "inputRequestResponseId": "input-request-response:sha256:def",
                "inputRequestId": "input-request:sha256:abc",
                "outcome": "approved",
                "reason": "Approved locally",
                "reasonByteSize": 16,
                "reasonContentHash": "sha256:reason"
            }))
            .unwrap()
        );
        assert!(event.payload.get("interventionResolutionId").is_none());
        assert_eq!(
            event.payload["inputRequestResponseId"],
            "input-request-response:sha256:def"
        );
    }

    fn opened_input_request_payload() -> InputRequestOpenedPayload {
        InputRequestOpenedPayload {
            input_request_id: InputRequestId::new("input-request:sha256:abc"),
            target: ReviewTargetRef::Revision {
                revision_id: RevisionId::new("ru-1"),
            },
            task_target: None,
            reason_code: InputRequestReasonCode::ManualDecisionRequired,
            title: "t".to_owned(),
            body: None,
            body_content_type: Default::default(),
            body_artifact_path: None,
            body_byte_size: None,
            body_content_hash: None,
            target_fingerprint: None,
        }
    }
}