a3s-code-core 8.3.0

A3S Code Core - Embeddable AI agent library with tool execution
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
//! Bounded, digest-bound batches of reviewer findings.

use super::{
    digest, validate_digest_field, validate_id, ResearchContractError, ResearchReviewFindingV1,
    ResearchReviewStatusV1,
};
use serde::{Deserialize, Serialize};

pub const RESEARCH_REVIEW_BATCH_SCHEMA_V1: &str = "a3s.code.review-batch.v1";
pub const RESEARCH_MAX_REVIEW_FINDINGS: usize = 512;
const RESEARCH_REVIEW_BATCH_DIGEST_DOMAIN: &str = "a3s.code.review-batch.identity.v1";

/// One immutable projection of an evaluator result into bounded findings.
///
/// A batch does not define a rubric or a business decision. It only prevents
/// a host from publishing a partially mixed reviewer response: every finding
/// must belong to the same project/run, evaluation record, and evidence
/// snapshot. A batch may contain zero findings to represent a clean reviewer
/// result; the evaluator record remains the authoritative result and evidence
/// identity. Human resolution remains an explicit operation on each finding.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ResearchReviewBatchV1 {
    pub schema: String,
    pub batch_id: String,
    pub project_id: String,
    pub run_id: String,
    pub evaluation_record_digest: String,
    pub evidence_digest: String,
    pub findings: Vec<ResearchReviewFindingV1>,
    pub batch_digest: String,
}

impl ResearchReviewBatchV1 {
    /// Construct a batch against the admitted Run and exact evaluator record.
    ///
    /// The identity-only [`new`](Self::new) constructor remains available for
    /// compatibility with callers that only have wire-level digests. New
    /// reviewer pipelines should use this constructor so the project/run
    /// namespace and evaluator evidence snapshot are closed at admission. A
    /// newly admitted batch must contain only open findings; resolved or
    /// waived findings must be restored from the already-published batch and
    /// changed through the explicit transition methods below.
    pub fn new_for_run(
        batch_id: impl Into<String>,
        run: &crate::research::ResearchRunV1,
        record: &crate::evaluation::EvaluationRecordV1,
        evidence_digest: impl Into<String>,
        findings: Vec<ResearchReviewFindingV1>,
    ) -> Result<Self, ResearchContractError> {
        let batch = Self::new(
            batch_id,
            run.project_id.clone(),
            run.run_id.clone(),
            record.record_digest.clone(),
            evidence_digest,
            findings,
        )?;
        batch.validate_for_run(run, record)?;
        if batch
            .findings
            .iter()
            .any(|finding| !matches!(finding.status, ResearchReviewStatusV1::Open))
        {
            return Err(ResearchContractError::InvalidField("finding.status"));
        }
        Ok(batch)
    }

    pub fn new(
        batch_id: impl Into<String>,
        project_id: impl Into<String>,
        run_id: impl Into<String>,
        evaluation_record_digest: impl Into<String>,
        evidence_digest: impl Into<String>,
        mut findings: Vec<ResearchReviewFindingV1>,
    ) -> Result<Self, ResearchContractError> {
        findings.sort_unstable_by(|left, right| left.finding_id.cmp(&right.finding_id));
        let mut batch = Self {
            schema: RESEARCH_REVIEW_BATCH_SCHEMA_V1.to_owned(),
            batch_id: batch_id.into(),
            project_id: project_id.into(),
            run_id: run_id.into(),
            evaluation_record_digest: evaluation_record_digest.into(),
            evidence_digest: evidence_digest.into(),
            findings,
            batch_digest: String::new(),
        };
        batch.validate_without_digest()?;
        batch.batch_digest = batch.expected_digest()?;
        Ok(batch)
    }

    pub fn validate(&self) -> Result<(), ResearchContractError> {
        self.validate_without_digest()?;
        validate_digest_field("batchDigest", &self.batch_digest)?;
        if self.batch_digest != self.expected_digest()? {
            return Err(ResearchContractError::DigestMismatch("batchDigest"));
        }
        Ok(())
    }

    /// Decode a bounded JSON batch and validate every nested finding and
    /// digest before returning it to a caller at a process boundary.
    pub fn from_slice(bytes: &[u8]) -> Result<Self, ResearchContractError> {
        let batch: Self = super::decode_json_slice(bytes)?;
        batch.validate()?;
        Ok(batch)
    }

