artifactize 0.10.1

The AI-native collaboration layer for one-of-a-kind teammates and their agents: split a project into Artifacts with their own evals, and reuse every review while it still holds.
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
//! Validated identities and persisted states. Their wire representations stay strings.

use rusqlite::types::{FromSql, FromSqlError, FromSqlResult, ToSql, ToSqlOutput, ValueRef};
use serde::{Deserialize, Serialize};
use sha2::Digest;
use std::{borrow::Borrow, fmt, ops::Deref, str::FromStr};

mod timestamp;
pub use timestamp::Timestamp;

/// Bound external identities and saved session path segments, including pre-UUID sessions.
pub(crate) const MAX_ID_BYTES: usize = 200;
/// Bound provider-controlled SSE item identifiers retained by the delivery tap;
/// 1 KiB accommodates opaque IDs without allowing unbounded per-block memory.
pub(crate) const ITEM_ID_BYTES: usize = 1024;
/// 128 bits of randomness, lowercase hex-encoded: the length of a Codex OAuth `state`.
const OAUTH_STATE_HEX_BYTES: usize = 32;
/// Mirrors retain the remote wire identity verbatim under this local-only namespace.
const REMOTE_EXECUTION_PREFIX: &str = "remote-";
/// Bound script output and reuse-key components without requiring a cryptographic digest.
pub(crate) const MAX_FINGERPRINT_BYTES: usize = 128;
pub(crate) use artifactize_tools::MAX_SAFE_JSON_INTEGER;
/// A SHA-256 digest has 32 bytes, encoded as 64 lowercase hexadecimal ASCII bytes
/// in reuse keys and remote definition hashes; this wire width is not a storage limit.
pub(crate) const SHA256_HEX_BYTES: usize = 64;
/// Eight digest bytes retain compact diagnostic manifests without changing wire width.
const DIGEST_PREFIX_HEX_BYTES: usize = 16;
/// Principal labels are bounded ASCII display identities, never bearer secrets.
const MAX_TOKEN_NAME_BYTES: usize = 64;

fn segment(value: &str) -> bool {
    (1..=MAX_ID_BYTES).contains(&value.len())
        && value.bytes().any(|byte| byte != b'.')
        && value
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.'))
}

macro_rules! identity {
    ($name:ident, $valid:expr) => {
        identity!($name, $valid, |value: &str| format!(
            "Invalid {}: {value:?}.",
            stringify!($name)
        ));
    };
    ($name:ident, $valid:expr, $error:expr) => {
        #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
        #[serde(try_from = "String")]
        pub struct $name(String);
        impl TryFrom<String> for $name {
            type Error = String;
            fn try_from(value: String) -> Result<Self, Self::Error> {
                if ($valid)(&value) {
                    Ok(Self(value))
                } else {
                    Err(($error)(&value))
                }
            }
        }
        impl FromStr for $name {
            type Err = String;
            fn from_str(value: &str) -> Result<Self, Self::Err> {
                Self::try_from(value.to_owned())
            }
        }
        impl From<$name> for String {
            fn from(value: $name) -> Self {
                value.0
            }
        }
        impl $name {
            pub fn as_str(&self) -> &str {
                &self.0
            }
        }
        impl Deref for $name {
            type Target = str;
            fn deref(&self) -> &str {
                &self.0
            }
        }
        impl AsRef<str> for $name {
            fn as_ref(&self) -> &str {
                &self.0
            }
        }
        impl Borrow<str> for $name {
            fn borrow(&self) -> &str {
                &self.0
            }
        }
        impl fmt::Display for $name {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                self.0.fmt(f)
            }
        }
        impl PartialEq<str> for $name {
            fn eq(&self, other: &str) -> bool {
                self.0 == other
            }
        }
        impl PartialEq<&str> for $name {
            fn eq(&self, other: &&str) -> bool {
                self.0 == *other
            }
        }
        impl PartialEq<String> for $name {
            fn eq(&self, other: &String) -> bool {
                &self.0 == other
            }
        }
        impl PartialEq<$name> for String {
            fn eq(&self, other: &$name) -> bool {
                *self == other.0
            }
        }
        impl PartialEq<$name> for str {
            fn eq(&self, other: &$name) -> bool {
                self == other.0
            }
        }
        impl PartialEq<$name> for &str {
            fn eq(&self, other: &$name) -> bool {
                *self == other.0
            }
        }
        impl Borrow<String> for $name {
            fn borrow(&self) -> &String {
                &self.0
            }
        }
        impl ToSql for $name {
            fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
                self.0.to_sql()
            }
        }
        impl FromSql for $name {
            fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
                value
                    .as_str()?
                    .parse()
                    .map_err(|error: String| FromSqlError::Other(error.into()))
            }
        }
    };
}
/// An Artifact name or a local Eval id: `[A-Za-z0-9][A-Za-z0-9_-]{0,63}`.
fn name(value: &str) -> bool {
    crate::config::identifier(value, "").is_ok()
}

