-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathtests.rs
More file actions
880 lines (815 loc) · 32.5 KB
/
Copy pathtests.rs
File metadata and controls
880 lines (815 loc) · 32.5 KB
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
//! Service-level coverage. The CLI adapter in `commands::runs` keeps the
//! full integration coverage (JSON shape, markdown, error messages); here
//! we exercise the standalone service surface so callers outside the CLI
//! can rely on it without re-deriving guarantees from the command tests.
use super::*;
use crate::observation::NewRunRecord;
use crate::test_support::with_isolated_home;
use serde_json::Value;
use std::sync::{mpsc, Mutex};
struct XdgGuard(Option<String>);
impl XdgGuard {
fn unset() -> Self {
let prior = std::env::var("XDG_DATA_HOME").ok();
std::env::remove_var("XDG_DATA_HOME");
Self(prior)
}
}
impl Drop for XdgGuard {
fn drop(&mut self) {
match &self.0 {
Some(value) => std::env::set_var("XDG_DATA_HOME", value),
None => std::env::remove_var("XDG_DATA_HOME"),
}
}
}
fn sample_run(kind: &str) -> NewRunRecord {
NewRunRecord::builder(kind)
.component_id("homeboy")
.command(format!("homeboy {kind}"))
.cwd_path(std::path::Path::new("/tmp/homeboy-fixture"))
.homeboy_version("test-version")
.git_sha(Some("abc123".to_string()))
.rig_id("studio")
.metadata(Value::Null)
.build()
}
#[test]
fn require_run_returns_validation_error_for_missing_run() {
with_isolated_home(|_home| {
let _xdg = XdgGuard::unset();
let store = ObservationStore::open_initialized().expect("store");
let err = require_run(&store, "missing-run").expect_err("missing");
assert_eq!(err.code.as_str(), "validation.invalid_argument");
assert!(err.message.contains("run record not found"));
});
}
#[test]
fn terminal_retention_is_dry_run_by_default_and_deletes_owned_lifecycle_on_apply() {
with_isolated_home(|_home| {
let _xdg = XdgGuard::unset();
let store = ObservationStore::open_initialized().expect("store");
let terminal = store
.start_run(sample_run("agent-task"))
.expect("terminal run");
store
.finish_run(&terminal.id, RunStatus::Pass, None)
.expect("finish run");
store
.record_url_artifact(&terminal.id, "report", "https://example.test/report")
.expect("artifact");
let artifact_path = crate::artifacts::root()
.expect("artifact root")
.join(&terminal.id)
.join("report.json");
std::fs::create_dir_all(artifact_path.parent().expect("artifact parent"))
.expect("artifact parent");
std::fs::write(&artifact_path, "{}").expect("artifact bytes");
let local_artifact = store
.record_artifact(&terminal.id, "local_report", &artifact_path)
.expect("local artifact");
let recorded_artifact_path = {
let path = std::path::PathBuf::from(&local_artifact.path);
if path.is_absolute() {
path
} else {
crate::artifacts::root().expect("artifact root").join(path)
}
};
let lifecycle_dir = crate::paths::homeboy_data()
.expect("homeboy data")
.join("agent-task-runs")
.join(&terminal.id);
std::fs::create_dir_all(&lifecycle_dir).expect("lifecycle directory");
std::fs::write(lifecycle_dir.join("plan.json"), "{}").expect("lifecycle evidence");
let active = store.start_run(sample_run("trace")).expect("active run");
let path = store.status().expect("status").path;
drop(store);
let db = rusqlite::Connection::open(path).expect("raw db");
db.execute(
"UPDATE runs SET finished_at = '2000-01-01T00:00:00Z' WHERE id = ?1",
[&terminal.id],
)
.expect("age terminal run");
let dry = retain_terminal_runs(TerminalRunRetentionOptions {
apply: false,
older_than_days: 1,
limit: 10,
})
.expect("dry run");
assert_eq!(dry.candidate_run_ids, vec![terminal.id.clone()]);
assert_eq!(dry.artifact_cleanup.len(), 1);
assert_eq!(dry.lifecycle_directories.len(), 1);
assert!(dry.lifecycle_directories[0].exists);
assert!(lifecycle_dir.exists());
assert!(recorded_artifact_path.exists());
let applied = retain_terminal_runs(TerminalRunRetentionOptions {
apply: true,
older_than_days: 1,
limit: 10,
})
.expect("apply");
assert_eq!(applied.removed_run_count, 1);
let store = ObservationStore::open_initialized().expect("reopen");
assert!(store
.get_run(&terminal.id)
.expect("terminal read")
.is_none());
assert!(store
.list_artifacts(&terminal.id)
.expect("artifact read")
.is_empty());
assert!(!lifecycle_dir.exists());
assert!(!recorded_artifact_path.exists());
assert!(store.get_run(&active.id).expect("active read").is_some());
});
}
/// Unix-only: blocking a candidate run requires an artifact path that exists
/// but fails the safety revalidation, and a symlink is the portable-enough way
/// to produce that state.
#[cfg(unix)]
#[test]
fn terminal_retention_counts_only_the_runs_it_actually_deleted() {
with_isolated_home(|home| {
let _xdg = XdgGuard::unset();
let store = ObservationStore::open_initialized().expect("store");
// Two aged terminal runs. One holds an artifact that cleanup must
// refuse (a symlink), so retention plans it as blocked and deletes
// only the other one.
let removable = store.start_run(sample_run("test")).expect("removable run");
let blocked = store.start_run(sample_run("test")).expect("blocked run");
for run in [&removable, &blocked] {
store
.finish_run(&run.id, RunStatus::Pass, None)
.expect("finish run");
}
let source = home.path().join("source.json");
std::fs::write(&source, "{}").expect("source bytes");
let removable_artifact = store
.record_artifact(&removable.id, "report", &source)
.expect("removable artifact");
let blocked_artifact = store
.record_artifact(&blocked.id, "report", &source)
.expect("blocked artifact");
// Replace the recorded bytes with a symlink so classification returns
// `skip` with `exists = true`, which is what blocks a candidate run.
let blocked_path = std::path::PathBuf::from(&blocked_artifact.path);
std::fs::remove_file(&blocked_path).expect("drop blocked bytes");
std::os::unix::fs::symlink(&source, &blocked_path).expect("symlink blocked bytes");
let path = store.status().expect("status").path;
drop(store);
let db = rusqlite::Connection::open(path).expect("raw db");
for id in [&removable.id, &blocked.id] {
db.execute(
"UPDATE runs SET finished_at = '2000-01-01T00:00:00Z' WHERE id = ?1",
[id],
)
.expect("age terminal run");
}
drop(db);
let applied = retain_terminal_runs(TerminalRunRetentionOptions {
apply: true,
older_than_days: 1,
limit: 10,
})
.expect("apply");
assert_eq!(applied.candidate_run_ids.len(), 2);
assert_eq!(applied.skipped_run_ids, vec![blocked.id.clone()]);
// Before the accounting fix this reported `1 - 1 == 0` because the
// planning-loop skip was subtracted from a set it was never in.
assert_eq!(applied.removed_run_count, 1);
let store = ObservationStore::open_initialized().expect("reopen");
assert!(store
.get_run(&removable.id)
.expect("removable read")
.is_none());
assert!(store.get_run(&blocked.id).expect("blocked read").is_some());
assert!(!std::path::Path::new(&removable_artifact.path).exists());
assert!(std::fs::symlink_metadata(&blocked_path).is_ok());
});
}
#[test]
fn missing_run_guidance_prints_runner_routed_retrieval_commands() {
let hints = missing_run_guidance_for_runner_ids("run-123", vec!["homeboy-lab".to_string()]);
assert_eq!(
hints,
vec![
"Resolve runner-owned artifacts non-destructively from the controller: `homeboy runs artifacts run-123 --runner homeboy-lab` (routes to the generation that retains the run without rotating the shared tunnel).",
"Check runner `homeboy-lab` from the controller: `homeboy runs list --runner homeboy-lab --limit 100`.",
"Inspect run `run-123` directly on runner `homeboy-lab`: `homeboy runner exec homeboy-lab -- homeboy runs show run-123`.",
"List artifacts for run `run-123` directly on runner `homeboy-lab`: `homeboy runner exec homeboy-lab -- homeboy runs artifacts run-123`.",
"If the admission daemon is stale, read retained evidence without a refresh: `homeboy runner exec homeboy-lab --read-only-artifact -- homeboy runs artifacts run-123`.",
"Export run `run-123` directly on runner `homeboy-lab`: `homeboy runner exec homeboy-lab -- homeboy runs export --run run-123 --output <dir>`.",
]
);
}
#[test]
fn list_artifacts_for_run_enriches_url_artifact_links() {
with_isolated_home(|_home| {
let _xdg = XdgGuard::unset();
let store = ObservationStore::open_initialized().expect("store");
let run = store.start_run(sample_run("bench")).expect("run");
store
.record_url_artifact(&run.id, "frontend_url", "https://example.test/")
.expect("record URL artifact");
let artifacts = list_artifacts_for_run(&store, &run.id).expect("artifacts");
assert_eq!(artifacts.len(), 1);
assert_eq!(artifacts[0].artifact_type, "url");
// URL artifacts are enriched: public_url is filled in from the
// recorded URL so downstream consumers don't need to re-derive it.
assert_eq!(
artifacts[0].public_url.as_deref(),
Some("https://example.test/")
);
});
}
#[test]
fn resolve_artifact_for_run_rejects_unknown_artifact_id() {
with_isolated_home(|_home| {
let _xdg = XdgGuard::unset();
let store = ObservationStore::open_initialized().expect("store");
let run = store.start_run(sample_run("bench")).expect("run");
let err = resolve_artifact_for_run(&store, &run.id, "missing-artifact")
.expect_err("missing artifact");
assert_eq!(err.code.as_str(), "validation.invalid_argument");
assert!(err.message.contains("artifact record not found"));
// With no artifacts recorded, the error is explicit rather than
// listing phantom names.
assert!(err.message.contains("no recorded artifacts"));
});
}
#[test]
fn resolve_artifact_for_run_unknown_id_lists_available_names() {
with_isolated_home(|home| {
let _xdg = XdgGuard::unset();
let store = ObservationStore::open_initialized().expect("store");
let run = store.start_run(sample_run("bench")).expect("run");
let source = home.path().join("bench-results.json");
std::fs::write(&source, br#"{"ok":true}"#).expect("source");
store
.record_artifact(&run.id, "bench_results", &source)
.expect("record");
let err = resolve_artifact_for_run(&store, &run.id, "does-not-exist")
.expect_err("unknown artifact");
assert_eq!(err.code.as_str(), "validation.invalid_argument");
assert!(
err.message.contains("available artifact names")
&& err.message.contains("bench_results"),
"expected available names listing the recorded kind, got: {}",
err.message
);
});
}
#[test]
fn copy_local_file_artifact_writes_bytes_and_reports_metadata() {
with_isolated_home(|home| {
let _xdg = XdgGuard::unset();
let store = ObservationStore::open_initialized().expect("store");
let run = store.start_run(sample_run("bench")).expect("run");
let source = home.path().join("bench-results.json");
std::fs::write(&source, br#"{"ok":true}"#).expect("source");
let artifact = store
.record_artifact(&run.id, "bench_results", &source)
.expect("record");
let dest = home.path().join("downloaded.json");
let outcome = copy_local_file_artifact(artifact.clone(), Some(dest.clone())).expect("copy");
assert_eq!(outcome.run_id, run.id);
assert_eq!(outcome.artifact_id, artifact.id);
assert_eq!(outcome.output_path, dest);
assert_eq!(std::fs::read(&dest).expect("downloaded"), br#"{"ok":true}"#);
});
}
#[test]
fn classify_artifact_storage_recognizes_local_remote_and_metadata_only() {
let mut artifact = ArtifactRecord {
id: "a1".into(),
run_id: "r1".into(),
kind: "bench".into(),
artifact_type: "file".into(),
path: "/tmp/local".into(),
url: None,
public_url: None,
viewer_url: None,
viewer_links: Vec::new(),
sha256: None,
size_bytes: None,
mime: None,
metadata_json: Value::Null,
created_at: "2026-06-12T00:00:00Z".into(),
};
assert_eq!(
classify_artifact_storage(&artifact),
ArtifactStorage::LocalFile
);
artifact.artifact_type = "metadata-only".into();
artifact.path = "metadata-only:trace.zip".into();
assert_eq!(
classify_artifact_storage(&artifact),
ArtifactStorage::MetadataOnly
);
artifact.artifact_type = "remote_file".into();
assert_eq!(
classify_artifact_storage(&artifact),
ArtifactStorage::Remote
);
artifact.artifact_type = "url".into();
assert_eq!(classify_artifact_storage(&artifact), ArtifactStorage::Other);
}
fn remote_artifact(id: &str, kind: &str) -> ArtifactRecord {
ArtifactRecord {
id: id.into(),
run_id: "run-1".into(),
kind: kind.into(),
artifact_type: "remote_file".into(),
path: format!("runner-artifact://homeboy-lab/run-1/{id}"),
url: None,
public_url: None,
viewer_url: None,
viewer_links: Vec::new(),
sha256: None,
size_bytes: None,
mime: None,
metadata_json: serde_json::json!({ "role": "matrix-finding-packets" }),
created_at: "2026-06-26T00:00:00Z".into(),
}
}
#[test]
fn hydrate_remote_artifacts_rewrites_remote_packets_into_readable_files() {
let temp = tempfile::tempdir().expect("tempdir");
let packet_path = temp.path().join("finding-packets.json");
std::fs::write(
&packet_path,
br#"{"finding_packets":[{"diagnostic_kind":"missing_title","fixture_id":"home"}]}"#,
)
.expect("write packet");
let local = ArtifactRecord {
id: "local".into(),
run_id: "run-1".into(),
kind: "summary".into(),
artifact_type: "file".into(),
path: temp.path().join("summary.json").display().to_string(),
url: None,
public_url: None,
viewer_url: None,
viewer_links: Vec::new(),
sha256: None,
size_bytes: None,
mime: None,
metadata_json: Value::Null,
created_at: "2026-06-26T00:00:00Z".into(),
};
let remote = remote_artifact("finding-packets", "bench_artifact");
let mut downloads = 0;
let (hydrated, diagnostics) = hydrate_remote_artifacts(
vec![local.clone(), remote.clone()],
|_| true,
|artifact| {
downloads += 1;
assert_eq!(artifact.id, "finding-packets");
Ok(ArtifactFetchOutcome {
run_id: artifact.run_id.clone(),
artifact_id: artifact.id.clone(),
output_path: packet_path.clone(),
content_type: Some("application/json".into()),
size_bytes: Some(42),
sha256: None,
artifact_ref: None,
})
},
);
// Only the remote artifact triggers a download; the local file is left
// untouched.
assert_eq!(downloads, 1);
assert!(diagnostics.is_empty());
assert_eq!(hydrated[0].artifact_type, "file");
assert_eq!(hydrated[0].path, local.path);
let hydrated_remote = &hydrated[1];
assert_eq!(hydrated_remote.artifact_type, "file");
assert_eq!(hydrated_remote.path, packet_path.display().to_string());
assert_eq!(hydrated_remote.mime.as_deref(), Some("application/json"));
// The hydrated record now parses into a non-zero matrix summary, where
// the un-hydrated `remote_file` record would have summarized 0.
let summary =
crate::artifacts::summarize_matrix_artifacts("run-1", &hydrated, &[]).expect("summary");
assert_eq!(summary.finding_count, 1);
assert_eq!(summary.top_diagnostic_kinds[0].key, "missing_title");
assert_eq!(summary.top_fixtures[0].key, "home");
let zero =
crate::artifacts::summarize_matrix_artifacts("run-1", &[remote], &[]).expect("summary");
assert_eq!(zero.finding_count, 0);
}
#[test]
fn hydrate_remote_artifacts_records_diagnostic_without_aborting() {
let remote = remote_artifact("finding-packets", "bench_artifact");
let (hydrated, diagnostics) = hydrate_remote_artifacts(
vec![remote.clone()],
|_| true,
|_| Err(Error::internal_unexpected("runner offline")),
);
assert_eq!(hydrated.len(), 1);
// The original record is preserved on failure.
assert_eq!(hydrated[0].artifact_type, "remote_file");
assert_eq!(diagnostics.len(), 1);
assert!(diagnostics[0].contains("could not be hydrated"));
assert!(diagnostics[0].contains("runner offline"));
}
#[test]
fn hydrate_remote_artifacts_skips_non_selected_remote_artifacts() {
let remote = remote_artifact("trace.zip", "trace");
let mut downloads = 0;
let (hydrated, diagnostics) = hydrate_remote_artifacts(
vec![remote],
|artifact| artifact.kind == "bench_artifact",
|_| {
downloads += 1;
Err(Error::internal_unexpected("should not download"))
},
);
assert_eq!(downloads, 0);
assert!(diagnostics.is_empty());
assert_eq!(hydrated[0].artifact_type, "remote_file");
}
fn labeled_run(id: &str, command: &str, metadata: Value) -> RunRecord {
RunRecord {
id: id.into(),
kind: "bench.matrix".into(),
component_id: Some("homeboy".into()),
started_at: "2026-06-26T00:00:00Z".into(),
status: "fail".into(),
command: Some(command.into()),
metadata_json: metadata,
..Default::default()
}
}
#[test]
fn match_run_label_resolves_label_from_command_id_and_metadata() {
let cases = [
("persisted-id", "", serde_json::json!(null)),
(
"command-label",
"--run-id command-label",
serde_json::json!(null),
),
(
"command-equals-label",
"--run-id=command-equals-label",
serde_json::json!(null),
),
(
"requested",
"",
serde_json::json!({ "requested_run_id": "requested" }),
),
(
"lab-label",
"",
serde_json::json!({ "lab": { "run_label": "lab-label" } }),
),
(
"lab-explicit",
"",
serde_json::json!({ "lab": { "explicit_run_id": "lab-explicit" } }),
),
(
"lab-requested",
"",
serde_json::json!({ "lab": { "requested_run_id": "lab-requested" } }),
),
(
"lab-mirror",
"",
serde_json::json!({ "lab": { "mirror_run_id": "lab-mirror" } }),
),
(
"proof",
"",
serde_json::json!({ "proof": { "provenance": { "run_id": "proof" } } }),
),
(
"caller",
"",
serde_json::json!({ "caller_run_id": "caller" }),
),
(
"mirror",
"",
serde_json::json!({ "mirror_run_id": "mirror" }),
),
(
"persisted",
"",
serde_json::json!({ "persisted_run_id": "persisted" }),
),
("run", "", serde_json::json!({ "run_id": "run" })),
];
let runs = cases
.iter()
.enumerate()
.map(|(index, (label, command, metadata))| {
let id = if index == 0 {
(*label).to_string()
} else {
format!("uuid-{index}")
};
labeled_run(&id, command, metadata.clone())
})
.collect::<Vec<_>>();
for (index, (label, _, _)) in cases.iter().enumerate() {
assert_eq!(
match_run_label(&runs, label).map(|run| run.id),
Some(runs[index].id.clone()),
"label source `{label}` should resolve"
);
}
// An unknown label matches nothing.
assert!(match_run_label(&runs, "nope").is_none());
}
#[test]
fn resolve_run_id_or_label_returns_local_run_id_unchanged() {
with_isolated_home(|_home| {
let _xdg = XdgGuard::unset();
let store = ObservationStore::open_initialized().expect("store");
let run = store.start_run(sample_run("bench.matrix")).expect("run");
let resolved = resolve_run_id_or_label(&store, &run.id).expect("resolve existing run id");
assert_eq!(resolved, run.id);
});
}
#[test]
fn require_run_resolves_requested_run_id_metadata_alias() {
with_isolated_home(|_home| {
let _xdg = XdgGuard::unset();
let store = ObservationStore::open_initialized().expect("store");
let run = store
.start_run(
NewRunRecord::builder("bench")
.component_id("homeboy")
.command("homeboy bench homeboy --run-id proof-label")
.cwd_path(std::path::Path::new("/tmp/homeboy-fixture"))
.rig_id("studio")
.metadata(serde_json::json!({ "requested_run_id": "proof-label" }))
.build(),
)
.expect("run");
let resolved = require_run(&store, "proof-label").expect("alias resolves");
assert_eq!(resolved.id, run.id);
assert_eq!(
resolve_run_id_or_label(&store, "proof-label").expect("alias id"),
run.id
);
});
}
#[test]
fn require_run_reads_terminal_lab_review_alias_while_runner_probe_is_stalled() {
struct StalledProvider {
entered: mpsc::Sender<()>,
release: Mutex<mpsc::Receiver<()>>,
}
impl RunnerEvidenceProvider for StalledProvider {
fn mirror_connected_runner_run(&self, _run_id: &str) -> Result<Option<RunRecord>> {
self.entered.send(()).expect("signal stalled probe");
self.release
.lock()
.expect("release lock")
.recv()
.expect("release stalled probe");
Ok(None)
}
fn statuses(&self) -> Vec<RunnerConnectionInfo> {
Vec::new()
}
fn daemon_api_get(&self, _runner_id: &str, _path: &str) -> Result<Value> {
unreachable!("local lookup must not query the daemon")
}
fn runner_artifact_content(
&self,
_runner_id: &str,
_job_id: &str,
_artifact_id: &str,
) -> Result<Value> {
unreachable!("local lookup must not hydrate artifacts")
}
fn runner_job_cancel(
&self,
_runner_id: &str,
_job_id: &str,
) -> Result<(crate::api_jobs::Job, Vec<crate::api_jobs::JobEvent>)> {
unreachable!("local lookup must not mutate runner jobs")
}
fn refresh_mirrored_daemon_evidence(
&self,
_run_id: &str,
) -> Result<Option<Vec<RunRecord>>> {
unreachable!("local lookup must not reconcile runner evidence")
}
fn mirrored_runner_job_identity(&self, _run: &RunRecord) -> Option<(String, String)> {
None
}
fn download_remote_artifact(
&self,
_path: &str,
_output: Option<std::path::PathBuf>,
) -> Result<RemoteArtifactDownloadInfo> {
unreachable!("local lookup must not hydrate artifacts")
}
}
let _provider_lock = runner_evidence::runner_evidence_test_lock()
.lock()
.expect("provider test lock");
with_isolated_home(|_home| {
let _xdg = XdgGuard::unset();
let store = ObservationStore::open_initialized().expect("store");
let label = "runner-exec-review-homeboy-lab-terminal-job";
let run = RunRecord {
id: "terminal-lab-review-mirror".to_string(),
kind: "runner-exec".to_string(),
started_at: "2026-07-28T00:00:00Z".to_string(),
finished_at: Some("2026-07-28T00:01:00Z".to_string()),
status: RunStatus::Fail.as_str().to_string(),
metadata_json: serde_json::json!({
"requested_run_id": label,
"lab": {
"runner": { "id": "homeboy-lab" },
"remote_job": { "id": "terminal-job" }
}
}),
..Default::default()
};
store
.import_run(&run)
.expect("persist terminal Lab review run");
let artifact_path = _home.path().join("terminal-evidence.json");
std::fs::write(&artifact_path, br#"{"ok":true}"#).expect("artifact bytes");
store
.record_artifact(&run.id, "terminal_evidence", &artifact_path)
.expect("persist terminal evidence");
let (entered_tx, entered_rx) = mpsc::channel();
let (release_tx, release_rx) = mpsc::channel();
runner_evidence::register_runner_evidence_provider(Box::new(StalledProvider {
entered: entered_tx,
release: Mutex::new(release_rx),
}));
let stalled = std::thread::spawn(|| {
runner_evidence::with_runner_evidence(|provider| {
provider.mirror_connected_runner_run("unrelated-run")
})
});
entered_rx.recv().expect("secondary probe is stalled");
let resolved = require_run(&store, label).expect("durable local terminal record");
assert_eq!(resolved.id, run.id);
assert_eq!(resolved.status, RunStatus::Fail.as_str());
let artifacts = list_artifacts_for_run(&store, &run.id)
.expect("durable artifact reader must not wait for the runner");
assert_eq!(artifacts.len(), 1);
assert_eq!(artifacts[0].kind, "terminal_evidence");
assert!(
!stalled.is_finished(),
"lookup completed before probe release"
);
release_tx.send(()).expect("release secondary probe");
stalled
.join()
.expect("secondary probe joined")
.expect("secondary probe result");
runner_evidence::clear_runner_evidence_provider();
});
}
#[test]
fn list_artifacts_for_run_resolves_requested_run_id_alias() {
with_isolated_home(|home| {
let _xdg = XdgGuard::unset();
let store = ObservationStore::open_initialized().expect("store");
let run = store
.start_run(
NewRunRecord::builder("bench")
.component_id("homeboy")
.command("homeboy bench homeboy --run-id proof-label")
.cwd_path(std::path::Path::new("/tmp/homeboy-fixture"))
.rig_id("studio")
.metadata(serde_json::json!({ "requested_run_id": "proof-label" }))
.build(),
)
.expect("run");
let source = home.path().join("bench-results.json");
std::fs::write(&source, br#"{"ok":true}"#).expect("source");
store
.record_artifact(&run.id, "bench_results", &source)
.expect("record");
let artifacts = list_artifacts_for_run(&store, "proof-label").expect("artifacts");
assert_eq!(artifacts.len(), 1);
assert_eq!(artifacts[0].run_id, run.id);
assert_eq!(artifacts[0].kind, "bench_results");
});
}
#[test]
fn require_run_rejects_ambiguous_requested_run_id_alias() {
with_isolated_home(|_home| {
let _xdg = XdgGuard::unset();
let store = ObservationStore::open_initialized().expect("store");
let first = store
.start_run(
NewRunRecord::builder("bench")
.component_id("homeboy")
.cwd_path(std::path::Path::new("/tmp/homeboy-fixture-a"))
.rig_id("studio-a")
.metadata(serde_json::json!({ "requested_run_id": "shared-label" }))
.build(),
)
.expect("first run");
let second = store
.start_run(
NewRunRecord::builder("bench")
.component_id("homeboy")
.cwd_path(std::path::Path::new("/tmp/homeboy-fixture-b"))
.rig_id("studio-b")
.metadata(serde_json::json!({ "requested_run_id": "shared-label" }))
.build(),
)
.expect("second run");
let err = require_run(&store, "shared-label").expect_err("ambiguous label");
assert_eq!(err.code.as_str(), "validation.invalid_argument");
assert!(err
.message
.contains("run label `shared-label` is ambiguous"));
let joined = err
.details
.get("tried")
.and_then(Value::as_array)
.expect("disambiguation entries")
.iter()
.filter_map(Value::as_str)
.collect::<Vec<_>>()
.join("\n");
assert!(joined.contains(&first.id));
assert!(joined.contains(&second.id));
assert!(joined.contains("started_at="));
assert!(joined.contains("component=homeboy"));
assert!(joined.contains("rig=studio-a"));
assert!(joined.contains("rig=studio-b"));
});
}
fn lab_labeled_run(id: &str, kind: &str, label: &str, job_id: &str) -> RunRecord {
RunRecord {
id: id.to_string(),
kind: kind.to_string(),
component_id: Some("homeboy".to_string()),
started_at: "2026-07-18T00:00:00Z".to_string(),
status: "running".to_string(),
command: Some(format!("homeboy {kind} --run-id {label}")),
cwd: Some("/tmp/homeboy-fixture".to_string()),
rig_id: Some("studio".to_string()),
metadata_json: serde_json::json!({
"requested_run_id": label,
"lab": {
"runner": { "id": "homeboy-lab" },
"remote_job": { "id": job_id }
}
}),
..Default::default()
}
}
#[test]
fn require_run_resolves_lab_label_to_caller_across_mirrors() {
with_isolated_home(|_home| {
let _xdg = XdgGuard::unset();
let store = ObservationStore::open_initialized().expect("store");
let caller = lab_labeled_run("caller", "fuzz", "shared-label", "job-1");
store.upsert_imported_run(&caller).expect("caller");
for id in ["mirror-a", "mirror-b", "mirror-c"] {
store
.upsert_imported_run(&lab_labeled_run(id, "runner-exec", "shared-label", "job-1"))
.expect("mirror");
}
let resolved = require_run(&store, "shared-label").expect("canonical caller");
assert_eq!(resolved.id, caller.id);
});
}
#[test]
fn require_run_keeps_unrelated_lab_label_collision_ambiguous() {
with_isolated_home(|_home| {
let _xdg = XdgGuard::unset();
let store = ObservationStore::open_initialized().expect("store");
let caller = lab_labeled_run("caller", "fuzz", "shared-label", "job-1");
let collision = lab_labeled_run("collision", "fuzz", "shared-label", "job-2");
store.upsert_imported_run(&caller).expect("caller");
for id in ["mirror-a", "mirror-b", "mirror-c"] {
store
.upsert_imported_run(&lab_labeled_run(id, "runner-exec", "shared-label", "job-1"))
.expect("mirror");
}
store.upsert_imported_run(&collision).expect("collision");
let err = require_run(&store, "shared-label").expect_err("ambiguous label");
assert!(err.message.contains("2 persisted runs match"));
let joined = err.details["tried"]
.as_array()
.expect("disambiguation entries")
.iter()
.filter_map(Value::as_str)
.collect::<Vec<_>>()
.join("\n");
assert!(joined.contains(&caller.id));
assert!(joined.contains(&collision.id));
assert!(!joined.contains("mirror-a"));
assert!(!joined.contains("mirror-b"));
assert!(!joined.contains("mirror-c"));
});
}