summaryrefslogtreecommitdiffstats
path: root/src/pipeline/steps.rs
blob: c9894765997ebe1a71ac0161324d649ecb05062f (plain)
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
//! The ten pipeline steps (§8.1).
//!
//! Every step is idempotent and records its result in one short transaction;
//! the long-running child process happens outside any transaction (§11a).

use std::path::Path;

use crate::db::{self, builds, model::*};
use crate::error::{Error, Result};
use crate::git;
use crate::pipeline::{Collect, CollectedPkg, Ctx, StepResult};
use crate::sandbox::Cmd;
use crate::watch::digests::cached_path;

pub fn run_step(ctx: &Ctx, step: &str) -> Result<StepResult> {
    match step {
        "materialize" => materialize(ctx),
        "plan" => plan(ctx),
        "chroot" => provision(ctx),
        "sources" => sources(ctx),
        "pkgver" => pkgver(ctx),
        "build" => build(ctx),
        "collect" => collect(ctx),
        "verify" => verify(ctx),
        "ingest" => ingest(ctx),
        "publish" => publish(ctx),
        other => Err(Error::invalid(format!("unknown step {other}"))),
    }
}

/// Step 0 — materialize from the local mirror only, never the network, and
/// re-hash what we got. This is the `aur_commit` pin doing its job: there is no
/// path from "AUR moved since the review" to "we built it anyway".
fn materialize(ctx: &Ctx) -> Result<StepResult> {
    let mirror = ctx
        .pb
        .mirror_path
        .as_ref()
        .map(Path::new)
        .map(|p| p.to_path_buf())
        .unwrap_or_else(|| ctx.cfg.mirror_path(&ctx.pb.name));
    if !mirror.exists() {
        return Err(Error::fail_closed(format!(
            "mirror {} missing; refusing to fetch a recipe from the network at build time",
            mirror.display()
        )));
    }
    if ctx.src.aur_commit.is_empty() {
        return Err(Error::fail_closed("no aur_commit on the source identity"));
    }
    let _ = std::fs::remove_dir_all(&ctx.srcdir);
    git::materialize(&mirror, &ctx.src.aur_commit, &ctx.srcdir)?;
    let tree = crate::watch::mirror::read_tree(&mirror, &ctx.src.aur_commit)?;
    let computed = tree.recipe_hash();
    if !ctx.src.recipe_hash.is_empty() && computed != ctx.src.recipe_hash {
        return Err(Error::fail_closed(format!(
            "recipe_hash mismatch: approved {}, materialized {}",
            ctx.src.recipe_hash, computed
        )));
    }
    ctx.log_line(&format!(
        "    materialized {} at {} (recipe_hash {})",
        ctx.pb.name,
        short(&ctx.src.aur_commit),
        short(&computed)
    ));
    Ok(StepResult::Done(Some(computed)))
}

/// A display-safe prefix; hashes are 64 hex chars but world digests can be tiny.
fn short(s: &str) -> String {
    s.chars().take(12).collect()
}

/// Step 1 — resolve dependencies against the current accepted index and compute
/// the intended world. Unresolvable means "a pkgbase we subscribe to that we have
/// not published yet": block and wait, do not fail (§10.4).
fn plan(ctx: &Ctx) -> Result<StepResult> {
    let recipe = recipe_at(&ctx.srcdir)?;
    let mut wanted: Vec<String> = Vec::new();
    for list in [&recipe.depends, &recipe.makedepends, &recipe.checkdepends] {
        wanted.extend(crate::pkgver::dep_names(list));
    }
    wanted.sort();
    wanted.dedup();

    let ours = db::our_package_names(&ctx.db)?;
    let mut missing = Vec::new();
    let mut official = 0;
    for dep in &wanted {
        if ours.contains(dep) || ctx.pb.name == *dep || recipe.pkgnames.contains(dep) {
            continue; // satisfied by our own index, or by this very build
        }
        // Anything else is only a problem if we are supposed to be publishing it.
        if db::get_subscription(&ctx.db, dep)?.is_some() || db::get_pkgbase(&ctx.db, dep)?.is_some() {
            missing.push(dep.clone());
        } else {
            official += 1;
        }
    }
    if !missing.is_empty() {
        builds::set_blocked_on(&ctx.db, &ctx.build.id, &missing)?;
        return Ok(StepResult::Blocked(missing));
    }
    let world = crate::pipeline::publish::index_world(&ctx.db)?;
    let hash = crate::hash::canonical_json(&world)?;
    ctx.log_line(&format!(
        "    deps: {} ours/official, {} from official repos, world {}",
        wanted.len() - official,
        official,
        short(&hash)
    ));
    Ok(StepResult::Done(Some(hash)))
}