identity!(ArtifactName, name);
// A workspace-qualified Eval id: the Artifact name, `/`, and the Eval's local id.
identity!(EvalId, |value: &str| value
    .split_once('/')
    .is_some_and(|(artifact, eval)| name(artifact) && name(eval)));
identity!(RunId, segment);
identity!(RequestId, segment);
// Stored mirrors predate typed identities and can be 207 bytes: the unchanged
// `remote-` prefix plus a maximum-length 200-byte wire identity. Only that
// namespace gets the larger bound; all other identities retain their wire limit.
identity!(ExecutionId, |value: &str| segment(value)
    || value
        .strip_prefix(REMOTE_EXECUTION_PREFIX)
        .is_some_and(segment));
impl ExecutionId {
    /// Wire publications never get the extra local mirror namespace allowance.
    pub(crate) fn valid_wire(&self) -> bool {
        segment(self.as_str())
    }

    pub(crate) fn remote_mirror(&self) -> Result<Self, String> {
        if !self.valid_wire() {
            return Err("A remote execution ID exceeds the wire identity bound.".into());
        }
        format!("{REMOTE_EXECUTION_PREFIX}{self}").parse()
    }
}
identity!(SessionId, segment);
identity!(Fingerprint, |value: &str| (1..=MAX_FINGERPRINT_BYTES)
    .contains(&value.len())
    && value.bytes().all(
        |byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b':' | b'-')
    ));
/// Lowercase hexadecimal SHA-256: what reuse keys and definition hashes are.
fn sha256_hex(value: &str) -> bool {
    value.len() == SHA256_HEX_BYTES
        && value
            .bytes()
            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
}

// A provider's own opaque identifier for one SSE reasoning-summary item, validated once
// where it is decoded (`llm::delivery`) rather than carried as an unchecked String.
identity!(ItemId, |value: &str| value.len() <= ITEM_ID_BYTES);
// The Codex OAuth sign-in's CSRF `state` correlation value (`auth::codex`): generated as
// 128 bits of randomness, so always exactly 32 lowercase hex characters.
identity!(OAuthState, |value: &str| value.len()
    == OAUTH_STATE_HEX_BYTES
    && value
        .bytes()
        .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)));
identity!(ReuseKey, sha256_hex);
// The SHA-256 of an eval's review strategy (`cache::eval_definition_hash`).
identity!(DefinitionHash, sha256_hex);
// State UUIDs and legacy session state identifiers share the saved segment domain.
identity!(StateId, segment);
identity!(Sha256Digest, sha256_hex);
// Session locators use the bounded printable user@host label, not a filesystem segment;
// a producer may contain a slash because locators split their four IDs from the right.
identity!(ProducerId, |value: &str| (1..=MAX_ID_BYTES)
    .contains(&value.len())
    && !value.chars().any(char::is_control));

/// A raw SHA-256 digest: 32 bytes, kept binary for streaming hash composition and byte
/// slicing. Hex-encode into a [`Sha256Digest`] or [`DigestPrefix`] to store or show it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Sha256Bytes([u8; 32]);

impl Sha256Bytes {
    /// The SHA-256 digest of `bytes`.
    pub fn of(bytes: &[u8]) -> Self {
        Self(sha2::Sha256::digest(bytes).into())
    }

