# CI

## Normal package workflow

Create/update the APKBUILD, run a targeted local build, then commit and push when
CI deployment is authorized. On `cdg-1`, the Gitolite post-receive hook starts
`/usr/local/bin/minci.sh -f foundationpkgs` for pushes to `main`. Minci runs jobs
selected by the effective Jobfile. Committing locally does not trigger CI.

The Jobfile runs `checks`, `plan`, `packages`, `transfer`, and `deploy` in order.
Minci stops at the first failed job. `checks` runs shell syntax
checks and offline backend/publication/staged-install regressions. Linux builds
default to APK and an Alpine-musl target; `FPKGS_FORMAT=tar.gz` explicitly retains
legacy output. `FPKGS_TARGETS` selects targets independently. Before deploying
this backend to CI, provision native abuild/apk-tools, an unprivileged build user,
signing configuration and target dependencies. Package jobs do not provision the
live host or rewrite existing recipes; keep legacy CI explicitly on tar.gz until
its packages and toolchain have been migrated.

**Per-format allowlists:** `.config/Jobfile` always selects `initify` as a required
Debian CI tool artifact, plus `minimal-fxa-server`, `sqlite-vector`,
`sqlite-memory`, and `saait` by default. `FPKGS_DEB_PACKAGES`
changes the application selection without dropping `initify`. Its recipe checks
Perl syntax and converts a synthetic service/timer during each uncached build.
The APK allowlist
`ci_apk_packages`/`FPKGS_APK_PACKAGES` is initially empty. An empty list skips
that format; it does not select every recipe. Direct helper invocations still
use `FPKGS_PACKAGES`, with unset meaning all discovered recipes.
Go work uses disk-backed `$workdir/tmp`, not the small `/tmp` tmpfs.
Debian CI builds are rootless. The separate `fpkgs-publisher` identity on `cdg-1`
retains verified CI artifacts before signing/activating the APT repository.
The Mac no longer needs to be online for publication. `scripts/apt-delivery.sh`
provides the transfer/deploy handoff; see the binaries repository's `docs/apt.md`
for publisher custody, native-tool checks, and failure handling.

Package builds are sequential;
your package may be queued behind others. One package can be published even if
other packages fail and the overall job fails. Verify the requested package,
target, and revision rather than inferring availability from overall job state.

## Init-system conversion tool