/// Step 2 — provision the sandbox with the pinned lease set.
///
/// The devtools chroot is gone: the sandbox boots from a base that already
/// carries the official packages, and everything *we* publish that this build
/// needs arrives as content-addressed blobs installed with `pacman -U`. The
/// step id stays `chroot` in the checkpoint table — the DB does not care what
/// the string means, and renaming would strand every existing checkpoint row.
///
/// Nothing is resolved at build time: the lease manifest is the plan, every
/// blob is re-hashed before it is staged, and the sandbox's own `pacman -Q`
/// must confirm the pinned world actually landed. A byte that hashes to
/// something else, or a world that drifted, fails the build closed.
fn provision(ctx: &Ctx) -> Result<StepResult> {
    let lease = lease_manifest(ctx)?;
    if lease.is_empty() {
        return Ok(StepResult::Skipped("no of-our-packages dependencies to install".into()));
    }
    let sbx = ctx.sandbox()?;
    for e in &lease {
        let path = ctx.cfg.store_path(&e.digest);
        // The hub hashes what it sends: store corruption is caught here, not
        // discovered by a confused package manager inside the sandbox.
        let (digest, _) = crate::hash::digest_file(&path)?;
        if digest != e.digest {
            return Err(Error::fail_closed(format!(
                "lease artifact {}-{}: store bytes hash to {digest} but the index says {}",
                e.name, e.version, e.digest
            )));
        }
        let mut f = std::fs::File::open(&path)?;
        sbx.put(&e.digest, &mut f)?;
    }
    let mut argv = vec![ctx.cfg.pacman_bin.clone(), "-U".into(), "--noconfirm".into()];
    argv.extend(lease.iter().map(|e| format!("blob:{}", e.digest)));
    let out = sbx.run(&Cmd::new(argv), &mut |_| {})?;
    if !out.success() {
        return Err(Error::fail_closed(format!(
            "{} -U refused the lease set: {}",
            ctx.cfg.pacman_bin,
            tail(&out.stderr)
        )));
    }
    // Fail-closed world check: every pinned entry must be present in the
    // sandbox at exactly the pinned version. The world we approved is the
    // world we build in, or nothing.
    let q = sbx.run(&Cmd::new(vec![ctx.cfg.pacman_bin.clone(), "-Q".into()]), &mut |_| {})?;
    if !q.success() {
        return Err(Error::fail_closed(format!(
            "{} -Q failed: {}",
            ctx.cfg.pacman_bin,
            tail(&q.stderr)
        )));
    }
    let installed: std::collections::BTreeSet<(String, String)> = String::from_utf8_lossy(&q.stdout)
        .lines()
        .filter_map(|l| {
            let mut it = l.split_whitespace();
            let (name, ver) = (it.next()?, it.next()?);
            Some((name.to_string(), ver.to_string()))
        })
        .collect();
    for e in &lease {
        if !installed.contains(&(e.name.clone(), e.version.clone())) {
            return Err(Error::fail_closed(format!(
                "sandbox world is missing {}-{} after installing the lease set",
                e.name, e.version
            )));
        }
    }
    ctx.log_line(&format!(
        "    provisioned {} pinned package(s): {}",
        lease.len(),
        lease.iter().map(|e| format!("{}-{}", e.name, e.version)).collect::<Vec<_>>().join(", ")
    ));
    let world: Vec<(&str, &str)> = lease.iter().map(|e| (e.name.as_str(), e.version.as_str())).collect();
    Ok(StepResult::Done(Some(crate::hash::canonical_json(&world)?)))
}