    /// From an already-finalized digest, such as after streaming `Sha256::update`.
    pub fn from_digest(bytes: [u8; 32]) -> Self {
        Self(bytes)
    }

    pub fn as_bytes(&self) -> &[u8; 32] {
        &self.0
    }
}

// Compact diagnostic digests are the unchanged first eight bytes of a SHA-256.
identity!(DigestPrefix, |value: &str| value.len()
    == DIGEST_PREFIX_HEX_BYTES
    && value
        .bytes()
        .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)));
identity!(StoreUrl, |value: &str| reqwest::Url::parse(value)
    .is_ok_and(|url| matches!(url.scheme(), "http" | "https")
        && url.host_str().is_some()
        && url.username().is_empty()
        && url.password().is_none()));
// Human audit labels permit printable Unicode and spaces, but never control characters.
identity!(
    ReviewerId,
    |value: &str| !value.trim().is_empty()
        && value.len() <= MAX_ID_BYTES
        && !value.chars().any(char::is_control),
    |_: &str| "A reviewer id of 1–200 bytes without control characters is required.".to_owned()
);

identity!(TokenName, |value: &str| (1..=MAX_TOKEN_NAME_BYTES)
    .contains(&value.len())
    && value.bytes().all(
        |b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.')
    ));

macro_rules! status {
    ($name:ident { $($variant:ident => $text:literal),+ $(,)? }) => {
        #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
        pub enum $name {
            $(#[serde(rename = $text)] $variant),+
        }
        impl $name {
            pub fn as_str(self) -> &'static str {
                match self {
                    $(Self::$variant => $text),+
                }
            }
        }
        impl fmt::Display for $name {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str(self.as_str())
            }
        }
        impl FromStr for $name {
            type Err = String;
            fn from_str(value: &str) -> Result<Self, Self::Err> {
                match value {
                    $($text => Ok(Self::$variant)),+,
                    _ => Err(format!("Invalid {}: {value:?}.", stringify!($name))),
                }
            }
        }
        impl ToSql for $name {
            fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
                self.as_str().to_sql()
            }
        }
        impl FromSql for $name {
            fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
                value
                    .as_str()?
                    .parse()
                    .map_err(|error: String| FromSqlError::Other(error.into()))
            }
        }
    };
}
status!(FailureCode {
   Authentication => "AUTHENTICATION",
   Quota => "QUOTA",
   RateLimit => "RATE_LIMIT",
   Transient => "TRANSIENT",
   Timeout => "TIMEOUT",
   Cancelled => "CANCELLED",
   ProviderBudgetExceeded => "PROVIDER_BUDGET_EXCEEDED",
   InvalidResult => "INVALID_RESULT",
   ProviderError => "PROVIDER_ERROR",
   AgentError => "AGENT_ERROR",
   BackendStopped => "BACKEND_STOPPED",
   PreparationFailed => "PREPARATION_FAILED",
   InputChanged => "INPUT_CHANGED",
   FingerprintRecheckFailed => "FINGERPRINT_RECHECK_FAILED",
   SpawnFailed => "SPAWN_FAILED",
   AbnormalExit => "ABNORMAL_EXIT",
   RuntimeError => "RUNTIME_ERROR",
   Superseded => "SUPERSEDED",
   OwnerDied => "OWNER_DIED",
   Spawn => "SPAWN",
});
impl std::ops::Deref for FailureCode {
    type Target = str;
    fn deref(&self) -> &str {
        self.as_str()
    }
}
status!(BackendStopCode { Authentication => "AUTHENTICATION", Quota => "QUOTA" });
impl TryFrom<FailureCode> for BackendStopCode {
    type Error = String;
    fn try_from(code: FailureCode) -> Result<Self, String> {
        code.as_str().parse()
    }
}
status!(FingerprintKind { Artifactsum => "artifactsum", Script => "script" });
status!(ArtifactValidationStatus { Basis => "BASIS", Green => "GREEN", Incomplete => "INCOMPLETE", Error => "ERROR", Red => "RED", Blocked => "BLOCKED", Wait => "WAIT", Stale => "STALE", Unreviewed => "UNREVIEWED" });
status!(RunStatus {
    Running => "RUNNING",
    Green => "GREEN",
    Red => "RED",
    Error => "ERROR",
    Incomplete => "INCOMPLETE",
});
status!(RequestStatus {
    Queued => "QUEUED",
    Running => "RUNNING",
    WaitingHuman => "WAITING_HUMAN",
    Green => "GREEN",
    Red => "RED",
    Error => "ERROR",
    BudgetExhausted => "BUDGET_EXHAUSTED",
    Stale => "STALE",
    Unreviewed => "UNREVIEWED",
    WaitDependency => "WAIT_DEPENDENCY",
    Blocked => "BLOCKED",
});
status!(ExecutionStatus {
    Running => "RUNNING",
    WaitingHuman => "WAITING_HUMAN",
    Green => "GREEN",
    Red => "RED",
    Error => "ERROR",
});
impl From<ExecutionStatus> for RequestStatus {
    fn from(status: ExecutionStatus) -> Self {
        match status {
            ExecutionStatus::Running => Self::Running,
            ExecutionStatus::WaitingHuman => Self::WaitingHuman,
            ExecutionStatus::Green => Self::Green,
            ExecutionStatus::Red => Self::Red,
            ExecutionStatus::Error => Self::Error,
        }
    }
}
impl TryFrom<RequestStatus> for ExecutionStatus {
    type Error = String;
    fn try_from(status: RequestStatus) -> Result<Self, String> {
        match status {
            RequestStatus::Running => Ok(Self::Running),
            RequestStatus::WaitingHuman => Ok(Self::WaitingHuman),
            RequestStatus::Green => Ok(Self::Green),
            RequestStatus::Red => Ok(Self::Red),
            RequestStatus::Error => Ok(Self::Error),
            other => Err(format!("Request state {other} is not an execution state.")),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn reviewers_preserve_printable_labels_and_validate_json_and_sql() {
        let db = rusqlite::Connection::open_in_memory().unwrap();
        for label in [
            "alice",
            " reviewer ",
            "홍 길동",
            "a/b@host",
            &"x".repeat(200),
        ] {
            let reviewer: ReviewerId = label.parse().unwrap();
            let wire = serde_json::to_string(label).unwrap();
            assert_eq!(serde_json::to_string(&reviewer).unwrap(), wire);
            assert_eq!(serde_json::from_str::<ReviewerId>(&wire).unwrap(), reviewer);
            assert_eq!(
                db.query_row("SELECT ?", [&reviewer], |row| row.get::<_, ReviewerId>(0))
                    .unwrap(),
                reviewer
            );
        }
        for label in ["", "  ", "\t", "a\n", "a\0b", &"x".repeat(201)] {
            assert!(label.parse::<ReviewerId>().is_err());
            assert!(
                serde_json::from_str::<ReviewerId>(&serde_json::to_string(label).unwrap()).is_err()
            );
            assert!(
                db.query_row("SELECT ?", [label], |row| row.get::<_, ReviewerId>(0))
                    .is_err()
            );
        }
    }
    #[test]
    fn identities_validate_json_and_sql_edges() {
        for value in ["", ".", "..", "a/b", "a\\b", "a b", "a\n"] {
            assert!(value.parse::<SessionId>().is_err(), "{value:?}");
            assert!(value.parse::<RunId>().is_err());
            assert!(value.parse::<RequestId>().is_err());
            assert!(value.parse::<ExecutionId>().is_err());
        }
        assert!("legacy.session-1".parse::<SessionId>().is_ok());
        assert!("v1:Mixed_CASE.42".parse::<Fingerprint>().is_ok());
        assert!("x".repeat(128).parse::<Fingerprint>().is_ok());
        assert!("x".repeat(129).parse::<Fingerprint>().is_err());
        for value in ["f".repeat(63), "F".repeat(64), "g".repeat(64)] {
            assert!(value.parse::<ReuseKey>().is_err());
        }
        let key: ReuseKey = "a".repeat(64).parse().unwrap();
        assert_eq!(
            serde_json::to_string(&key).unwrap(),
            format!("\"{}\"", "a".repeat(64))
        );
        assert!(serde_json::from_str::<SessionId>("\"../escape\"").is_err());
        let db = rusqlite::Connection::open_in_memory().unwrap();
        assert!(
            db.query_row("SELECT '../escape'", [], |row| row.get::<_, RunId>(0))
                .is_err()
        );
    }
    #[test]
    fn store_identity_boundaries_preserve_text_and_reject_invalid_inputs() {
        assert_eq!(
            serde_json::to_string(&"state".parse::<StateId>().unwrap()).unwrap(),
            "\"state\""
        );
        let store: StoreUrl = "https://reviews.example/path".parse().unwrap();
        assert_eq!(
            serde_json::to_string(&store).unwrap(),
            "\"https://reviews.example/path\""
        );
        for invalid in [
            "fixture",
            "file:///path",
            "https://user:secret@reviews.example/",
        ] {
            assert!(invalid.parse::<StoreUrl>().is_err());
        }
        for invalid in ["", "bad name", "../escape"] {
            assert!(invalid.parse::<TokenName>().is_err());
        }
        for invalid in ["F".repeat(64), "f".repeat(63)] {
            assert!(invalid.parse::<Sha256Digest>().is_err());
        }
        assert!("f".repeat(64).parse::<Sha256Digest>().is_ok());
        assert!("f".repeat(16).parse::<DigestPrefix>().is_ok());
        assert!("f".repeat(64).parse::<DigestPrefix>().is_err());
        assert_eq!(
            serde_json::to_string(&FailureCode::OwnerDied).unwrap(),
            "\"OWNER_DIED\""
        );
        assert!(BackendStopCode::try_from(FailureCode::Timeout).is_err());
        assert_eq!(
            BackendStopCode::try_from(FailureCode::Quota).unwrap(),
            BackendStopCode::Quota
        );
        assert!("UNKNOWN".parse::<FailureCode>().is_err());
        let db = rusqlite::Connection::open_in_memory().unwrap();
        assert!(
            db.query_row("SELECT 'bad name'", [], |row| row.get::<_, TokenName>(0))
                .is_err()
        );
    }
    #[test]
    fn status_domains_retain_wire_names_and_reject_cross_domain_states() {
        assert_eq!(
            serde_json::to_string(&RunStatus::Incomplete).unwrap(),
            "\"INCOMPLETE\""
        );
        assert_eq!(
            serde_json::from_str::<RequestStatus>("\"WAITING_HUMAN\"").unwrap(),
            RequestStatus::WaitingHuman
        );
        assert!("QUEUED".parse::<ExecutionStatus>().is_err());
        assert!("WAITING_HUMAN".parse::<RunStatus>().is_err());
        assert!("INCOMPLETE".parse::<RequestStatus>().is_err());
    }
}

// OAuth account claims are opaque provider strings, historically any nonempty text.
identity!(CodexAccountId, |value: &str| !value.is_empty());

// The block a streamed delivery belongs to: a response text part, a reasoning summary, or
// the whole attempt, which an interruption ends. Summary blocks carry the provider's item
// identity, so any non-empty text is valid.
identity!(DeliveryBlock, |value: &str| !value.is_empty());

/// The block naming a whole attempt.
const ATTEMPT_BLOCK: &str = "attempt";

impl DeliveryBlock {
    /// The whole attempt.
    pub fn attempt() -> Self {
        Self(ATTEMPT_BLOCK.to_owned())
    }
    /// Whether this names the whole attempt.
    pub fn is_attempt(&self) -> bool {
        self.0 == ATTEMPT_BLOCK
    }
    /// Response text part `part`.
    pub fn text(part: usize) -> Self {
        Self(format!("text-{part}"))
    }
    /// Summary `index` of the reasoning item `identity` names.
    pub fn summary(identity: &str, index: usize) -> Self {
        Self(format!("summary-{identity}-{index}"))
    }
}