    /// Encode a validated batch for a process boundary.
    pub fn to_vec(&self) -> Result<Vec<u8>, ResearchContractError> {
        self.validate()?;
        super::encode_json(self)
    }

    /// Validate this batch against the admitted Run and exact evaluator
    /// record that the host intends to publish.
    pub fn validate_for_run(
        &self,
        run: &crate::research::ResearchRunV1,
        record: &crate::evaluation::EvaluationRecordV1,
    ) -> Result<(), ResearchContractError> {
        self.validate()?;
        run.validate_reviewable()?;
        record
            .validate()
            .map_err(|_| ResearchContractError::InvalidField("evaluationRecord"))?;
        if run.project_id != self.project_id {
            return Err(ResearchContractError::InvalidField("researchRun.projectId"));
        }
        if run.run_id != self.run_id {
            return Err(ResearchContractError::InvalidField("researchRun.runId"));
        }
        if record.record_digest != self.evaluation_record_digest {
            return Err(ResearchContractError::InvalidField(
                "evaluationRecord.recordDigest",
            ));
        }
        if record.result.target.run_id != run.run_id {
            return Err(ResearchContractError::InvalidField(
                "evaluationRecord.target.runId",
            ));
        }
        if record.result.evidence_digest != run.evidence_snapshot_digest {
            return Err(ResearchContractError::InvalidField(
                "evaluationRecord.evidenceDigest",
            ));
        }
        if record.result.evidence_digest != self.evidence_digest {
            return Err(ResearchContractError::InvalidField(
                "evaluationRecord.evidenceDigest",
            ));
        }
        for finding in &self.findings {
            if finding.evaluator_id != record.result.evaluator_id {
                return Err(ResearchContractError::InvalidField("finding.evaluatorId"));
            }
        }
        Ok(())
    }

    /// Resolve one finding and rebind the batch identity atomically.
    pub fn resolve_finding(
        &mut self,
        finding_id: &str,
        resolution_digest: impl Into<String>,
    ) -> Result<(), ResearchContractError> {
        self.validate()?;
        let finding = self
            .findings
            .iter_mut()
            .find(|finding| finding.finding_id == finding_id)
            .ok_or(ResearchContractError::InvalidField("findingId"))?;
        finding.resolve(resolution_digest)?;
        self.batch_digest = self.expected_digest()?;
        self.validate()
    }

    /// Waive one finding and rebind the batch identity atomically.
    pub fn waive_finding(
        &mut self,
        finding_id: &str,
        resolution_digest: impl Into<String>,
    ) -> Result<(), ResearchContractError> {
        self.validate()?;
        let finding = self
            .findings
            .iter_mut()
            .find(|finding| finding.finding_id == finding_id)
            .ok_or(ResearchContractError::InvalidField("findingId"))?;
        finding.waive(resolution_digest)?;
        self.batch_digest = self.expected_digest()?;
        self.validate()
    }

    fn validate_without_digest(&self) -> Result<(), ResearchContractError> {
        if self.schema != RESEARCH_REVIEW_BATCH_SCHEMA_V1 {
            return Err(ResearchContractError::UnsupportedSchema);
        }
        validate_id("batchId", &self.batch_id)?;
        validate_id("projectId", &self.project_id)?;
        validate_id("runId", &self.run_id)?;
        validate_digest_field("evaluationRecordDigest", &self.evaluation_record_digest)?;
        validate_digest_field("evidenceDigest", &self.evidence_digest)?;
        if self.findings.len() > RESEARCH_MAX_REVIEW_FINDINGS {
            return Err(ResearchContractError::InvalidField("findings"));
        }
        for pair in self.findings.windows(2) {
            if pair[0].finding_id >= pair[1].finding_id {
                return Err(ResearchContractError::InvalidField("findings"));
            }
        }
        for finding in &self.findings {
            finding.validate()?;
            if finding.project_id != self.project_id || finding.run_id != self.run_id {
                return Err(ResearchContractError::InvalidField("finding.identity"));
            }
            if finding.evaluation_record_digest.as_deref()
                != Some(self.evaluation_record_digest.as_str())
            {
                return Err(ResearchContractError::InvalidField(
                    "finding.evaluationRecordDigest",
                ));
            }
            if finding
                .evidence_digests
                .binary_search(&self.evidence_digest)
                .is_err()
            {
                return Err(ResearchContractError::InvalidField(
                    "finding.evidenceDigest",
                ));
            }
        }
        Ok(())
    }

