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
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
|
use std::collections::{BTreeMap, BTreeSet};
use std::fmt::{self, Display, Formatter};
use camino::Utf8PathBuf;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use time::OffsetDateTime;
use time::format_description::well_known::Rfc3339;
use crate::{
AgentSessionId, AnnotationId, ArtifactId, CheckpointId, CoreError, ExperimentId, FrontierId,
NodeId, RunId,
};
#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
#[serde(transparent)]
pub struct NonEmptyText(String);
impl NonEmptyText {
pub fn new(value: impl Into<String>) -> Result<Self, CoreError> {
let value = value.into();
if value.trim().is_empty() {
return Err(CoreError::EmptyText);
}
Ok(Self(value))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl Display for NonEmptyText {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.0)
}
}
#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
#[serde(transparent)]
pub struct GitCommitHash(NonEmptyText);
impl GitCommitHash {
pub fn new(value: impl Into<String>) -> Result<Self, CoreError> {
NonEmptyText::new(value).map(Self)
}
#[must_use]
pub fn as_str(&self) -> &str {
self.0.as_str()
}
}
impl Display for GitCommitHash {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
Display::fmt(&self.0, formatter)
}
}
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct TagName(String);
impl TagName {
pub fn new(value: impl Into<String>) -> Result<Self, CoreError> {
let normalized = value.into().trim().to_ascii_lowercase();
if normalized.is_empty() {
return Err(CoreError::EmptyTagName);
}
let mut previous_was_separator = true;
for character in normalized.chars() {
if character.is_ascii_lowercase() || character.is_ascii_digit() {
previous_was_separator = false;
continue;
}
if matches!(character, '-' | '_' | '/') && !previous_was_separator {
previous_was_separator = true;
continue;
}
return Err(CoreError::InvalidTagName(normalized));
}
if previous_was_separator {
return Err(CoreError::InvalidTagName(normalized));
}
Ok(Self(normalized))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl TryFrom<String> for TagName {
type Error = CoreError;
fn try_from(value: String) -> Result<Self, Self::Error> {
Self::new(value)
}
}
impl From<TagName> for String {
fn from(value: TagName) -> Self {
value.0
}
}
impl Display for TagName {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.0)
}
}
pub type JsonObject = Map<String, Value>;
#[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
pub enum NodeClass {
Contract,
Hypothesis,
Run,
Analysis,
Decision,
Source,
Note,
}
impl NodeClass {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Contract => "contract",
Self::Hypothesis => "hypothesis",
Self::Run => "run",
Self::Analysis => "analysis",
Self::Decision => "decision",
Self::Source => "source",
Self::Note => "note",
}
}
#[must_use]
pub const fn default_track(self) -> NodeTrack {
match self {
Self::Contract | Self::Hypothesis | Self::Run | Self::Analysis | Self::Decision => {
NodeTrack::CorePath
}
Self::Source | Self::Note => NodeTrack::OffPath,
}
}
}
impl Display for NodeClass {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
pub enum NodeTrack {
CorePath,
OffPath,
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
pub enum AnnotationVisibility {
HiddenByDefault,
Visible,
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
pub enum DiagnosticSeverity {
Error,
Warning,
Info,
}
impl DiagnosticSeverity {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Error => "error",
Self::Warning => "warning",
Self::Info => "info",
}
}
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
pub enum FieldPresence {
Required,
Recommended,
Optional,
}
impl FieldPresence {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Required => "required",
Self::Recommended => "recommended",
Self::Optional => "optional",
}
}
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
pub enum FieldRole {
Index,
ProjectionGate,
RenderOnly,
Opaque,
}
impl FieldRole {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Index => "index",
Self::ProjectionGate => "projection_gate",
Self::RenderOnly => "render_only",
Self::Opaque => "opaque",
}
}
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
pub enum InferencePolicy {
ManualOnly,
ModelMayInfer,
}
impl InferencePolicy {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::ManualOnly => "manual_only",
Self::ModelMayInfer => "model_may_infer",
}
}
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum FieldValueType {
String,
Numeric,
Boolean,
Timestamp,
}
impl FieldValueType {
#[must_use]
pub const fn is_plottable(self) -> bool {
matches!(self, Self::Numeric | Self::Timestamp)
}
#[must_use]
pub fn accepts(self, value: &Value) -> bool {
match self {
Self::String => value.is_string(),
Self::Numeric => value.is_number(),
Self::Boolean => value.is_boolean(),
Self::Timestamp => value
.as_str()
.is_some_and(|raw| OffsetDateTime::parse(raw, &Rfc3339).is_ok()),
}
}
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::String => "string",
Self::Numeric => "numeric",
Self::Boolean => "boolean",
Self::Timestamp => "timestamp",
}
}
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum FrontierStatus {
Exploring,
Paused,
Saturated,
Archived,
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum CheckpointDisposition {
Champion,
FrontierCandidate,
Baseline,
DeadEnd,
Archived,
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
pub enum MetricUnit {
Seconds,
Bytes,
Count,
Ratio,
Custom,
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
pub enum OptimizationObjective {
Minimize,
Maximize,
Target,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct MetricDefinition {
pub key: NonEmptyText,
pub unit: MetricUnit,
pub objective: OptimizationObjective,
pub description: Option<NonEmptyText>,
pub created_at: OffsetDateTime,
}
impl MetricDefinition {
#[must_use]
pub fn new(
key: NonEmptyText,
unit: MetricUnit,
objective: OptimizationObjective,
description: Option<NonEmptyText>,
) -> Self {
Self {
key,
unit,
objective,
description,
created_at: OffsetDateTime::now_utc(),
}
}
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "snake_case", tag = "type", content = "value")]
pub enum RunDimensionValue {
String(NonEmptyText),
Numeric(f64),
Boolean(bool),
Timestamp(NonEmptyText),
}
impl RunDimensionValue {
#[must_use]
pub const fn value_type(&self) -> FieldValueType {
match self {
Self::String(_) => FieldValueType::String,
Self::Numeric(_) => FieldValueType::Numeric,
Self::Boolean(_) => FieldValueType::Boolean,
Self::Timestamp(_) => FieldValueType::Timestamp,
}
}
#[must_use]
pub fn as_json(&self) -> Value {
match self {
Self::String(value) | Self::Timestamp(value) => Value::String(value.to_string()),
Self::Numeric(value) => {
serde_json::Number::from_f64(*value).map_or(Value::Null, Value::Number)
}
Self::Boolean(value) => Value::Bool(*value),
}
}
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct RunDimensionDefinition {
pub key: NonEmptyText,
pub value_type: FieldValueType,
pub description: Option<NonEmptyText>,
pub created_at: OffsetDateTime,
}
impl RunDimensionDefinition {
#[must_use]
pub fn new(
key: NonEmptyText,
value_type: FieldValueType,
description: Option<NonEmptyText>,
) -> Self {
Self {
key,
value_type,
description,
created_at: OffsetDateTime::now_utc(),
}
}
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct MetricValue {
#[serde(alias = "metric_key")]
pub key: NonEmptyText,
pub value: f64,
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum RunStatus {
Queued,
Running,
Succeeded,
Failed,
Cancelled,
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum ExecutionBackend {
LocalProcess,
WorktreeProcess,
SshProcess,
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum FrontierVerdict {
PromoteToChampion,
KeepOnFrontier,
RevertToChampion,
ArchiveDeadEnd,
NeedsMoreEvidence,
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum AdmissionState {
Admitted,
Rejected,
}
#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
pub struct PayloadSchemaRef {
pub namespace: NonEmptyText,
pub version: u32,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct NodePayload {
pub schema: Option<PayloadSchemaRef>,
pub fields: JsonObject,
}
impl NodePayload {
#[must_use]
pub fn empty() -> Self {
Self {
schema: None,
fields: JsonObject::new(),
}
}
#[must_use]
pub fn with_schema(schema: PayloadSchemaRef, fields: JsonObject) -> Self {
Self {
schema: Some(schema),
fields,
}
}
#[must_use]
pub fn field(&self, name: &str) -> Option<&Value> {
self.fields.get(name)
}
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct NodeAnnotation {
pub id: AnnotationId,
pub visibility: AnnotationVisibility,
pub label: Option<NonEmptyText>,
pub body: NonEmptyText,
pub created_at: OffsetDateTime,
}
impl NodeAnnotation {
#[must_use]
pub fn hidden(body: NonEmptyText) -> Self {
Self {
id: AnnotationId::fresh(),
visibility: AnnotationVisibility::HiddenByDefault,
label: None,
body,
created_at: OffsetDateTime::now_utc(),
}
}
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct TagRecord {
pub name: TagName,
pub description: NonEmptyText,
pub created_at: OffsetDateTime,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct ValidationDiagnostic {
pub severity: DiagnosticSeverity,
pub code: String,
pub message: NonEmptyText,
pub field_name: Option<String>,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct NodeDiagnostics {
pub admission: AdmissionState,
pub items: Vec<ValidationDiagnostic>,
}
impl NodeDiagnostics {
#[must_use]
pub const fn admitted() -> Self {
Self {
admission: AdmissionState::Admitted,
items: Vec::new(),
}
}
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct ProjectFieldSpec {
pub name: NonEmptyText,
pub node_classes: BTreeSet<NodeClass>,
pub presence: FieldPresence,
pub severity: DiagnosticSeverity,
pub role: FieldRole,
pub inference_policy: InferencePolicy,
#[serde(default)]
pub value_type: Option<FieldValueType>,
}
impl ProjectFieldSpec {
#[must_use]
pub fn applies_to(&self, class: NodeClass) -> bool {
self.node_classes.is_empty() || self.node_classes.contains(&class)
}
#[must_use]
pub fn is_plottable(&self) -> bool {
self.value_type.is_some_and(FieldValueType::is_plottable)
}
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct ProjectSchema {
pub namespace: NonEmptyText,
pub version: u32,
pub fields: Vec<ProjectFieldSpec>,
}
impl ProjectSchema {
#[must_use]
pub fn default_with_namespace(namespace: NonEmptyText) -> Self {
Self {
namespace,
version: 1,
fields: Vec::new(),
}
}
#[must_use]
pub fn schema_ref(&self) -> PayloadSchemaRef {
PayloadSchemaRef {
namespace: self.namespace.clone(),
version: self.version,
}
}
#[must_use]
pub fn field_spec(&self, class: NodeClass, name: &str) -> Option<&ProjectFieldSpec> {
self.fields
.iter()
.find(|field| field.applies_to(class) && field.name.as_str() == name)
}
#[must_use]
pub fn validate_node(&self, class: NodeClass, payload: &NodePayload) -> NodeDiagnostics {
let items = self
.fields
.iter()
.filter(|field| field.applies_to(class))
.filter_map(|field| {
let value = payload.field(field.name.as_str());
let is_missing = value.is_none();
if !is_missing || field.presence == FieldPresence::Optional {
if let (Some(value), Some(value_type)) = (value, field.value_type)
&& !value_type.accepts(value)
{
return Some(ValidationDiagnostic {
severity: field.severity,
code: format!("type.{}", field.name.as_str()),
message: validation_message(format!(
"project payload field `{}` expected {}, found {}",
field.name.as_str(),
value_type.as_str(),
json_value_kind(value)
)),
field_name: Some(field.name.as_str().to_owned()),
});
}
return None;
}
Some(ValidationDiagnostic {
severity: field.severity,
code: format!("missing.{}", field.name.as_str()),
message: validation_message(format!(
"missing project payload field `{}`",
field.name.as_str()
)),
field_name: Some(field.name.as_str().to_owned()),
})
})
.collect();
NodeDiagnostics {
admission: AdmissionState::Admitted,
items,
}
}
}
fn validation_message(value: String) -> NonEmptyText {
match NonEmptyText::new(value) {
Ok(message) => message,
Err(_) => unreachable!("validation diagnostics are never empty"),
}
}
fn json_value_kind(value: &Value) -> &'static str {
match value {
Value::Null => "null",
Value::Bool(_) => "boolean",
Value::Number(_) => "numeric",
Value::String(_) => "string",
Value::Array(_) => "array",
Value::Object(_) => "object",
}
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct DagNode {
pub id: NodeId,
pub class: NodeClass,
pub track: NodeTrack,
pub frontier_id: Option<FrontierId>,
pub archived: bool,
pub title: NonEmptyText,
pub summary: Option<NonEmptyText>,
pub tags: BTreeSet<TagName>,
pub payload: NodePayload,
pub annotations: Vec<NodeAnnotation>,
pub diagnostics: NodeDiagnostics,
pub agent_session_id: Option<AgentSessionId>,
pub created_at: OffsetDateTime,
pub updated_at: OffsetDateTime,
}
impl DagNode {
#[must_use]
pub fn new(
class: NodeClass,
frontier_id: Option<FrontierId>,
title: NonEmptyText,
summary: Option<NonEmptyText>,
payload: NodePayload,
diagnostics: NodeDiagnostics,
) -> Self {
let now = OffsetDateTime::now_utc();
Self {
id: NodeId::fresh(),
class,
track: class.default_track(),
frontier_id,
archived: false,
title,
summary,
tags: BTreeSet::new(),
payload,
annotations: Vec::new(),
diagnostics,
agent_session_id: None,
created_at: now,
updated_at: now,
}
}
#[must_use]
pub fn is_core_path(&self) -> bool {
self.track == NodeTrack::CorePath
}
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
pub enum EdgeKind {
Lineage,
Evidence,
Comparison,
Supersedes,
Annotation,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct DagEdge {
pub source_id: NodeId,
pub target_id: NodeId,
pub kind: EdgeKind,
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum ArtifactKind {
Note,
Patch,
BenchmarkBundle,
MetricSeries,
Table,
Plot,
Log,
Binary,
Checkpoint,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct ArtifactRef {
pub id: ArtifactId,
pub kind: ArtifactKind,
pub label: NonEmptyText,
pub path: Utf8PathBuf,
pub media_type: Option<NonEmptyText>,
pub produced_by_run: Option<RunId>,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct CodeSnapshotRef {
pub repo_root: Utf8PathBuf,
pub worktree_root: Utf8PathBuf,
pub worktree_name: Option<NonEmptyText>,
pub head_commit: Option<GitCommitHash>,
pub dirty_paths: BTreeSet<Utf8PathBuf>,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct CheckpointSnapshotRef {
pub repo_root: Utf8PathBuf,
pub worktree_root: Utf8PathBuf,
pub worktree_name: Option<NonEmptyText>,
pub commit_hash: GitCommitHash,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct CommandRecipe {
pub working_directory: Utf8PathBuf,
pub argv: Vec<NonEmptyText>,
pub env: BTreeMap<String, String>,
}
impl CommandRecipe {
pub fn new(
working_directory: Utf8PathBuf,
argv: Vec<NonEmptyText>,
env: BTreeMap<String, String>,
) -> Result<Self, CoreError> {
if argv.is_empty() {
return Err(CoreError::EmptyCommand);
}
Ok(Self {
working_directory,
argv,
env,
})
}
}
#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
pub struct MetricSpec {
pub metric_key: NonEmptyText,
pub unit: MetricUnit,
pub objective: OptimizationObjective,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct EvaluationProtocol {
pub benchmark_suites: BTreeSet<NonEmptyText>,
pub primary_metric: MetricSpec,
pub supporting_metrics: BTreeSet<MetricSpec>,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct FrontierContract {
pub objective: NonEmptyText,
pub evaluation: EvaluationProtocol,
pub promotion_criteria: Vec<NonEmptyText>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct MetricObservation {
pub metric_key: NonEmptyText,
pub unit: MetricUnit,
pub objective: OptimizationObjective,
pub value: f64,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct FrontierRecord {
pub id: FrontierId,
pub label: NonEmptyText,
pub root_contract_node_id: NodeId,
pub status: FrontierStatus,
pub created_at: OffsetDateTime,
pub updated_at: OffsetDateTime,
}
impl FrontierRecord {
#[must_use]
pub fn new(label: NonEmptyText, root_contract_node_id: NodeId) -> Self {
Self::with_id(FrontierId::fresh(), label, root_contract_node_id)
}
#[must_use]
pub fn with_id(id: FrontierId, label: NonEmptyText, root_contract_node_id: NodeId) -> Self {
let now = OffsetDateTime::now_utc();
Self {
id,
label,
root_contract_node_id,
status: FrontierStatus::Exploring,
created_at: now,
updated_at: now,
}
}
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct CheckpointRecord {
pub id: CheckpointId,
pub frontier_id: FrontierId,
pub node_id: NodeId,
pub snapshot: CheckpointSnapshotRef,
pub disposition: CheckpointDisposition,
pub summary: NonEmptyText,
pub created_at: OffsetDateTime,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct RunRecord {
pub node_id: NodeId,
pub run_id: RunId,
pub frontier_id: Option<FrontierId>,
pub status: RunStatus,
pub backend: ExecutionBackend,
pub code_snapshot: Option<CodeSnapshotRef>,
pub dimensions: BTreeMap<NonEmptyText, RunDimensionValue>,
pub command: CommandRecipe,
pub started_at: Option<OffsetDateTime>,
pub finished_at: Option<OffsetDateTime>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct ExperimentResult {
pub dimensions: BTreeMap<NonEmptyText, RunDimensionValue>,
pub primary_metric: MetricValue,
pub supporting_metrics: Vec<MetricValue>,
pub benchmark_bundle: Option<ArtifactId>,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct OpenExperiment {
pub id: ExperimentId,
pub frontier_id: FrontierId,
pub base_checkpoint_id: CheckpointId,
pub hypothesis_node_id: NodeId,
pub title: NonEmptyText,
pub summary: Option<NonEmptyText>,
pub created_at: OffsetDateTime,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct FrontierNote {
pub summary: NonEmptyText,
pub next_hypotheses: Vec<NonEmptyText>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct CompletedExperiment {
pub id: ExperimentId,
pub frontier_id: FrontierId,
pub base_checkpoint_id: CheckpointId,
pub candidate_checkpoint_id: CheckpointId,
pub hypothesis_node_id: NodeId,
pub run_node_id: NodeId,
pub run_id: RunId,
pub analysis_node_id: Option<NodeId>,
pub decision_node_id: NodeId,
pub title: NonEmptyText,
pub summary: Option<NonEmptyText>,
pub result: ExperimentResult,
pub note: FrontierNote,
pub verdict: FrontierVerdict,
pub created_at: OffsetDateTime,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct FrontierProjection {
pub frontier: FrontierRecord,
pub champion_checkpoint_id: Option<CheckpointId>,
pub candidate_checkpoint_ids: BTreeSet<CheckpointId>,
pub experiment_count: u64,
}
#[cfg(test)]
mod tests {
use std::collections::{BTreeMap, BTreeSet};
use camino::Utf8PathBuf;
use serde_json::json;
use super::{
CommandRecipe, DagNode, DiagnosticSeverity, FieldPresence, FieldRole, FieldValueType,
InferencePolicy, JsonObject, NodeClass, NodePayload, NonEmptyText, ProjectFieldSpec,
ProjectSchema,
};
use crate::CoreError;
#[test]
fn non_empty_text_rejects_blank_input() {
let text = NonEmptyText::new(" ");
assert_eq!(text, Err(CoreError::EmptyText));
}
#[test]
fn command_recipe_requires_argv() {
let recipe = CommandRecipe::new(
Utf8PathBuf::from("/tmp/worktree"),
Vec::new(),
BTreeMap::new(),
);
assert_eq!(recipe, Err(CoreError::EmptyCommand));
}
#[test]
fn schema_validation_warns_without_rejecting_ingest() -> Result<(), CoreError> {
let schema = ProjectSchema {
namespace: NonEmptyText::new("local.libgrid")?,
version: 1,
fields: vec![ProjectFieldSpec {
name: NonEmptyText::new("hypothesis")?,
node_classes: BTreeSet::from([NodeClass::Hypothesis]),
presence: FieldPresence::Required,
severity: DiagnosticSeverity::Warning,
role: FieldRole::ProjectionGate,
inference_policy: InferencePolicy::ManualOnly,
value_type: None,
}],
};
let payload = NodePayload::with_schema(schema.schema_ref(), JsonObject::new());
let diagnostics = schema.validate_node(NodeClass::Hypothesis, &payload);
assert_eq!(diagnostics.admission, super::AdmissionState::Admitted);
assert_eq!(diagnostics.items.len(), 1);
assert_eq!(diagnostics.items[0].severity, DiagnosticSeverity::Warning);
Ok(())
}
#[test]
fn schema_validation_warns_on_type_mismatch() -> Result<(), CoreError> {
let schema = ProjectSchema {
namespace: NonEmptyText::new("local.libgrid")?,
version: 1,
fields: vec![ProjectFieldSpec {
name: NonEmptyText::new("improvement")?,
node_classes: BTreeSet::from([NodeClass::Analysis]),
presence: FieldPresence::Recommended,
severity: DiagnosticSeverity::Warning,
role: FieldRole::RenderOnly,
inference_policy: InferencePolicy::ManualOnly,
value_type: Some(FieldValueType::Numeric),
}],
};
let payload = NodePayload::with_schema(
schema.schema_ref(),
JsonObject::from_iter([("improvement".to_owned(), json!("not a number"))]),
);
let diagnostics = schema.validate_node(NodeClass::Analysis, &payload);
assert_eq!(diagnostics.admission, super::AdmissionState::Admitted);
assert_eq!(diagnostics.items.len(), 1);
assert_eq!(diagnostics.items[0].code, "type.improvement");
Ok(())
}
#[test]
fn source_nodes_default_to_off_path() -> Result<(), CoreError> {
let payload = NodePayload {
schema: None,
fields: JsonObject::from_iter([("topic".to_owned(), json!("ideas"))]),
};
let node = DagNode::new(
NodeClass::Source,
None,
NonEmptyText::new("feature scouting")?,
None,
payload,
super::NodeDiagnostics::admitted(),
);
assert!(!node.is_core_path());
Ok(())
}
}
|