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
//! CI: trigger runs from push events, validate the job graph.
mod run;
pub(crate) mod error;
pub use error::{Error, Result};
pub use quire_core::ci::pipeline::{
DefinitionError, Diagnostic, Job, Pipeline, PipelineError, StructureError,
};
pub use quire_core::ci::run::ApiSession;
pub use quire_core::ci::run::RunMeta;
pub use quire_core::ci::{pipeline, registration, runtime};
pub use run::{Executor, Run, Runs, materialize_workspace, reconcile_orphans};
use tracing_opentelemetry::OpenTelemetrySpanExt as _;
/// A resolved commit reference.
///
/// Carries both the full SHA (for git operations) and a short display
/// form (for error messages and user-facing output).
pub struct CommitRef {
/// Full commit SHA for git operations.
pub sha: String,
/// Short or human-readable form for display.
pub display: String,
}
use std::path::{Path, PathBuf};
use crate::event::{PushEvent, PushRef};
use crate::quire::Repo;
/// Path to the CI config within a bare repo, relative to the repo root.
pub const CI_FNL: &str = ".quire/ci.fnl";
/// Access to CI operations for a single repo.
///
/// Provides pipeline compilation and validation scoped to a bare
/// repo. Obtain one via `Repo::ci()`. Run lifecycle is on `Runs`,
/// obtainable via `Repo::runs()`.
pub struct Ci {
repo_path: PathBuf,
}
impl Ci {
pub fn new(repo_path: PathBuf) -> Self {
Self { repo_path }
}
/// Read and compile ci.fnl at a given SHA, returning the validated
/// pipeline.
///
/// Pure compilation and structural validation. Secrets are not needed
/// here — they are passed to `run.execute` since they only matter
/// when the run-fns actually fire.
///
/// Returns `Ok(None)` if the repo has no ci.fnl at that commit.
/// Errors if the Fennel source fails to parse/evaluate or if the
/// resulting job graph violates any structural rule.
pub fn pipeline(&self, commit: &CommitRef) -> error::Result<Option<Pipeline>> {
let Some(source) = self.source(&commit.sha)? else {
return Ok(None);
};
Ok(Some(pipeline::compile(&source, CI_FNL)?))
}
/// Read the contents of `.quire/ci.fnl` at a given commit SHA.
///
/// Returns `Ok(None)` if the file does not exist at that commit,
/// `Ok(Some(contents))` if it does, or `Err` for unexpected failures.
fn source(&self, sha: &str) -> error::Result<Option<String>> {
let output = self
.git(&["show", &format!("{sha}:{CI_FNL}")])
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
if stderr.contains("does not exist") || stderr.contains("not found") {
return Ok(None);
}
return Err(error::Error::Git(format!(
"failed to read {CI_FNL} at {sha}: {stderr}"
)));
}
Ok(Some(String::from_utf8(output.stdout)?))
}
/// Start a git command rooted in this repo.
fn git(&self, args: &[&str]) -> std::process::Command {
let mut cmd = std::process::Command::new("git");
cmd.args(args).current_dir(&self.repo_path);
cmd
}
}
/// Everything needed to run CI for refs in a single push event, constant
/// across all refs.
struct TriggerContext<'a> {
run: RunContext<'a>,
event_repo: &'a str,
port: u16,
sentry_dsn: Option<String>,
}
/// Repo-level context passed into the inner execution function.
struct RunContext<'a> {
repo: &'a Repo,
db_path: &'a Path,
executor: Executor,
}
/// Trigger CI for a push event: scan each updated ref for `.quire/ci.fnl`,
/// create a run, and evaluate + validate it.
pub fn trigger(quire: &crate::Quire, event: &PushEvent) {
let repo = match quire.repo(&event.repo) {
Ok(r) => r,
Err(e) => {
tracing::error!(repo = %event.repo, error = %e, "failed to resolve repo");
return;
}
};
let config = &quire.config;
let sentry_dsn = config.sentry.as_ref().and_then(|s| match s.dsn.reveal() {
Ok(dsn) => Some(dsn.to_string()),
Err(e) => {
tracing::warn!(
error = &e as &(dyn std::error::Error + 'static),
"failed to resolve Sentry DSN, quire-ci runs will skip Sentry",
);
None
}
});
let db_path = quire.db_path();
let ctx = TriggerContext {
run: RunContext {
repo: &repo,
db_path: &db_path,
executor: config.ci.executor,
},
event_repo: &event.repo,
port: config.port,
sentry_dsn,
};
for push_ref in event.updated_refs() {
run_ref(&ctx, event.pushed_at, push_ref);
}
}
/// Set up Sentry trace scope and run CI for a single ref.
fn run_ref(ctx: &TriggerContext<'_>, pushed_at: jiff::Timestamp, push_ref: &PushRef) {
let session = ApiSession::new(ctx.port);
let span = tracing::info_span!("quire.ci.run", repo = %ctx.event_repo);
let traceparent = {
let mut injector = std::collections::HashMap::new();
opentelemetry::global::get_text_map_propagator(|p| {
p.inject_context(&span.context(), &mut injector)
});
injector.remove("traceparent")
};
let _guard = span.enter();
sentry::with_scope(
|scope| {
scope.set_tag("repo", ctx.event_repo);
// TraceContext is now managed by sentry-opentelemetry
},
|| {
if let Err(e) = run_ref_inner(
&ctx.run,
pushed_at,
push_ref,
&session,
traceparent.as_deref(),
ctx.sentry_dsn.as_deref(),
) {
tracing::error!(
repo = %ctx.event_repo,
sha = %push_ref.new_sha, // cov-excl-line
error = &e as &(dyn std::error::Error + 'static),
"CI trigger failed",
);
}
},
);
}
/// Create and run CI for a single updated ref.
fn run_ref_inner(
ctx: &RunContext<'_>,
pushed_at: jiff::Timestamp,
push_ref: &PushRef,
session: &ApiSession,
traceparent: Option<&str>,
sentry_dsn: Option<&str>,
) -> error::Result<()> {
let ci = ctx.repo.ci();
if ci.source(&push_ref.new_sha)?.is_none() {
return Ok(());
}
let meta = RunMeta {
sha: push_ref.new_sha.clone(),
r#ref: push_ref.ref_name.clone(),
pushed_at,
};
let run = ctx.repo.runs(ctx.db_path).create(&meta, Some(session))?;
// The run id only exists post-create, after run_ref already opened
// the scope; mutate that scope so the tag also covers the "CI
// trigger failed" event run_ref emits if this fn returns Err.
sentry::configure_scope(|scope| scope.set_tag("run_id", run.id()));
tracing::info!(
run_id = %run.id(), // cov-excl-line
sha = %push_ref.new_sha,
ref_name = %push_ref.ref_name,
"created CI run"
);
let workspace = run.path().join("workspace");
run::materialize_workspace(&ctx.repo.path(), &push_ref.new_sha, &workspace)?;
match ctx.executor {
Executor::Process => {
// Compilation happens inside quire-ci so a malformed ci.fnl is
// reported once, with the worker's trace context.
run.execute(
&ctx.repo.path(),
&workspace,
traceparent,
sentry_dsn,
Some(session),
)?;
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Quire;
use crate::event::PushRef;
use std::path::Path;
fn git_in(cwd: &Path, args: &[&str]) {
let output = std::process::Command::new("git")
.args(args)
.current_dir(cwd)
.env("GIT_AUTHOR_NAME", "test")
.env("GIT_AUTHOR_EMAIL", "test@test")
.env("GIT_COMMITTER_NAME", "test")
.env("GIT_COMMITTER_EMAIL", "test@test")
.env("GIT_CONFIG_GLOBAL", "/dev/null")
.env("GIT_CONFIG_SYSTEM", "/dev/null")
.output()
.expect("git command");
assert!(output.status.success());
}
/// Create a bare repo with one commit containing `.quire/ci.fnl`.
/// Returns the tempdir, the Quire, and the repo name.
fn bare_repo_with_ci(source: &str) -> (tempfile::TempDir, Quire, String) {
let dir = tempfile::tempdir().expect("tempdir");
let work = dir.path().join("work");
let bare = dir.path().join("repos").join("test.git");
fs_err::create_dir_all(&work).expect("mkdir work");
git_in(&work, &["init", "-b", "main"]);
git_in(&work, &["commit", "--allow-empty", "-m", "initial"]);
let ci_dir = work.join(".quire");
fs_err::create_dir_all(&ci_dir).expect("mkdir .quire");
fs_err::write(ci_dir.join("ci.fnl"), source).expect("write ci.fnl");
git_in(&work, &["add", "."]);
git_in(&work, &["commit", "-m", "add ci.fnl"]);
git_in(
work.parent().unwrap(),
&[
"clone",
"--bare",
work.to_str().unwrap(),
bare.to_str().unwrap(),
],
);
let quire = Quire::load(dir.path().to_path_buf()).expect("load");
// Initialize the database.
let mut db = crate::db::open(&quire.db_path()).expect("init db");
crate::db::migrate(&mut db).expect("migrate db");
drop(db);
(dir, quire, "test.git".to_string())
}
fn bare_repo_without_ci() -> (tempfile::TempDir, Quire, String) {
let dir = tempfile::tempdir().expect("tempdir");
let work = dir.path().join("work");
let bare = dir.path().join("repos").join("test.git");
fs_err::create_dir_all(&work).expect("mkdir work");
git_in(&work, &["init", "-b", "main"]);
git_in(&work, &["commit", "--allow-empty", "-m", "initial"]);
git_in(
work.parent().unwrap(),
&[
"clone",
"--bare",
work.to_str().unwrap(),
bare.to_str().unwrap(),
],
);
let quire = Quire::load(dir.path().to_path_buf()).expect("load");
let mut db = crate::db::open(&quire.db_path()).expect("init db");
crate::db::migrate(&mut db).expect("migrate db");
drop(db);
(dir, quire, "test.git".to_string())
}
fn head_sha(repo: &crate::quire::Repo) -> String {
let output = std::process::Command::new("git")
.args(["-C", repo.path().to_str().unwrap(), "rev-parse", "HEAD"])
.output()
.expect("rev-parse");
String::from_utf8(output.stdout).unwrap().trim().to_string()
}
#[test]
fn ci_pipeline_returns_none_when_no_ci_fnl() {
let (_dir, quire, name) = bare_repo_without_ci();
let repo = quire.repo(&name).expect("repo");
let ci = repo.ci();
let sha = head_sha(&repo);
let commit = CommitRef {
sha: sha.clone(),
display: sha,
};
let result = ci.pipeline(&commit).expect("pipeline should not error");
assert!(result.is_none(), "no ci.fnl should return None");
}
#[test]
fn ci_pipeline_returns_pipeline_when_ci_fnl_present() {
let source = r#"(local ci (require :quire.ci))
(ci.job :build [:quire/push] (fn [] nil))"#;
let (_dir, quire, name) = bare_repo_with_ci(source);
let repo = quire.repo(&name).expect("repo");
let ci = repo.ci();
let sha = head_sha(&repo);
let commit = CommitRef {
sha: sha.clone(),
display: sha,
};
let pipeline = ci
.pipeline(&commit)
.expect("pipeline should succeed")
.expect("should have pipeline");
// 2 = 1 user job (`build`) + the built-in `quire/push` job
// that `compile` appends to every pipeline.
assert_eq!(pipeline.job_count(), 2);
assert!(pipeline.job("build").is_some());
assert!(pipeline.job("quire/push").is_some());
}
#[test]
fn ci_pipeline_errors_on_invalid_fennel() {
let source = "{:bad {:}";
let (_dir, quire, name) = bare_repo_with_ci(source);
let repo = quire.repo(&name).expect("repo");
let ci = repo.ci();
let sha = head_sha(&repo);
let commit = CommitRef {
sha: sha.clone(),
display: sha,
};
let result = ci.pipeline(&commit);
assert!(result.is_err(), "bad Fennel should fail");
}
fn run_ctx<'a>(repo: &'a crate::quire::Repo, db_path: &'a std::path::Path) -> RunContext<'a> {
RunContext {
repo,
db_path,
executor: Executor::Process,
}
}
/// Serialize PATH mutations so concurrent tests don't observe each
/// other's fake binaries.
static PATH_MUTEX: std::sync::Mutex<()> = std::sync::Mutex::new(());
/// Create a temp directory containing a fake `quire-ci` that exits
/// with the given code. Returns the temp dir (for lifetime) and the
/// new PATH value.
fn fake_quire_ci(exit_code: i32) -> (tempfile::TempDir, std::ffi::OsString) {
let dir = tempfile::tempdir().expect("tempdir for fake quire-ci");
if cfg!(unix) {
let path = dir.path().join("quire-ci");
// For a clean exit, write RunFinished(success) to the --events
// file so the server can determine the outcome from events alone.
let script = if exit_code == 0 {
r#"#!/bin/sh
events=
while [ $# -gt 0 ]; do
case "$1" in
--events) events="$2"; shift 2 ;;
*) shift ;;
esac
done
if [ -n "$events" ] && [ "$events" != "null" ]; then
printf '{"at_ms":0,"type":"run_finished","outcome":"succeeded"}\n' > "$events"
fi
exit 0
"#
.to_string()
} else {
format!("#!/bin/sh\nexit {exit_code}\n")
};
fs_err::write(&path, script).expect("write fake quire-ci");
use std::os::unix::fs::PermissionsExt;
fs_err::set_permissions(&path, std::fs::Permissions::from_mode(0o755))
.expect("chmod fake quire-ci");
} else {
let path = dir.path().join("quire-ci.bat");
fs_err::write(&path, format!("@echo off\nexit /b {exit_code}\n"))
.expect("write fake quire-ci");
}
let old_path = std::env::var_os("PATH").unwrap_or_default();
let mut new_path = dir.path().as_os_str().to_owned();
new_path.push(std::ffi::OsString::from(if cfg!(windows) {
";"
} else {
":"
}));
new_path.push(&old_path);
(dir, new_path)
}
/// Run a closure with a modified PATH, restoring it afterward.
/// Acquires a global mutex so concurrent tests don't race on PATH.
fn with_path<F, R>(new_path: &std::ffi::OsString, f: F) -> R
where
F: FnOnce() -> R,
{
let _guard = PATH_MUTEX.lock().unwrap();
let old = std::env::var_os("PATH").unwrap_or_default();
// SAFETY: the mutex guarantees no other thread is reading or
// writing PATH during this scope.
unsafe {
std::env::set_var("PATH", new_path);
}
let result = f();
unsafe {
std::env::set_var("PATH", &old);
}
result
}
#[test]
fn run_ref_inner_drives_run_to_succeeded_with_fake_quire_ci() {
let source = r#"(local ci (require :quire.ci))
(ci.job :build [:quire/push] (fn [] nil))"#;
let (_dir, quire, name) = bare_repo_with_ci(source);
let repo = quire.repo(&name).expect("repo");
let sha = head_sha(&repo);
let pushed_at: jiff::Timestamp = "2026-04-28T12:00:00Z".parse().unwrap();
let push_ref = PushRef {
old_sha: "0000000000000000000000000000000000000000".to_string(),
new_sha: sha.clone(),
ref_name: "refs/heads/main".to_string(),
};
let (_fake_dir, fake_path) = fake_quire_ci(0);
let db_path = quire.db_path();
let ctx = run_ctx(&repo, &db_path);
let trigger_result = with_path(&fake_path, || {
run_ref_inner(
&ctx,
pushed_at,
&push_ref,
&ApiSession::new(3000),
None,
None,
)
});
trigger_result.expect("trigger_ref should succeed with fake quire-ci");
// The run should have reached succeeded.
let conn = crate::db::open(&quire.db_path()).expect("db");
let outcome: Option<String> = conn
.query_row(
"SELECT outcome FROM runs WHERE sha = ?1",
rusqlite::params![&sha],
|row| row.get(0),
)
.expect("should have a run");
assert_eq!(
outcome.as_deref(),
Some("succeeded"),
"run should be succeeded after fake quire-ci exits 0"
);
// No unresolved rows left behind.
let count: i64 = conn
.query_row(
"SELECT COUNT(*) FROM runs WHERE outcome IS NULL",
[],
|row| row.get(0),
)
.expect("count");
assert_eq!(count, 0, "run should be succeeded, not orphaned");
}
#[test]
fn run_ref_inner_transitions_to_failed_when_process_crashes() {
let source = r#"(local ci (require :quire.ci))
(ci.job :build [:quire/push] (fn [] nil))"#;
let (_dir, quire, name) = bare_repo_with_ci(source);
let repo = quire.repo(&name).expect("repo");
let sha = head_sha(&repo);
let pushed_at: jiff::Timestamp = "2026-04-28T12:00:00Z".parse().unwrap();
let push_ref = PushRef {
old_sha: "0000000000000000000000000000000000000000".to_string(),
new_sha: sha.clone(),
ref_name: "refs/heads/main".to_string(),
};
let (_fake_dir, fake_path) = fake_quire_ci(1);
let db_path = quire.db_path();
let ctx = run_ctx(&repo, &db_path);
let trigger_result = with_path(&fake_path, || {
run_ref_inner(
&ctx,
pushed_at,
&push_ref,
&ApiSession::new(3000),
None,
None,
)
});
let err = trigger_result.expect_err("should fail when quire-ci exits nonzero");
assert!(
err.to_string().contains("quire-ci exited"),
"expected ProcessFailed error, got: {err}"
);
let conn = crate::db::open(&quire.db_path()).expect("db");
let outcome: Option<String> = conn
.query_row(
"SELECT outcome FROM runs WHERE sha = ?1",
rusqlite::params![&sha],
|row| row.get(0),
)
.expect("should have a run");
assert!(
outcome
.as_deref()
.map(|o| o.starts_with("failed"))
.unwrap_or(false),
"run should be failed after quire-ci exits 1, got: {outcome:?}"
);
}
#[test]
fn trigger_skips_when_no_ci_fnl() {
let (_dir, quire, name) = bare_repo_without_ci();
let repo = quire.repo(&name).expect("repo");
let sha = head_sha(&repo);
let pushed_at: jiff::Timestamp = "2026-04-28T12:00:00Z".parse().unwrap();
let push_ref = PushRef {
old_sha: "0000000000000000000000000000000000000000".to_string(),
new_sha: sha,
ref_name: "refs/heads/main".to_string(),
};
let db_path = quire.db_path();
let ctx = run_ctx(&repo, &db_path);
run_ref_inner(
&ctx,
pushed_at,
&push_ref,
&ApiSession::new(3000),
None,
None,
)
.expect("should succeed without ci.fnl");
}
fn push_event(repo: &str, sha: &str) -> PushEvent {
PushEvent::new(
repo.to_string(),
vec![PushRef {
old_sha: "0000000000000000000000000000000000000000".to_string(),
new_sha: sha.to_string(),
ref_name: "refs/heads/main".to_string(),
}],
)
}
#[test]
fn trigger_skips_nonexistent_repo() {
let dir = tempfile::tempdir().expect("tempdir");
let quire = Quire::load(dir.path().to_path_buf()).expect("load");
let event = push_event("no-such.git", "abc123");
// Should not panic — just logs and returns.
trigger(&quire, &event);
}
#[test]
fn trigger_skips_repo_not_on_disk() {
let dir = tempfile::tempdir().expect("tempdir");
let quire = Quire::load(dir.path().to_path_buf()).expect("load");
// repo name is valid but directory doesn't exist.
let event = push_event("missing.git", "abc123");
trigger(&quire, &event);
}
#[test]
fn trigger_skips_invalid_repo_name() {
let dir = tempfile::tempdir().expect("tempdir");
let quire = Quire::load(dir.path().to_path_buf()).expect("load");
// Repo name with path traversal — quire.repo() returns Err.
let event = push_event("../evil.git", "abc123");
trigger(&quire, &event);
}
#[test]
fn trigger_processes_multiple_refs() {
let source = r#"(local ci (require :quire.ci))
(ci.job :build [:quire/push] (fn [] nil))"#;
let (_dir, quire, name) = bare_repo_with_ci(source);
let repo = quire.repo(&name).expect("repo");
let sha = head_sha(&repo);
let _pushed_at: jiff::Timestamp = "2026-04-28T12:00:00Z".parse().unwrap();
// Two updated refs — both should create runs.
let event = PushEvent::new(
name.clone(),
vec![
PushRef {
old_sha: "0000000000000000000000000000000000000000".to_string(),
new_sha: sha.clone(),
ref_name: "refs/heads/main".to_string(),
},
PushRef {
old_sha: "0000000000000000000000000000000000000000".to_string(),
new_sha: sha.clone(),
ref_name: "refs/tags/v1".to_string(),
},
],
);
trigger(&quire, &event);
}
#[test]
fn ci_source_errors_on_invalid_sha() {
let source = r#"(local ci (require :quire.ci))
(ci.job :build [:quire/push] (fn [] nil))"#;
let (_dir, quire, name) = bare_repo_with_ci(source);
let repo = quire.repo(&name).expect("repo");
let ci = repo.ci();
// Use a SHA that doesn't exist — git show will fail with
// "invalid object name" which doesn't match the does-not-exist filter.
let result = ci.source("abcdef1234567890");
let Err(e) = result else { unreachable!() };
let msg = e.to_string();
assert!(
msg.contains("failed to read"),
"expected git read error, got: {msg}"
);
}
}