/// One pinned entry of the lease manifest.
#[derive(Debug, Clone)]
struct LeasePkg {
    name: String,
    version: String,
    digest: String,
}

/// The lease manifest: every dependency this build needs that we publish,
/// pinned to the exact version and digest of the artifact we serve. Official
/// packages are the base image's business — they arrive with the sandbox, and
/// pinning them is the hub's official-repo cache, not this step. Anything
/// unresolvable here would have been `plan()`'s problem (blocked, not built).
fn lease_manifest(ctx: &Ctx) -> Result<Vec<LeasePkg>> {
    let recipe = recipe_at(&ctx.srcdir)?;
    let mut wanted: Vec<String> = Vec::new();
    for list in [&recipe.depends, &recipe.makedepends, &recipe.checkdepends] {
        wanted.extend(crate::pkgver::dep_names(list));
    }
    wanted.sort();
    wanted.dedup();
    let mut out = Vec::new();
    for dep in wanted {
        if dep == ctx.pb.name || recipe.pkgnames.contains(&dep) {
            continue; // this build's own output is not its own dependency
        }
        if let Some((version, digest)) = db::index_artifact(&ctx.db, &dep)? {
            out.push(LeasePkg { name: dep, version, digest });
        }
    }
    Ok(out)
}

/// Step 3 — make sure every source we reviewed is on disk and hashes to what the
/// candidate recorded. For a `SKIP` source this is the only verification that
/// exists, and it closes the window between "we hashed it at review time" and
/// "makepkg downloaded something else just now" (§8.1).
fn sources(ctx: &Ctx) -> Result<StepResult> {
    let digests: Vec<SourceDigest> = serde_json::from_str(&ctx.src.source_digests_json).unwrap_or_default();
    let mut verified = 0;
    for d in &digests {
        match d.kind.as_str() {
            // Already materialized from the mirror at the pinned commit.
            "local" => verified += 1,
            // VCS kinds (git/svn/hg/bzr): honouring upstream_pins at build time
            // is deferred to P1 (§20); the pkgver assertion is the interim guard.
            "vcs" | "git" | "svn" | "hg" | "bzr" => verified += 1,
            _ => {
                let (digest, _size) = match cached_path(&ctx.db, &d.url, &d.digest) {
                    Some(p) => crate::hash::digest_file(&p)?,
                    None => crate::watch::digests::download_and_cache(&ctx.cfg, &ctx.db, &d.url)?,
                };
                if digest != d.digest {
                    return Err(Error::fail_closed(format!(
                        "source {} hashed to {digest} but the candidate recorded {}",
                        d.url, d.digest
                    )));
                }
                verified += 1;
            }
        }
    }
    ctx.log_line(&format!("    {}/{} source digests verified", verified, digests.len()));
    Ok(StepResult::Done(Some(crate::hash::hex_str(
        &ctx.src.source_digests_json,
    ))))
}

/// Step 4 — the belt-and-braces assertion that what we build is what was
/// approved. If upstream moved between approval and build, fail with both
/// versions instead of silently shipping the new one (§8.1).
fn pkgver(ctx: &Ctx) -> Result<StepResult> {
    let recipe = recipe_at(&ctx.srcdir)?;
    let has_vcs = recipe.source_entries.iter().any(|s| s.is_vcs());
    if !has_vcs {
        let want = (ctx.src.pkgver.clone(), ctx.src.pkgrel.clone());
        let got = (recipe.pkgver.clone(), recipe.pkgrel.clone());
        if want != got {
            return Err(Error::fail_closed(format!(
                "approved {}-{} but the recipe says {}-{}",
                want.0, want.1, got.0, got.1
            )));
        }
        return Ok(StepResult::Skipped("no VCS sources; pkgver is static".into()));
    }
    let cmd = vec![ctx.cfg.makepkg_bin.clone(), "--vercheck".to_string()];
    let sbx = ctx.sandbox()?;
    let out = sbx.run(&Cmd::new(cmd).in_dir(&ctx.srcdir), &mut |_| {})?;
    if !out.success() {
        return Err(Error::Subprocess {
            cmd: ctx.cfg.makepkg_bin.clone(),
            detail: String::from_utf8_lossy(&out.stderr).into_owned(),
        });
    }
    let text = String::from_utf8_lossy(&out.stdout).trim().to_string();
    let (got_ver, got_rel) = match text.rsplit_once('-') {
        Some((v, r)) => (v.to_string(), r.to_string()),
        None => (text.clone(), "1".into()),
    };
    if got_ver != ctx.src.pkgver || got_rel != ctx.src.pkgrel {
        return Err(Error::fail_closed(format!(
            "approved {}-{}, upstream now resolves to {got_ver}-{got_rel}",
            ctx.src.pkgver, ctx.src.pkgrel
        )));
    }
    ctx.log_line(&format!("    pkgver resolves as approved: {text}"));
    Ok(StepResult::Done(Some(text)))
}