    fn expected_digest(&self) -> Result<String, ResearchContractError> {
        #[derive(Serialize)]
        struct Identity<'a> {
            schema: &'a str,
            batch_id: &'a str,
            project_id: &'a str,
            run_id: &'a str,
            evaluation_record_digest: &'a str,
            evidence_digest: &'a str,
            findings: &'a [ResearchReviewFindingV1],
        }
        digest(
            RESEARCH_REVIEW_BATCH_DIGEST_DOMAIN,
            &Identity {
                schema: &self.schema,
                batch_id: &self.batch_id,
                project_id: &self.project_id,
                run_id: &self.run_id,
                evaluation_record_digest: &self.evaluation_record_digest,
                evidence_digest: &self.evidence_digest,
                findings: &self.findings,
            },
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::evaluation::{EvaluationRecordV1, EvaluationResultV1, ExecutionTargetV1};
    use crate::research::{
        ResearchReviewCategoryV1, ResearchReviewSeverityV1, ResearchReviewStatusV1,
    };

    fn digest(ch: char) -> String {
        format!("sha256:{}", ch.to_string().repeat(64))
    }

    fn finding(id: &str, record: &EvaluationRecordV1) -> ResearchReviewFindingV1 {
        ResearchReviewFindingV1::new(
            id,
            "project-1",
            "run-1",
            digest('a'),
            ResearchReviewCategoryV1::Citation,
            ResearchReviewSeverityV1::Warning,
            "citation needs review",
            None,
            vec![record.result.evidence_digest.clone()],
            record.result.evaluator_id.clone(),
            3,
        )
        .unwrap()
        .bind_evaluation_record(record)
        .unwrap()
    }

    fn record() -> EvaluationRecordV1 {
        EvaluationRecordV1::new(
            EvaluationResultV1::new(
                "reviewer",
                ExecutionTargetV1::new("session-1", "run-1"),
                "aux-1",
                "needs_review",
                serde_json::json!({"finding_count": 2}),
                digest('b'),
            )
            .unwrap(),
            2,
        )
        .unwrap()
    }

    #[test]
    fn batch_sorts_findings_and_keeps_human_decisions_explicit() {
        let record = record();
        let mut batch = ResearchReviewBatchV1::new(
            "batch-1",
            "project-1",
            "run-1",
            record.record_digest.clone(),
            record.result.evidence_digest.clone(),
            vec![finding("finding-2", &record), finding("finding-1", &record)],
        )
        .unwrap();
        assert_eq!(batch.findings[0].finding_id, "finding-1");
        assert!(batch
            .findings
            .iter()
            .all(|finding| finding.status == ResearchReviewStatusV1::Open));
        let before = batch.batch_digest.clone();
        batch.resolve_finding("finding-1", digest('c')).unwrap();
        assert_ne!(before, batch.batch_digest);
        assert!(batch.validate().is_ok());
    }

    #[test]
    fn batch_rejects_mixed_run_or_evidence_and_tampering() {
        let record = record();
        let other_run_record = EvaluationRecordV1::new(
            EvaluationResultV1::new(
                "reviewer",
                ExecutionTargetV1::new("session-2", "run-2"),
                "aux-2",
                "needs_review",
                serde_json::json!({"finding_count": 1}),
                digest('b'),
            )
            .unwrap(),
            2,
        )
        .unwrap();
        let mixed = ResearchReviewFindingV1::new(
            "finding-1",
            "project-1",
            "run-2",
            digest('a'),
            ResearchReviewCategoryV1::Citation,
            ResearchReviewSeverityV1::Warning,
            "citation needs review",
            None,
            vec![other_run_record.result.evidence_digest.clone()],
            "reviewer",
            3,
        )
        .unwrap()
        .bind_evaluation_record(&other_run_record)
        .unwrap();
        assert_eq!(
            ResearchReviewBatchV1::new(
                "batch-1",
                "project-1",
                "run-1",
                record.record_digest.clone(),
                record.result.evidence_digest.clone(),
                vec![mixed],
            ),
            Err(ResearchContractError::InvalidField("finding.identity"))
        );

        let mut other = finding("finding-1", &record);
        other.run_id = "run-2".to_owned();
        assert!(matches!(
            ResearchReviewBatchV1::new(
                "batch-1",
                "project-1",
                "run-1",
                record.record_digest.clone(),
                record.result.evidence_digest.clone(),
                vec![other],
            ),
            Err(ResearchContractError::DigestMismatch("findingDigest"))
        ));

        let mut batch = ResearchReviewBatchV1::new(
            "batch-1",
            "project-1",
            "run-1",
            record.record_digest.clone(),
            record.result.evidence_digest.clone(),
            vec![finding("finding-1", &record)],
        )
        .unwrap();
        batch.findings[0].message = "tampered".to_owned();
        assert_eq!(
            batch.validate(),
            Err(ResearchContractError::DigestMismatch("findingDigest"))
        );
    }

    #[test]
    fn empty_batch_represents_a_clean_review_result() {
        let record = record();
        let batch = ResearchReviewBatchV1::new(
            "clean-batch",
            "project-1",
            "run-1",
            record.record_digest.clone(),
            record.result.evidence_digest.clone(),
            Vec::new(),
        )
        .unwrap();

        assert!(batch.findings.is_empty());
        assert!(batch.validate().is_ok());
    }

    #[test]
    fn batch_round_trip_is_strict_and_tamper_evident() {
        let record = record();
        let batch = ResearchReviewBatchV1::new(
            "wire-batch",
            "project-1",
            "run-1",
            record.record_digest.clone(),
            record.result.evidence_digest.clone(),
            vec![finding("finding-1", &record)],
        )
        .unwrap();

        let encoded = batch.to_vec().unwrap();
        let reopened = ResearchReviewBatchV1::from_slice(&encoded).unwrap();
        assert_eq!(reopened, batch);
        assert!(reopened.validate().is_ok());

        let mut with_unknown_field: serde_json::Value = serde_json::from_slice(&encoded).unwrap();
        with_unknown_field["unexpected"] = serde_json::Value::Bool(true);
        let with_unknown_field = serde_json::to_vec(&with_unknown_field).unwrap();
        assert!(ResearchReviewBatchV1::from_slice(&with_unknown_field).is_err());

        let mut tampered = reopened;
        tampered.findings[0].message = "changed after publication".to_owned();
        assert_eq!(
            tampered.validate(),
            Err(ResearchContractError::DigestMismatch("findingDigest"))
        );
    }

    #[test]
    fn closed_batch_round_trip_preserves_terminal_finding_state() {
        let record = record();
        let mut resolved = ResearchReviewBatchV1::new(
            "resolved-wire-batch",
            "project-1",
            "run-1",
            record.record_digest.clone(),
            record.result.evidence_digest.clone(),
            vec![finding("finding-1", &record)],
        )
        .unwrap();
        resolved.resolve_finding("finding-1", digest('c')).unwrap();
        let reopened: ResearchReviewBatchV1 =
            serde_json::from_slice(&serde_json::to_vec(&resolved).unwrap()).unwrap();
        assert_eq!(reopened, resolved);
        assert_eq!(
            reopened.findings[0].status,
            ResearchReviewStatusV1::Resolved
        );
        assert!(reopened.validate().is_ok());
        assert_eq!(
            reopened.clone().resolve_finding("finding-1", digest('d')),
            Err(ResearchContractError::InvalidTransition {
                from: "resolved",
                to: "resolved"
            })
        );
        assert_eq!(
            reopened.clone().waive_finding("finding-1", digest('e')),
            Err(ResearchContractError::InvalidTransition {
                from: "resolved",
                to: "waived"
            })
        );

        let mut waived = ResearchReviewBatchV1::new(
            "waived-wire-batch",
            "project-1",
            "run-1",
            record.record_digest.clone(),
            record.result.evidence_digest.clone(),
            vec![finding("finding-2", &record)],
        )
        .unwrap();
        waived.waive_finding("finding-2", digest('f')).unwrap();
        let mut reopened: ResearchReviewBatchV1 =
            serde_json::from_slice(&serde_json::to_vec(&waived).unwrap()).unwrap();
        assert_eq!(reopened, waived);
        assert_eq!(reopened.findings[0].status, ResearchReviewStatusV1::Waived);
        assert!(reopened.validate().is_ok());
        assert_eq!(
            reopened.resolve_finding("finding-2", digest('1')),
            Err(ResearchContractError::InvalidTransition {
                from: "waived",
                to: "resolved"
            })
        );
    }
}