Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ hex = "0.4.3"
strsim = "0.11.1"
schemars = "1.2.3"
globset = "0.4.22"
tempfile = "3.20.0"

[dev-dependencies]
assert_cmd = "2.0.17"
Expand Down
12 changes: 11 additions & 1 deletion docs/src/content/docs/cli.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
title: CLI
description: cigen validate, cigen generate, cigen hash and cigen explain, with every option.
description: cigen validate, cigen generate, cigen hash, cigen explain and cigen replay, with every option.
---

```text
Expand Down Expand Up @@ -183,6 +183,16 @@ With `--format json`, it prints one object with `job`, `workflow`, `inputs` (eac
`hash`), `also_hashed`, `runs_matrix`, `matrix_entry` (the entry given, or `null`) and `hash`. An unknown job is an
error that suggests the closest id.

## `cigen replay`

Estimates how many job runs cigen would have skipped over the project's git history, with no CI. It's an estimate from
a model that assumes every run passed. See [estimate skipping](/docs/replay/) for the model and every option.

```sh
cigen replay --last 100 --workflow ci
cigen replay --last 200 --config ../my-cigen.yml --format json
```

## Environment

| Variable | What it does |
Expand Down
1 change: 1 addition & 0 deletions docs/src/content/docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ what to write instead.
- `cigen generate` for GitHub Actions and CircleCI.
- `cigen hash`, which computes a job's hash from its inputs and the inputs cigen derives.
- `cigen explain`, which shows what a job's hash covers: each input, the files it matches, and the derived inputs.
- [`cigen replay`](/docs/replay/), which estimates from git history how many job runs cigen would have skipped.
- Skipping on GitHub Actions, using markers in the GitHub Actions cache.
- Deterministic output: generating twice gives the same bytes.

Expand Down
180 changes: 180 additions & 0 deletions docs/src/content/docs/replay.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
---
title: Estimate skipping
description: cigen replay estimates how many job runs cigen would have skipped over a project's git history, with no CI.
---

`cigen replay` walks a project's git history and works out, commit by commit, which jobs cigen would have run and which
it would have skipped. It needs no CI and changes nothing: each commit is checked out in a temporary worktree, which is
removed afterwards.

The result is an **estimate from a model**, not a measurement of real CI. It says so in its output, and the
[model](#the-model) below says exactly what it assumes.

```sh
cigen replay --last 100 # the last 100 commits of HEAD
cigen replay v1.2.0..main # a range (first-parent history)
cigen replay --last 100 --format json # the same, as data
```

## What it does for each commit

1. Checks the commit out in the temporary worktree.
2. Loads the config: the commit's own, or the one given with `--config`.
3. Hashes every job exactly as [`cigen hash --job`](/docs/cli/#cigen-hash) does in CI, with the job's declared inputs and
everything cigen [derives](/docs/inputs/#derived-inputs): lockfiles, toolchain pins, files the steps name, the files
its modules contribute, the job's definition, and the hashes of the jobs it `needs`. So a job reruns when a job it
needs would have run, as in CI.
4. Counts the job as **skipped** if a run of the same job with the same hash already passed on an earlier commit of the
replay and its marker hasn't expired; otherwise as **ran**.

For this config, over five commits:

```yaml
# cigen.yml
provider: github
workflows:
ci:
jobs:
test:
image: rust:latest
inputs: ['src/**', 'tests/**']
steps:
- run: cargo test --locked
docs:
image: node:24
inputs: ['docs/**']
steps:
- run: npm run docs
audit:
image: rust:latest
steps:
- run: cargo audit
```

```text
$ cigen replay --last 5 --commits --durations durations.json
cigen replay: an estimate from git history, not a measurement.
Model: every run passed; a job skips when its hash already ran on an earlier commit of this replay; first-parent history of one branch; a pass expires after 7 days unused (by commit date).
Note: workflow triggers (`on:`) aren't modelled: every replayed workflow runs on every commit.
Note: a matrix job counts once per commit, as one job id.
Note: pull requests aren't modelled: in CI they can also reuse the branch's passes.
Config: each commit's own
Workflows: all (use --workflow to choose)
Commits: 5