/// Step 5 — `makepkg -c -f` in the provisioned sandbox, with the log going to
/// the file the SSE tail reads. No `-s`: the lease set is already installed,
/// and a build that resolves dependencies at build time is exactly what the
/// pinning model forbids. No `-si`: the sandbox never holds the signing key;
/// ingest signs hub-side.
fn build(ctx: &Ctx) -> Result<StepResult> {
    let argv = vec![ctx.cfg.makepkg_bin.clone(), "-c".into(), "-f".into()];
    // Capture the child's output into the build log regardless of outcome —
    // the sandbox streams it here as it arrives, and the SSE tail reads the
    // same file.
    if let Some(parent) = ctx.log.parent() {
        let _ = std::fs::create_dir_all(parent);
    }
    use std::io::Write;
    let mut log_file = std::fs::OpenOptions::new().create(true).append(true).open(&ctx.log).ok();
    let mut on_log = move |bytes: &[u8]| {
        if let Some(f) = log_file.as_mut() {
            let _ = f.write_all(bytes);
        }
    };
    let sbx = ctx.sandbox()?;
    let out = sbx.run(&Cmd::new(argv).in_dir(&ctx.srcdir), &mut on_log)?;
    drop(on_log); // closes the log file before the outcome is recorded
    if !out.success() {
        return Err(Error::Subprocess {
            cmd: ctx.cfg.makepkg_bin.clone(),
            detail: tail(&out.stderr),
        });
    }
    Ok(StepResult::Done(Some(crate::hash::hex_str(&format!(
        "build:{}",
        ctx.build.id
    )))))
}

fn tail(b: &[u8]) -> String {
    let s = String::from_utf8_lossy(b).trim().to_string();
    let lines: Vec<&str> = s.lines().collect();
    lines[lines.len().saturating_sub(6)..].join(" | ")
}