`noarch/initify/APKBUILD` pins [goose121/initify](https://github.com/goose121/initify)
and packages `initify`, `cronify`, and the checked `initify-package` staging helper.
It supports APK, opt-in Debian, and legacy
archive output. The required CI build makes the tool available as an artifact. Before package
builds, `scripts/prepare-ci-tools.sh` also builds the converter from the same
revision and stages its executables on the native build PATH, allowing service
recipes to call `initify-package`. Neither step installs into the running CI
host. Perl is in the host preparation manifest. Installing the resulting tool follows the normal reviewed
APT workflow after publication through `foundationpkgs-binaries`.

Use `initify example.service` in a disposable directory: it writes an OpenRC
script beside the input, dropping `.service`. Use `cronify example.timer` to
print a cron schedule. These are build-time helpers, not a service manager.

Upstream only converts simple services. It does not implement `.path` watchers,
`User`/`Group`, `EnvironmentFile`, `WorkingDirectory`, `ExecStartPre`, systemd
sandboxing, or equivalent oneshot semantics. Timer conversion is also limited;
the recipe exercises only a daily calendar fixture. Never assume the stagit
queue service can be deployed safely by passing it through this converter.
Review generated output and supply platform-specific behavior separately.
Service recipes opt into checked build-time conversion with `initify-package`;
see [service packaging](usage.md#service-packaging). Arbitrary upstream units are
not automatically converted, and packages never enable/start a generated service.

## Prepare the Debian CI host

The maintained host package list is [`.config/ci-packages.list`](../.config/ci-packages.list).
It covers the **Debian 13 amd64 build host**, not the Alpine target filesystem.
Ordinary packages come from the machine's configured signed Debian repositories;
custom packages come from a supplied `foundationpkgs-binaries` checkout or snapshot.
Each custom `.deb` is pinned by its versioned relative path and SHA-256 in this
manifest. Its source repository revision is recorded in the manifest comments.
Debian packages track the configured repositories rather than a frozen snapshot.

```sh
# Portable, read-only validation: show the list and verify custom package bytes.
scripts/prepare-ci-host.sh --plan ../foundationpkgs-binaries

# On Debian 13 amd64: ask APT to resolve the combined transaction, without changes.
scripts/prepare-ci-host.sh --simulate ../foundationpkgs-binaries

# Explicit administrator action, after reviewing the simulation:
sudo scripts/prepare-ci-host.sh --install /absolute/path/to/foundationpkgs-binaries
```

The default action is `--plan`. Use a trusted foundationpkgs checkout: its script
and manifest authorize privileged installation. No remote is fetched implicitly;
provide the approved bootstrap snapshot (the initial artifacts are from
`d82b595d7822e05b2819425862084fd0153284b9`). The bootstrap repository's own
checksum file is not substituted for the pins maintained here.

Both custom packages and all manifest entries are validated before invoking APT.
Verified `.deb` files are copied to temporary staging, so APT can read them even
when the source checkout is private. Their runtime dependencies are resolved
from the `.deb` metadata rather than repeated in this list. A single APT install
transaction handles Debian and custom packages together, with **no removals**,
no recommended extras, and normal interactive confirmation for `--install`.
APT can still upgrade installed packages/dependencies; review the entire plan.
Repeated installation uses APT's existing package state. There is no extraction
over `/`, automatic `apt-get update`, or `autoremove`. Update APT indexes
separately when required before simulating/installing.

This command is not called by the Jobfile or ordinary package builds. It does
not create users, signing keys, credentials, target APK databases or cross
compilers, migrate recipes, or enable the APK CI backend. Configure those
separately before cutting over live CI. Keep private signing keys outside Git.

To change a custom version, update its path and SHA-256 together in the manifest,
then rerun validation and simulation. The offline check is
`sh tests/prepare-ci-host.sh`; it needs neither root nor bootstrap artifacts.

## Jobfile selection

The deployed runner selects the first applicable source:

1. The explicitly configured `jobfile`.
2. An external per-repository Jobfile (default
   `/etc/minci.d/foundationpkgs/Jobfile`).
3. `origin/<integbranch>:.config/Jobfile`; `integbranch` defaults to `integ`.
4. `.config/Jobfile` in the checked-out build branch.

**Verified 2026-10-29:** foundationpkgs has only `main`; there is no `integ` branch
and no explicit/external override. It therefore uses `main:.config/Jobfile`,
whose trigger is `refs/heads/main: checks plan packages transfer deploy` in this revision. If an `integ` branch is added,
its Jobfile takes precedence; the branch being built remains selected by the
hook/runner and the jobs' triggers, not by the Jobfile's location.

To inspect the configured jobs, read the effective Jobfile, not minci's
implementation. Check remote branches with `git ls-remote --heads origin`.
The deployed runner configuration is `/home/git/.minci`; it contains secrets,
so inspect only named non-secret settings when diagnosing selection problems.

## Check a binary

The CI checkout includes a read-only lookup command:

```sh
rev=$(git rev-parse HEAD)  # the revision you actually pushed
ssh cdg-1 "/home/git/.local/cache/minci/foundationpkgs/scripts/fpkgs-ci.sh status minimal-fxa-server x86_64-unknown-linux-gnu $rev"
```

The command searches published manifests and verifies SHA-256 for all files in
new publications' `SHA256SUMS`, including split packages and signed indexes.
Legacy publications without that registry retain main-archive sidecar checking.
It returns format, manifest, archive, and log URLs plus the server archive path.
It neither starts a build nor modifies artifacts.

| Exit | Meaning | Next action |
| --- | --- | --- |
| 0 | Exact revision/target/package found; publication checksums verified | Use the returned artifact |
| 1 | No matching publication yet | Check CI jobs/logs; this alone does not distinguish queued, running, failed, or never triggered |
| 2 | Matching manifest exists but artifact/checksum is missing or invalid | Investigate publication; do not deploy it |

Invocation/configuration errors are also nonzero and print a diagnostic.
Use a full commit SHA for remote queries. A local branch name or short SHA is
resolved against `FPKGS_ROOT` (default current directory). If several builds of
the same revision exist, the command returns the first complete verified match;
it is not a "latest version" selector. With no `FPKGS_FORMAT` filter it can find
both APK and old tarball publications. Set `FPKGS_FORMAT=apk` or `tar.gz` to
restrict lookup. Older GNU/tarball releases keep their original targets/URLs.

**Do not compute the build key on your laptop to locate a CI artifact.** Keys
include builder paths, environment, and tool versions. Read published manifests
using `status`; the existing `key` command is for build-key diagnostics.

### Status and logs

- Dashboard and recorded job results:
  <https://ci.nply.org/cgi-bin/minci.cgi>.
- Published package build log: the `log_url` returned by `status`.
- Current runner output on `cdg-1`: `/tmp/minci.log`. This is shared/overwritten
  by jobs; use the dashboard for recorded results.
- Gitolite trigger diagnostics: `/home/git/minci-post-receive.log`.
- Unpublished package build logs:
  `/home/git/.local/cache/minci/work/foundationpkgs/fpkgs/build/<buildkey>/build.log`.
  The runner output identifies the key when it starts a package or reports a
  failure. Read that exact log rather than repeatedly scanning processes/files.

### Publication locations

Public base: <https://nply.org/dl/foundationpkgs/>.
Server root: `/srv/http/dl.nply.org/foundationpkgs`.
`dl.nply.org` is not the public endpoint until DNS/TLS are intentionally changed.

```text
<root>/<target>/<pkgname>/<pkgver>-r<pkgrel>/<buildkey>/
  manifest
  build.log
  SHA256SUMS
  <bucket>/<apk-arch>/<pkgname>-<pkgver>-r<pkgrel>.apk
  <bucket>/<apk-arch>/APKINDEX.tar.gz
  ...split APKs and matching .sha256 sidecars...
  # tar.gz format instead retains flat *.tar.gz and *.tar.gz.sha256 files.
```

The manifest identifies `gitrev`, `target`, `format`, the primary relative
`artifact` path, package/version, build key, public URL, and timestamp. The build
key includes format, backend scripts, compiler/tool versions, upstream abuild
script/configuration fingerprints, public signing keys and build environment.
Corrupt or incomplete cached publications are rebuilt rather than skipped. The `.sha256` file contains a **bare hexadecimal digest**,
not a filename-bearing `sha256sum -c` record. Publication is atomic: artifacts,
log, and manifest are staged together before the directory becomes visible.

## Install or upgrade a Debian application

For packages selected for `.deb` output, use the signed APT repository maintained
in `~/Projects/foundationpkgs-binaries`; its `docs/apt.md` documents the public
key fingerprint, scoped `Signed-By` setup, local retention and publication.
After initial enrollment, `apt update` / `apt install minimal-fxa-server` / normal
APT upgrades own and update the live files. No staging-copy deployment is needed.
Unattended third-party-origin upgrades are a separate explicit administrator policy.

Use `FPKGS_FORMAT=deb scripts/fpkgs-ci.sh status PACKAGE x86_64-unknown-linux-gnu REV`
to find exact CI output. The Debian backend uses `dpkg-deb` without sudo; it does
not change host package state or access the APT archive signing key. The later
`transfer` and `deploy` jobs invoke a fixed, root-owned receiver under the separate
publisher identity using narrowly scoped sudo, not sudo inside package builds.
The receiver independently verifies the copied artifacts for the exact commit.
Publication retains provenance and signed snapshots before HTTPS activation;
`deploy` success, not just `packages` success, means APT delivery completed.

## Install an APK

Use the verified `artifact_path` with the target system's normal APK manager,
with its trusted signing key and dependency repositories configured:

```sh
apk add /path/to/verified-package.apk
# An older explicit package version/file can be installed to downgrade.
```

This is for the intended APK target, not the Debian CI host. Do not extract APK
files over `/` or use the APK manager to overwrite Debian's dpkg-managed base.
SHA-256 transport checks complement, rather than replace, APK signature trust.
The public CI signing key is [`keys/foundationpkgs-ci.rsa.pub`](../keys/foundationpkgs-ci.rsa.pub),
also published at <https://nply.org/dl/foundationpkgs/keys/foundationpkgs-ci.rsa.pub>.
Trust it from an independently trusted foundationpkgs checkout before installing
on the intended APK target:

```sh
install -m644 keys/foundationpkgs-ci.rsa.pub /etc/apk/keys/
apk verify /path/to/verified-package.apk
apk add /path/to/verified-package.apk
```

The private key belongs to the `git` CI user, mode 0600, outside the repository.
The initial x86_64 Alpine target has an empty, isolated APK database for static
Go dependency tracing; no Alpine base filesystem or chroot is used to build.
Dynamic recipes require their actual target dependency state. Native Go 1.25.6
is already supplied on this host by its existing `go-bin` package; the FXA
upstream module requires at least Go 1.25.5. That recipe-level toolchain is not
replaced by the base host package installer.

Downgrade does not roll back application databases or migrations.

## Install a legacy tar.gz CI binary

On `cdg-1`, use the verified `artifact_path` from `status`. Extract into staging,
then install only the files required by the deployment. This example is for the
minimal-fxa-server package; substitute the selected files for other packages.

```sh
# Run on cdg-1 as root, after status succeeds for the intended revision.
set -eu
archive=/srv/http/dl.nply.org/foundationpkgs/TARGET/PACKAGE/VERSION/BUILDKEY/PACKAGE-VERSION.tar.gz
expected=$(awk 'NR == 1 {print $1}' "$archive.sha256")
actual=$(sha256sum "$archive" | awk '{print $1}')
[ "$actual" = "$expected" ]

stage=$(mktemp -d)
trap 'rm -rf "$stage"' EXIT HUP INT TERM
before=$(stat -c '%a %u:%g %n' / /usr /usr/bin /usr/share)
tar -xzf "$archive" -C "$stage"
install -o root -g root -m 755 "$stage/usr/bin/minimal-fxa-server" /usr/bin/minimal-fxa-server
install -o root -g root -m 755 "$stage/usr/bin/fxa-user" /usr/bin/fxa-user
install -d -o root -g root -m 755 /usr/share/licenses/minimal-fxa-server
install -o root -g root -m 644 "$stage/usr/share/licenses/minimal-fxa-server/LICENSE" /usr/share/licenses/minimal-fxa-server/LICENSE
after=$(stat -c '%a %u:%g %n' / /usr /usr/bin /usr/share)
[ "$before" = "$after" ]
```

`sh tests/staged-install.sh` tests this pattern against a disposable target tree
with deliberately different parent modes; it never writes to system directories.

Never extract these CI tarballs directly over `/`: archives contain builder
ownership and parent-directory modes, including `./` and `./usr/`. Restart the
service and run its health/integration checks after installing. Back up runtime
configuration/data before a deployment that changes them.

## Developing CI/package tooling

`minci.sh` owns CI execution/reporting; `scripts/fpkgs-ci.sh` owns package
planning, building, publishing, and artifact lookup. Keep these responsibilities
separate. The CI graph is in [ci-architecture.dot](ci-architecture.dot).

Useful local commands:

```sh
scripts/fpkgs-ci.sh plan FULL_COMMIT_SHA
scripts/fpkgs-ci.sh run FULL_COMMIT_SHA
scripts/fpkgs-ci.sh key Unix/minimal-fxa-server/APKBUILD x86_64-unknown-linux-gnu FULL_COMMIT_SHA
sh tests/artifact-status.sh
sh tests/staged-install.sh
sh tests/apk-backend.sh
# With real upstream tools and signing configuration, as a non-root user:
FPKGS_TEST_REAL_APK=1 sh tests/apk-backend.sh
```

`run` builds/publishes locally; it is not the normal way to trigger deployed CI.
For test/mirror stores, configure `FPKGS_DL_ROOT` and `FPKGS_DL_BASE_URL`.
See [usage](usage.md#cipackage-planner) for the remaining environment variables.