615812012b 2026-01-01 Add the parser: ran audit, docs, test; skipped nothing
76fca80472 2026-01-02 Fix a typo in the README: ran audit; skipped docs, test
b7c0e0c390 2026-01-03 Handle empty input: ran audit, test; skipped docs
df2ea18bc3 2026-01-04 Update serde: ran audit, docs, test; skipped nothing
408a909d43 2026-01-05 Document the parser: ran audit, docs; skipped test

job ran skipped skip rate
audit 5 0 0% (no inputs: always runs)
docs 3 2 40%
test 3 2 40%

Skipped 4 of 15 job runs (26.7%).
Estimated CI minutes saved: 30 of 85.
```

"Update serde" changed only `Cargo.lock`, which no job lists in its `inputs`, and both jobs still ran: the lockfile is a
derived input. `audit` has no `inputs`, so CI never skips it, and neither does the replay.

## The model

Everything the estimate assumes:

- **Every run passed.** Replay reads no CI history, so it can't know which runs failed. A failed run records no pass in
real CI, so a project with failures skips less than the estimate says.
- **One branch, first-parent history.** It models pushes to one branch, such as `main`, one commit at a time. Commits
that came in on a merged branch aren't replayed. Pull requests aren't modelled; in CI they can also reuse the branch's
passes.
- **Passes expire after 7 days unused**, measured by commit date, as GitHub's cache evicts entries nobody has read for 7
days. A hit refreshes the marker. `--no-expiry` turns this off.
- **Triggers aren't modelled.** Every replayed workflow counts on every commit, including workflows that only run on
tags or on some paths. Use `--workflow` to pick the workflows that run on every push.
- **A matrix job counts once** per commit, as one job id, not once per combination.
- **The first commit runs everything**: there are no passes yet, as when a project starts using cigen.
- **The hash comes from the cigen you run.** Its version is part of every hash, so it's the same for the whole replay.

## Trying cigen on a project that doesn't use it yet

A project that has never used cigen has no config in its history. Write one, keep it outside the repository's history
(or uncommitted), and pass it with `--config`. Replay then applies that config to every commit and hashes each commit's
own files:

```sh
cigen replay --last 200 --config ../my-cigen.yml --workflow ci --durations ../durations.json
```

Without `--config`, replay uses each commit's own config. A commit with no config is listed with `no_config` and left out
of the counts. A commit whose config this version of cigen can't load (often one written for an older version, before
the schema became strict) is listed with `config_error` and left out too; the text output shows the first error.

## Options

| Option | What it does |
| --------------------- | ------------------------------------------------------------------------------------------ |
| `<from>..<to>` | The commits to replay, as git reads a range. Only first-parent commits are replayed. |
| `--last <N>` | The last N first-parent commits of HEAD, in place of a range. |
| `-c`, `--config` | A `cigen.yml` or `.cigen/` to apply to every commit, in place of each commit's own. |
| `--repo <dir>` | The repository to replay. Default: the current directory. |
| `--workflow <name>` | Replay only this workflow. Repeat it for several. |
| `--no-expiry` | Never expire a pass. |
| `--durations <file>` | Average minutes per run, by job (`{"test": 12, "docs": 3}`), to estimate CI minutes saved. |
| `--commits` | List every commit with the jobs it ran and skipped (text output). |
| `--format text\|json` | Text (the default) or JSON. |

With `--durations`, minutes are counted only for the jobs in the file; the others are named in the output
(`minutes_unknown` in JSON) rather than guessed.

## JSON

`--format json` prints one object. Every field of the model is in it, so a number is never shown without its
assumptions:

```json
{
"estimate": true,
"model": {
"assume_pass": true,
"branch": "first-parent",
"expiry_days": 7,
"workflows": null,
"config": "per-commit",
"notes": [
"workflow triggers (`on:`) aren't modelled: every replayed workflow runs on every commit."
]
},
"range": { "from": "615812012b…", "to": "408a909d43…", "commits": 5 },
"commits": [
{
"sha": "df2ea18bc3…",
"date": "2026-01-04T00:00:00Z",
"subject": "Update serde",
"ran": ["audit", "docs", "test"],
"skipped": []
}
],
"jobs": {
"test": {
"ran": 3,
"skipped": 2,
"skip_rate": 0.4,
"always_runs": false,
"minutes_per_run": 12.0
}
},
"totals": {
"job_runs": 15,
"ran": 11,
"skipped": 4,
"skip_rate": 0.26666666666666666,
"minutes_total": 85.0,
"minutes_saved": 30.0
}
}
```

`expiry_days` is `null` with `--no-expiry`, `workflows` is `null` when every workflow is replayed, and `config` is
`per-commit` or the path given with `--config`. A commit can also carry `no_config: true` or a `config_error`.
2 changes: 2 additions & 0 deletions docs/src/content/docs/roadmap.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ right. This page lists what's planned. Nothing on it exists yet; what exists is
no 7-day eviction, batch lookup, and a history of why each job ran. Records hold hashes, job names and who wrote them,
never code.
7. **CircleCI parity**, including skipping in the setup workflow.
8. **Replay against real CI history.** [`cigen replay`](/docs/replay/) assumes every run passed today; reading which runs
actually passed from a CI provider's history would make its estimate closer to what CI did.

## Not planned

Expand Down
2 changes: 1 addition & 1 deletion docs/src/lib/docs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export const sections: { title: string; pages: string[] }[] = [
title: "Configure",
pages: ["configuration", "jobs", "steps-and-commands", "inputs", "modules"],
},
{ title: "Run", pages: ["skipping", "providers", "cli"] },
{ title: "Run", pages: ["skipping", "replay", "providers", "cli"] },
{ title: "Project", pages: ["roadmap"] },
];

Expand Down
13 changes: 13 additions & 0 deletions internal_docs/STATUS.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,14 @@ What the code does today, checked against the code in December 2026. Where cigen
generated step passes no `--modules-digest` for the needed job): a one-time rerun of those jobs, never a skip. For a
job that runs GitHub's matrix, explain says each entry is hashed in, and with `--matrix` it shows that entry's hash
(`src/hashing/matrix.rs` mixes the entry into the job's hash, for `hash --matrix` too).
`cigen replay (<from>..<to> | --last N) [--config <path>] [--workflow <name>] [--no-expiry] [--durations <file>]
[--format text|json]` (`src/replay/`) estimates skipping from git history: it checks each first-parent commit out in
a temporary worktree, hashes every job with `hashing::hash_job` (modules and `needs` included, as in CI; git runs
through `cigen::git::command`), and counts a run as skipped when the same job and
hash ran on an earlier commit and its marker hasn't gone 7 days unused (by commit date; a hit refreshes it). It
assumes every run passed (no CI history is read), doesn't model workflow triggers, pull requests or matrix
combinations, and says so in its output. `--config` applies one config to every commit, for projects whose history
has none; otherwise commits with no config, or one this cigen can't load, are listed and left out of the counts.
- **Config loading** (`src/config/`, `src/schema/`): one schema in two layouts. `cigen.yml` is the whole document;
`.cigen/` is the same document split into files (`config.yml` and `config/*.yml` for the top level,
`commands/<name>.yml`, `workflows/<name>.yml` or `workflows/<name>/config.yml` for a workflow's settings, and
Expand Down Expand Up @@ -146,6 +154,11 @@ What the code does today, checked against the code in December 2026. Where cigen
- `tests/explain.rs`: `cigen explain` lists declared and derived inputs (module inputs included) with their files and
the jobs a job needs, in JSON and text, and its hash equals `cigen hash --job`'s before and after an input, a module
input or a needed job changes, and for a matrix entry.
- `tests/replay.rs`: `cigen replay` over histories built in the test, with exact counts: an unchanged input skips, a
change outside the inputs skips, a lockfile change (a derived input) runs, a revert skips, a job definition change
runs, a marker expires after 7 idle days and a hit refreshes it, a range replays first-parent commits only,
`--config` applies to a history with no config, `--workflow` filters, and durations give minutes saved.
- `tests/replay_needs.rs`: a job reruns when a job it `needs` changed.
- `tests/derived_inputs.rs`: changing a script a step runs, a command the job uses, a toolchain pin or the
`package.json` script that `npm run test` runs (the root's or a sub-package's) makes the job run in mockci, and changing a used command, a named service, a top-level provider block, a local action, a lockfile or the
`packageManager` pin changes the job's hash; an unused command or service doesn't.
Expand Down
2 changes: 2 additions & 0 deletions src/commands/mod.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
mod explain;
mod generate;
mod hash;
mod replay;
pub mod report;
mod validate;

pub use explain::{ExplainArgs, explain_command};
pub use generate::generate_command;
pub use hash::{HashArgs, hash_command};
pub use replay::{ReplayArgs, replay_command};
pub use validate::{ValidateArgs, validate_command};
105 changes: 105 additions & 0 deletions src/commands/replay.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
use super::report::{OutputFormat, print_json};
use anyhow::{Context, Result, bail};
use cigen::replay::{GITHUB_EXPIRY_DAYS, Options, Range, replay};
use clap::Args;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

/// Arguments for `cigen replay`.
#[derive(Debug, Args)]
pub struct ReplayArgs {
/// Commits to replay: `<from>..<to>` (first-parent history). Use `--last` instead for the
/// latest commits of HEAD
#[arg(value_name = "RANGE", conflicts_with = "last")]
pub range: Option<String>,

/// Replay the last N first-parent commits of HEAD
#[arg(long, value_name = "N")]
pub last: Option<usize>,

/// A cigen.yml or .cigen/ to apply to every commit, in place of each commit's own config.
/// Use it to try cigen on a project whose history has no cigen config
#[arg(short, long)]
pub config: Option<PathBuf>,

/// The git repository to replay
#[arg(long, default_value = ".")]
pub repo: PathBuf,

/// Replay only this workflow (repeatable). Triggers aren't modelled, so pick the workflows
/// that run on every push
#[arg(long = "workflow", value_name = "NAME")]
pub workflows: Vec<String>,

/// Never expire a pass. By default a pass expires after 7 days unused, as GitHub's cache
/// evicts it
#[arg(long)]
pub no_expiry: bool,

/// A JSON file of average minutes per job (`{"test": 12.5}`), to estimate minutes saved
#[arg(long, value_name = "FILE")]
pub durations: Option<PathBuf>,

/// List every commit with the jobs it ran and skipped (text output)
#[arg(long)]
pub commits: bool,

/// Output format
#[arg(long, value_enum, default_value_t = OutputFormat::Text)]
pub format: OutputFormat,
}

pub fn replay_command(args: ReplayArgs) -> Result<()> {
let range = match (args.last, args.range) {
(Some(0), _) => bail!("`--last` needs at least 1 commit"),
(Some(count), _) => Range::Last(count),
(None, Some(spec)) if spec.contains("..") => Range::Between(spec),
(None, Some(spec)) => bail!(
"`{spec}` isn't a range: write `<from>..<to>`, or use `--last <N>` for the latest \
commits"
),
(None, None) => bail!("say which commits to replay: `--last <N>` or `<from>..<to>`"),
};
let durations = args.durations.as_deref().map(load_durations).transpose()?;
let options = Options {
repo: args.repo,
range,
config: args.config.map(absolute).transpose()?,
expiry_days: (!args.no_expiry).then_some(GITHUB_EXPIRY_DAYS),
workflows: args.workflows,
durations,
};
eprintln!("Replaying history (an estimate; see `cigen replay --help`)...");
let report = replay(&options)?;
match args.format {
OutputFormat::Json => print_json(&report),
OutputFormat::Text => {
print!("{}", report.to_text(args.commits));
Ok(())
}
}
}

/// The config is read outside the worktree, so a relative path is resolved here, once.
fn absolute(path: PathBuf) -> Result<PathBuf> {
std::fs::canonicalize(&path)
.with_context(|| format!("can't find the config at {}", path.display()))
}

fn load_durations(path: &Path) -> Result<BTreeMap<String, f64>> {
let text = std::fs::read_to_string(path)
.with_context(|| format!("can't read the durations file {}", path.display()))?;
let durations: BTreeMap<String, f64> = serde_json::from_str(&text).with_context(|| {
format!(
"{} must be a JSON object of minutes per job, such as {{\"test\": 12.5}}",
path.display()
)
})?;
if let Some((job, minutes)) = durations.iter().find(|(_, m)| !m.is_finite() || **m < 0.0) {
bail!(
"{}: `{job}` has {minutes} minutes; durations must be 0 or more",
path.display()
);
}
Ok(durations)
}
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@ pub mod modules;
pub mod orchestrator;
pub mod pathspec;
pub mod plugin;
pub mod replay;
pub mod schema;
Loading
Loading