/// Step 6 — parse `.PKGINFO`/`.BUILDINFO` out of the produced artifacts (§10.1:
/// plain text in a tar, no libalpm needed).
fn collect(ctx: &Ctx) -> Result<StepResult> {
    let mut pkgs = Vec::new();
    let mut entries: Vec<PathBuf> = std::fs::read_dir(&ctx.srcdir)?
        .filter_map(|e| e.ok())
        .map(|e| e.path())
        .filter(|p| p.to_string_lossy().ends_with(".pkg.tar.zst"))
        .collect();
    entries.sort();
    // I9: the build is untrusted. In production it runs in a chroot, but the
    // control plane must not *depend* on that for its own safety. Everything
    // below takes a path that a PKGBUILD could have arranged to exist in the
    // srcdir, and the next step copies whatever that path points at into the
    // content-addressed store — from where it is served from our repo and signed
    // with our key. A symlink to the signing keyring, the database, or anyone's
    // home directory would otherwise become a signed artifact we publish. So:
    // no symlinks, and the resolved target must live inside this build's own
    // staging directory. Anything else fails the build closed.
    let staging_root = ctx.staging.canonicalize()?;
    for path in entries {
        if std::fs::symlink_metadata(&path).map(|m| m.file_type().is_symlink()).unwrap_or(true) {
            return Err(Error::fail_closed(format!(
                "{} is a symlink; a build may not smuggle bytes in from outside its own staging dir (I9)",
                path.display()
            )));
        }
        let resolved = path.canonicalize()?;
        if !resolved.starts_with(&staging_root) {
            return Err(Error::fail_closed(format!(
                "{} resolves outside this build's staging dir ({staging_root:?}); refusing to ingest it (I9)",
                path.display()
            )));
        }
        let path = resolved;
        let bytes = std::fs::read(&path)?;
        let (digest, size) = crate::hash::digest_file(&path)?;
        // Read what the package says about itself out of the archive, rather
        // than trusting what the build claimed on stdout (§10.1).
        let pkginfo = crate::pkginfo::pkginfo_text(&bytes)
            .map_err(|e| Error::invalid(format!("{}: {e}", path.display())))?;
        let meta = crate::pkginfo::parse_pkginfo(&pkginfo);
        // `.BUILDINFO` is what the world snapshot is built from. Absent is not
        // fatal — the snapshot is then simply empty for this package — but a
        // present-but-unparseable one would be a lie we should not swallow.
        let buildinfo = crate::pkginfo::buildinfo_text(&bytes).unwrap_or_default();
        let sig = path.with_extension("pkg.tar.zst.sig");
        pkgs.push(CollectedPkg {
            name: meta.name.clone(),
            version: meta.version.clone(),
            arch: if meta.arch.is_empty() { ctx.cfg.arch.clone() } else { meta.arch.clone() },
            path: path.display().to_string(),
            digest,
            size,
            signature_path: sig.exists().then(|| sig.display().to_string()),
            depends: meta.depends.clone(),
            makedepends: meta.makedepends.clone(),
            provides: meta.provides.clone(),
            conflicts: meta.conflicts.clone(),
            installed: crate::pkginfo::parse_installed(&buildinfo)
                .into_iter()
                .map(|i| (i.name, i.version))
                .collect(),
        });
    }
    if pkgs.is_empty() {
        return Err(Error::invalid("build produced no packages"));
    }
    let collect = Collect { packages: pkgs.clone() };
    collect.save(&ctx.collect_path)?;
    // A split pkgbase is one approval and N index entries (§3).
    ctx.log_line(&format!("    collected {}", pkgs.iter().map(|p| format!("{}-{}", p.name, p.version)).collect::<Vec<_>>().join(", ")));
    Ok(StepResult::Done(Some(crate::hash::hex_str(&serde_json::to_string(&pkgs)?))))
}

/// Step 7 — dependencies satisfiable, no downgrade. Signature checking is not
/// here: the build no longer signs (the sandbox never sees the key), so the
/// signature is made at ingest, after these checks pass.
fn verify(ctx: &Ctx) -> Result<StepResult> {
    let collect = Collect::load(&ctx.collect_path)?;
    let ours = db::our_package_names(&ctx.db)?;
    for p in &collect.packages {
        if crate::pkgver::is_downgrade(
            &db::index_version(&ctx.db, &p.name)?.unwrap_or_else(|| "0".into()),
            &p.version,
        ) {
            // Downgrades are allowed but flagged (§16); the review already shows it.
            ctx.log_line(&format!("    note: {} is a downgrade from what we serve", p.name));
        }
        let mut provided: std::collections::BTreeSet<String> = ours.clone();
        provided.extend(collect.packages.iter().map(|q| q.name.clone()));
        provided.extend(p.provides.iter().flat_map(|v| crate::pkgver::dep_names(std::slice::from_ref(v))));
        for dep in crate::pkgver::dep_names(&p.depends) {
            if !provided.contains(&dep) && db::get_pkgbase(&ctx.db, &dep)?.is_some() {
                return Err(Error::fail_closed(format!(
                    "{} depends on {dep}, which is not satisfiable in the target repo",
                    p.name
                )));
            }
        }
    }
    Ok(StepResult::Done(Some(crate::hash::hex_str(&serde_json::to_string(
        &collect.packages.iter().map(|p| (&p.name, &p.version)).collect::<Vec<_>>(),
    )?))))
}

/// Step 8 — move artifacts into the content-addressed store and record rows.
/// Staging stays disposable; a GC pass sweeps abandoned directories (§8.2).
fn ingest(ctx: &Ctx) -> Result<StepResult> {
    let mut collect = Collect::load(&ctx.collect_path)?;
    for p in &mut collect.packages {
        let from = Path::new(&p.path);
        let dest = ctx.cfg.store_path(&p.digest);
        if !dest.exists() {
            if let Some(parent) = dest.parent() {
                std::fs::create_dir_all(parent)?;
            }
            std::fs::copy(from, &dest)?;
        }
        p.path = dest.display().to_string();
        // Hub-side signing: the build environment never holds the key, so the
        // signature is made here, over the exact bytes that just entered the
        // store, by the same key that signs the database. A gpg failure fails
        // the build closed — an unsigned artifact never reaches the repo.
        if !ctx.cfg.signing_key_id.is_empty() {
            let sigdest = ctx.cfg.store_path(&format!("{}-sig", p.digest));
            if !sigdest.exists() {
                crate::pipeline::publish::sign_to(&ctx.cfg, Path::new(&p.path), &sigdest)?;
            }
            p.signature_path = Some(sigdest.display().to_string());
        }
    }
    collect.save(&ctx.collect_path)?;

    let at = crate::time::now();
    let packages = collect.packages.clone();
    let packages_for_db = packages.clone();
    let build_id = ctx.build.id.clone();
    let log_path = ctx.log.display().to_string();
    ctx.db.writer.tx(move |tx| {
        for p in &packages_for_db {
            db::insert_artifact_in(
                tx,
                &db::NewArtifact {
                    digest: &p.digest,
                    size: p.size as i64,
                    path: &p.path,
                    signature_path: p.signature_path.as_deref(),
                    build_log_path: Some(&log_path),
                    build_id: &build_id,
                    at: &at,
                },
            )?;
        }
        Ok(())
    })?;

    // §10.1: the world snapshot is the build's installed set INTERSECTED with our
    // own packages, filtered at ingest time, not at query time. Left unfiltered,
    // every package would be permanently stale because Arch never stops moving.
    let ours = db::our_package_names(&ctx.db)?;
    let mut members: Vec<WorldMember> = Vec::new();
    for p in &collect.packages {
        for (name, version) in &p.installed {
            if ours.contains(name) {
                members.push(WorldMember { pkgbase: name.clone(), version: version.clone() });
            }
        }
    }
    let world_id = db::put_world_snapshot(&ctx.db.writer, &members)?;
    builds::set_world(&ctx.db, &ctx.build.id, world_id)?;
    ctx.log_line(&format!("    ingested {} artifact(s), world has {} of our packages", packages.len(), members.len()));
    Ok(StepResult::Done(Some(crate::hash::hex_str(&format!(
        "ingest:{}",
        packages.len()
    )))))
}

/// Step 9 — the only externally visible step, serialized per repo (§9).
fn publish(ctx: &Ctx) -> Result<StepResult> {
    let release_id = crate::pipeline::publish::publish(ctx)?;
    Ok(StepResult::Done(Some(format!("release:{release_id}"))))
}

// ---------------------------------------------------------------- helpers --

use std::path::PathBuf;

/// Read the recipe from a materialized tree, preferring `.SRCINFO`.
pub(crate) fn recipe_at(dir: &Path) -> Result<Recipe> {
    let mut files = std::collections::BTreeMap::new();
    for entry in walkdir::WalkDir::new(dir).max_depth(2).into_iter().filter_map(|e| e.ok()) {
        let p = entry.path();
        if !p.is_file() {
            continue;
        }
        let rel = p.strip_prefix(dir).unwrap_or(p).display().to_string();
        if let Ok(body) = std::fs::read_to_string(p) {
            files.insert(rel, body);
        }
    }
    crate::recipe::recipe_from_tree(&files)
}