ci: replace GitFlow with a single main branch, tag releases and Komodo deployment
CI / publish (pull_request) Skipped
CI / policy (pull_request) Successful in 12s
CI / build (pull_request) Successful in 32s
CI / validate (pull_request) Successful in 40s
CI / benchmark (pull_request) Successful in 1m17s
CI / test (pull_request) Successful in 3m15s
CI / required (pull_request) Successful in 3s

PRs into main run the commit check (only the PR's own commits, no merge
commits), lint, format, type checks, tests, the benchmark and the build,
gated by `required`. Editing a PR no longer reruns CI. A push to main
builds one image, publishes it as sha-<commit> and beta, and redeploys the
Komodo beta stack; a vX.Y.Z tag promotes that image to vX.Y.Z and latest
and redeploys production. The deploy goes through the Komodo API and waits
for the update, so a failed deployment fails the run.

Removes the security scans, PR and branch-* images, the release/hotfix
rules and the merge-message template. compose.prod.yml now pulls the
registry image.

Closes #391

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit was merged in pull request #392.
This commit is contained in:
nessarandClaude Opus 5.5 committed 2026-11-30 23:45:51 +01:00
1 parent eddf6532af
commit 40ee34ebd1
12 files changed
+357 -494

No files matched your search

@@ -1,5 +0,0 @@
${PullRequestTitle}
${ClosingIssues}
See pull request ${PullRequestReference}
+28 -72
View File
@@ -2,10 +2,10 @@ name: CI
on:
push:
branches: [develop, main]
branches: [main]
tags: ['v*']
pull_request:
types: [opened, reopened, synchronize, edited]
types: [opened, reopened, synchronize]
workflow_dispatch:
permissions:
@@ -16,21 +16,21 @@ permissions:
# commands never use it: the jobs that run them install the pinned Bun with
# scripts/install-bun.sh and run `run:` steps under a shell whose PATH has Bun but no Node.
# PR and manual runs only validate, so a newer run replaces an older one. Publications
# (pushes to main, and every release tag in one shared group) wait and are never cancelled.
concurrency:
group: ci-${{ github.event_name }}-${{ github.ref }}
cancel-in-progress: ${{ !startsWith(github.ref, 'refs/tags/') }}
group: ci-${{ github.event_name }}-${{ startsWith(github.ref, 'refs/tags/') && 'release' || github.ref }}
cancel-in-progress: ${{ github.event_name != 'push' }}
jobs:
policy:
name: policy
if: ${{ github.event_name != 'push' }}
runs-on: ubuntu-latest
container: node:24.22.0
defaults:
run:
shell: env PATH=/opt/bun/bin:/usr/bin:/bin bash -e {0}
outputs:
slug: ${{ steps.policy.outputs.slug }}
tag: ${{ steps.policy.outputs.tag }}
steps:
- uses: https://gitea.com/actions/checkout@v7
with:
@@ -40,12 +40,12 @@ jobs:
run: sh scripts/install-bun.sh
- name: Policy regression tests
run: bun scripts/ci-policy.test.mjs && bun scripts/ci-image.test.mjs
- name: Validate event and commit
id: policy
- name: Validate the pull request's commits
run: bun scripts/ci-policy.mjs
validate:
name: validate
if: ${{ github.event_name != 'push' }}
runs-on: ubuntu-latest
container: node:24.22.0
defaults:
@@ -64,6 +64,7 @@ jobs:
test:
name: test
if: ${{ github.event_name != 'push' }}
runs-on: ubuntu-latest
container: node:24.22.0
defaults:
@@ -93,6 +94,7 @@ jobs:
benchmark:
name: benchmark
if: ${{ github.event_name != 'push' }}
runs-on: ubuntu-latest
container:
image: node:24.22.0
@@ -113,6 +115,7 @@ jobs:
build:
name: build
if: ${{ github.event_name != 'push' }}
runs-on: ubuntu-latest
container: node:24.22.0
defaults:
@@ -133,57 +136,13 @@ jobs:
retention-days: 7
if-no-files-found: error
security:
name: security
runs-on: ubuntu-latest
container: node:24.22.0
steps:
- uses: https://gitea.com/actions/checkout@v7
with:
persist-credentials: false
- name: Install scanners
run: |
apt-get update
apt-get install --yes --no-install-recommends python3-venv
python3 -m venv /tmp/semgrep
/tmp/semgrep/bin/pip install semgrep==1.180.0
case "$(uname -m)" in
x86_64) trivy_arch=64bit ;;
aarch64) trivy_arch=ARM64 ;;
*) echo 'Unsupported Trivy architecture' >&2; exit 1 ;;
esac
archive="trivy_0.75.0_Linux-${trivy_arch}.tar.gz"
curl --fail --location --silent --show-error "https://github.com/aquasecurity/trivy/releases/download/v0.75.0/${archive}" --output "/tmp/${archive}"
curl --fail --location --silent --show-error https://github.com/aquasecurity/trivy/releases/download/v0.75.0/trivy_0.75.0_checksums.txt --output /tmp/trivy-checksums.txt
(cd /tmp && sha256sum --check --ignore-missing trivy-checksums.txt)
tar -xzf "/tmp/${archive}" -C /usr/local/bin trivy
- name: JavaScript and TypeScript SAST
run: /tmp/semgrep/bin/semgrep scan --config p/javascript --config p/typescript --metrics off --sarif --output semgrep-results.sarif src scripts
- name: Dependency and secret scan
if: ${{ !cancelled() }}
run: trivy fs --db-repository public.ecr.aws/aquasecurity/trivy-db:2 --format sarif --output trivy-results.sarif --skip-dirs node_modules,dist,coverage .
- name: Security reports
if: ${{ always() }}
uses: https://gitea.com/actions/upload-artifact@v7
with:
name: security
path: '*-results.sarif'
retention-days: 7
if-no-files-found: error
images:
name: images
needs: [policy, validate, test, benchmark, build, security]
if: >-
success() &&
(github.event_name == 'push' ||
(github.event_name == 'pull_request' &&
github.event.pull_request.head.repo.full_name == github.repository))
publish:
name: publish
# The pushed commit is the one its PR validated: direct pushes are forbidden and
# outdated PRs are blocked, so pushes to main and tags only publish and deploy.
if: ${{ github.event_name == 'push' }}
runs-on: ubuntu-latest
container: docker:29.9.1
concurrency:
group: image-${{ needs.policy.outputs.tag != '' && 'stable' || needs.policy.outputs.slug }}
cancel-in-progress: false
services:
docker:
image: docker:29.9.1-dind
@@ -212,28 +171,25 @@ jobs:
persist-credentials: false
- name: Install Bun
run: sh scripts/install-bun.sh
- name: Build branch images or promote a release
- name: Publish beta or promote a release, then redeploy it on Komodo
env:
REGISTRY_USERNAME: ${{ secrets.REGISTRY_USERNAME }}
REGISTRY_PASSWORD: ${{ secrets.REGISTRY_PASSWORD }}
KOMODO_URL: ${{ secrets.KOMODO_URL }}
KOMODO_API_KEY: ${{ secrets.KOMODO_API_KEY }}
KOMODO_API_SECRET: ${{ secrets.KOMODO_API_SECRET }}
KOMODO_BETA_STACK: vac-optimizer_beta
KOMODO_PRODUCTION_STACK: vac-optimizer
run: /opt/bun/bin/bun scripts/ci-image.mjs
required:
name: required
if: ${{ always() }}
needs: [policy, validate, test, benchmark, build, security, images]
if: ${{ always() && github.event_name != 'push' }}
needs: [policy, validate, test, benchmark, build]
runs-on: ubuntu-latest
container: node:24.22.0
env:
CHECK_RESULTS: ${{ needs.policy.result }} ${{ needs.validate.result }} ${{ needs.test.result }} ${{ needs.benchmark.result }} ${{ needs.build.result }} ${{ needs.security.result }}
IMAGE_RESULT: ${{ needs.images.result }}
IMAGE_EXPECTED: ${{ github.event_name == 'push' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository) }}
CHECK_RESULTS: ${{ needs.policy.result }} ${{ needs.validate.result }} ${{ needs.test.result }} ${{ needs.benchmark.result }} ${{ needs.build.result }}
steps:
- name: Require successful validation and expected publication
run: |
test "$CHECK_RESULTS" = 'success success success success success success' || exit 1
if [ "$IMAGE_EXPECTED" = 'true' ]; then
test "$IMAGE_RESULT" = 'success'
else
test "$IMAGE_RESULT" = 'skipped'
fi
- name: Require successful validation
run: test "$CHECK_RESULTS" = 'success success success success success'
+7 -10
View File
@@ -12,15 +12,12 @@ Use the default canonical labels: `needs-triage`, `needs-info`, `ready-for-agent
This is a single-context repo using root `CONTEXT.md` and `docs/adr/`. See `docs/agents/domain.md`.
## GitFlow
## Branches and releases
- `develop` is the default integration branch; `main` contains releases. Start `feature/*` branches from the current `origin/develop` and target their PRs to `develop`.
- Rebase working branches onto the latest `origin/develop` before opening or merging a PR. If `develop` advances, rebase and rerun the PR checks before merging.
- Integrate through PRs with successful required checks and merges restricted to designated maintainers through Gitea's merge allowlist. The `develop` allowlist also admits the `renovate` bot, which automerges minor, patch, digest, and pin updates once `required` passes; major updates and the grouped Bun updates (see [Gitea Actions](docs/gitea-actions.md#bun-toolchain-and-node)) stay manual. Merge with Gitea's rebase method so `develop` stays linear; merge commits and squashing are disabled in the repository. Direct and forced pushes to `main` and `develop` are forbidden.
- Use Conventional Commits for new commits and PR titles.
- Create `release/X.Y.Z` from `develop` and `hotfix/X.Y.Z` from `main`. Only `release/*` and `hotfix/*` PRs target `main`. Merge each release or hotfix into both `main` and `develop`, keeping its branch until both PRs are merged.
- Use merges and back-merges for releases and hotfixes. Never rebase `main`, `develop`, or a frozen release branch.
- `main` is the only long-lived branch and the default. Start each branch from the current `origin/main` and target its PR to `main`.
- Integrate through PRs whose `required` check passed, merged with Gitea's rebase method so `main` stays linear. Merge commits and squash are disabled, a PR may not contain merge commits, and direct and forced pushes to `main` are forbidden. Outdated PRs are blocked: when `main` advances, rebase onto it and let the checks rerun.
- The merge allowlist is the owner and the `renovate` bot, which automerges minor, patch, digest, and pin updates once `required` passes; major updates and the grouped Bun updates (see [Gitea Actions](docs/gitea-actions.md#bun-toolchain-and-node)) stay manual.
- Use Conventional Commits for every commit; CI checks each commit from the PR base to its head.
- Each merge into `main` publishes the `beta` image and redeploys beta on Komodo. A release is a PR that bumps `package.json`, then an annotated `vX.Y.Z` tag on that `main` commit, which promotes beta's image to `vX.Y.Z` and `latest` and redeploys production. A hotfix is an ordinary PR followed by a patch tag.
The CI workflow is `.gitea/workflows/ci.yml`. Activation is tracked in Gitea issue #268; Actions is enabled with owner approval, and the migration gate stays required until live workflow validation and merge-message review. Before changing CI, image publication, or activation settings, read [Gitea Actions](docs/gitea-actions.md).
Before preparing a release or hotfix, creating a tag, or changing image publication, read [GitFlow and releases](README.md#gitflow-and-releases) for package versions, explicit stable tags, and image promotion.
The CI workflow is `.gitea/workflows/ci.yml`. Before changing CI, image publication, or Komodo deployment, read [Gitea Actions](docs/gitea-actions.md). Before releasing or creating a tag, read [Branches and releases](README.md#branches-and-releases).
+21 -26
View File
@@ -271,36 +271,27 @@ Behind a reverse proxy, forward WebSocket upgrades for `/api/planning`; on Nginx
## Continuous integration
[`.gitea/workflows/ci.yml`](.gitea/workflows/ci.yml) defines Gitea Actions validation, functional coverage, production builds, security scans, and Docker image publication. [Issue #268](https://gitea.nessar.fr/nessar/vac-optimizer/issues/268) tracks activation. Actions is enabled with owner approval; publisher credentials and live workflow validation are still pending. The [activation guide](docs/gitea-actions.md) records runner, credential, permission, and merge-gate requirements.
[`.gitea/workflows/ci.yml`](.gitea/workflows/ci.yml) validates pull requests, publishes images, and asks Komodo to redeploy. [Gitea Actions](docs/gitea-actions.md) describes its jobs, runner, secrets, Komodo call, and repository settings.
The workflow runs on pushes to `develop` and `main`, `v*` tag pushes, PR opening/reopening/synchronization/edits, and manual dispatch. Other branches run CI only through their PR, so a branch without a PR gets no automatic CI or image. Manual runs validate without publishing images. Required jobs cover policy regression tests, GitFlow and Conventional Commits, ESLint, Prettier, `bun check` type checks, Bun coverage, the production build, Semgrep SAST, and Trivy dependency/secret scans. Coverage, build output, and SARIF reports are retained for seven days.
- **Pull requests** (opened, reopened, synchronized) and manual runs check the PR's commits, then run ESLint, Prettier, `bun check` type checks, Bun functional coverage, the benchmark, and the production build. The `required` job aggregates them, and its `CI / required (pull_request)` status gates merging. Editing a PR's title or description runs nothing. Coverage and build output are kept for seven days.
- **A push to `main`** revalidates nothing: it builds one image, publishes it as `sha-<commit>` and `beta`, and redeploys beta.
- **A `vX.Y.Z` tag** gives the image beta ran for that commit the names `vX.Y.Z` and `latest` without rebuilding it, then redeploys production.
Jobs that run project commands install Bun 1.4.5 with `scripts/install-bun.sh` (a checksum-verified download, no npm) and run their steps with a `PATH` that holds Bun but no Node. The job containers keep Node only for Gitea's checkout and artifact actions, which are JavaScript actions the runner executes itself; see the [activation guide](docs/gitea-actions.md#runners-and-permissions).
Jobs that run project commands install Bun 1.4.5 with `scripts/install-bun.sh` (a checksum-verified download, no npm) and run their steps with a `PATH` that holds Bun but no Node. The job containers keep Node only for Gitea's checkout and artifact actions, which are JavaScript actions the runner executes itself; see [Gitea Actions](docs/gitea-actions.md#bun-toolchain-and-node).
Functional tests run with `bun test --isolate`; coverage is line-level only (Bun reports no branch or function data). The separate required benchmark job runs without coverage in a container limited to 3 GiB (JavaScriptCore has no heap-size flag, so this replaces the former 2 GiB Node heap cap) and keeps its 240-second hang guard, one warm-up and two measured repetitions of all eight scenarios. [#78](https://gitea.nessar.fr/nessar/vac-optimizer/issues/78) restored this gate after a complete local pass in 298.6 seconds; see [the measurements and hardware limits](docs/benchmark/issue-78.md). After [#302](docs/benchmark/issue-302.md) the local protocol takes about 41 seconds. Benchmark success is required for image publication and the aggregate `required` job. The lowered hang guard and tightened multipliers still need confirmation on the CI runners.
Functional tests run with `bun test --isolate`; coverage is line-level only (Bun reports no branch or function data). The separate required benchmark job runs without coverage in a container limited to 3 GiB (JavaScriptCore has no heap-size flag, so this replaces the former 2 GiB Node heap cap) and keeps its 240-second hang guard, one warm-up and two measured repetitions of all eight scenarios. [#78](https://gitea.nessar.fr/nessar/vac-optimizer/issues/78) restored this gate after a complete local pass in 298.6 seconds; see [the measurements and hardware limits](docs/benchmark/issue-78.md). After [#302](docs/benchmark/issue-302.md) the local protocol takes about 41 seconds. Benchmark success is required by the `required` job. The lowered hang guard and tightened multipliers still need confirmation on the CI runners.
The `required` job aggregates successful validation and expected image publication, accepting the image job's intentional skip for fork PRs and manual runs. Image jobs require successful validation and are limited to pushes to `develop`, `main` and release tags, and same-repository PRs. Registry credentials are confined to the publishing step.
### Branches and releases
Both protected branches still require `gitlab-to-gitea/ci-conversion-required` until the owner approves the first merge message and a successful Gitea PR run, then replaces the migration gate with the actual pull-request context for `required`. Local validation does not satisfy this status. Historical CI reports and artifacts remain in administrator rollback backups; the original configuration is retained in Git history.
`main` is the only long-lived branch. Start each branch from the current `origin/main`, open a PR into `main`, and merge it with Gitea's rebase method once `required` passes, which keeps `main` linear. Branch protection blocks outdated PRs: when `main` advances, rebase the branch onto it, which reruns the checks. A PR may not contain merge commits.
### GitFlow and releases
Use Conventional Commits for every commit, for example `feat(calendar): add planning periods`, `fix(planner): handle expired balances`, or `chore(release): 1.6.0`. Scopes are optional; `!` marks a breaking change. A rebase merge keeps each commit's own subject, so CI checks every commit from the PR's base to its head, not the PR title.
`develop` is the default integration branch. Create `feature/*` branches from it, rebase them onto the current `origin/develop` before opening or merging their PR, and merge into `develop` with Gitea's rebase method, which keeps its history linear. Existing working-branch names such as `feat/*` follow the same rules. Working branches cannot merge `develop` into themselves instead of rebasing.
To release:
Create `release/X.Y.Z` from `develop` when the release scope is ready. Set `package.json` to `X.Y.Z` on this branch, stabilize it, then merge it into `main` and back into `develop`. Keep the release branch until both PRs have merged. A `hotfix/X.Y.Z` starts from `main`, changes the package version, and follows the same two-target merge process. Do not rebase `main`, `develop`, or a frozen release onto ongoing development.
Use Conventional Commits for new commits and PR titles, for example `feat(calendar): add planning periods`, `fix(planner): handle expired balances`, or `chore(release): prepare 1.6.0`. Scopes are optional; `!` marks a breaking change. A rebase merge keeps each commit's own subject, so every commit of a PR follows this convention; where a merge commit is made, its subject must preserve the validated PR title. Gitea supports a [Git-based merge-message template](https://docs.gitea.com/usage/issues-prs/merge-message-templates/) at `.gitea/default_merge_message/MERGE_TEMPLATE.md`, using `${PullRequestTitle}` and `${PullRequestReference}`. The committed template and a checked example expansion are documented in the [activation guide](docs/gitea-actions.md); legacy history is not rewritten.
The image publisher implements this tag contract in `gitea.nessar.fr/nessar/vac-optimizer`:
| Trigger | Published image tags |
| --- | --- |
| Successful push to `develop` or `main`, or same-repository PR | `branch-<normalized branch slug>` and `sha-<full commit SHA>` |
| Explicit release tag `vX.Y.Z` | `vX.Y.Z` and `latest`, using the existing SHA image |
For example, `feature/calendar` uses `branch-feature-calendar`; integration uses `branch-develop`. Preserve the previous slug normalization: lowercase the branch name, replace characters other than `a-z` and `0-9` with `-`, truncate to 63 bytes, and remove leading/trailing `-`. Choose branch names with distinct slugs. Only valid release tags can update `latest`. Automatic image publication and tag promotion begin after the owner provisions publisher credentials and validates publication permissions.
After owner activation, the PR into `main` has merged, and its full checks and SHA image publication have succeeded, tag the published main commit:
1. Merge a PR that sets the `package.json` version to `X.Y.Z`.
2. Wait for that push's `publish` job, which publishes `sha-<commit>` and redeploys beta, and check beta.
3. Tag that commit and push the tag:
```bash
git fetch origin
@@ -308,13 +299,17 @@ git tag -a v1.6.0 origin/main -m "Release 1.6.0"
git push origin v1.6.0
```
The tag must match the tagged commit's `package.json` version, use stable `vMAJOR.MINOR.PATCH` syntax, and point to a commit reachable from `main`. Wait for the main checks and image publication before tagging: promotion requires its `sha-<commit>` image. Tags do not increment the version automatically.
If `main` has moved since, tag the release commit's SHA instead of `origin/main`. The tag must use stable `vMAJOR.MINOR.PATCH` syntax, match the tagged commit's `package.json` version, and be reachable from `main`; otherwise the run fails before any image tag changes. A tag whose `sha-<commit>` image is missing fails without changing `vX.Y.Z` or `latest` and without deploying. A hotfix is an ordinary PR into `main` that bumps the patch version, followed by its tag.
The Gitea repository policy requires `develop` as the default branch and **Rebase** as the merge method (fast-forward-only may stay enabled), with merge-commit and squash methods disabled. Configure [branch protection](https://docs.gitea.com/usage/access-control/protected-branches/) for `main` and `develop` to disable direct and forced pushes, restrict the merge allowlist to designated maintainers, require successful status checks, and block outdated PRs. Administrators must follow the protection rules. The `develop` allowlist also admits the `renovate` bot: [renovate.json](renovate.json) automerges minor, patch, digest, and pin updates by rebase three days after their release once the `required` check passes, and leaves major updates and the grouped Bun updates for manual review. After merge-message approval and a successful reviewed PR run, replace the migration gate with the reported pull-request context for the `required` job, as described in the activation guide. These are required settings; the migration does not establish that every setting has already been applied.
| Event | Image tags in `gitea.nessar.fr/nessar/vac-optimizer` | Komodo |
| --- | --- | --- |
| Push to `main` | `sha-<full commit SHA>` and `beta`, built once | Redeploys beta |
| Tag `vX.Y.Z` | `vX.Y.Z`, then `latest`, from the existing `sha-<commit>` image | Redeploys production |
| Pull request or manual run | None | None |
Only `release/*` and `hotfix/*` PRs may target `main`; working PRs target `develop`. CI validates these rules and checks working-branch rebases against the fetched integration head. If `develop` advances after validation, rebase and rerun the PR checks before merging.
[renovate.json](renovate.json) automerges minor, patch, digest, and pin updates by rebase three days after their release once `required` passes, and leaves major updates and the grouped Bun updates for manual review.
Run `bun scripts/ci-policy.test.mjs` and `bun scripts/ci-image.test.mjs` locally to verify GitFlow event handling and image publication without writing to a registry. The adapter reads Gitea webhook data through the runner's `GITHUB_*` compatibility variables. Local checks do not satisfy the migration gate.
Run `bun scripts/ci-policy.test.mjs` and `bun scripts/ci-image.test.mjs` to check the commit and tag policy, image publication, and the Komodo calls against a temporary Git repository, a fake `docker`, and a fake Komodo, without writing to a registry.
## Domain and design references
+2 -4
View File
@@ -1,9 +1,7 @@
services:
vac-optimizer:
build:
context: .
dockerfile: Dockerfile
image: vac-optimizer:latest
# The image CI promotes on each release tag; pin a vX.Y.Z tag to hold a version.
image: gitea.nessar.fr/nessar/vac-optimizer:latest
container_name: vac-optimizer-prod
restart: always
ports:
+1 -1
View File
@@ -16,7 +16,7 @@ Run inside the clone so the CLI discovers the repository and login from `origin`
- **Comment**: `tea-cli comment <number> "..."`; this works for issues and PRs.
- **Apply / remove labels, edit a body, or assign**: use the Gitea UI or the REST operations below; this CLI version does not support these edits. Preserve unrelated labels and assignees.
- **Close**: post the explanation with `tea-cli comment <number> "..."`, then run `tea-cli issues close <number>`.
- **Create a pull request**: `tea-cli pulls create --base develop --title "docs: update Gitea documentation" --description "..."`. Read with `tea-cli pulls --comments <number>`; list with `tea-cli pulls --state open --output yaml`.
- **Create a pull request**: `tea-cli pulls create --base main --title "docs: update Gitea documentation" --description "..."`. Read with `tea-cli pulls --comments <number>`; list with `tea-cli pulls --state open --output yaml`.
- **List milestones**: `tea-cli milestones --state all --fields id,title --output tsv`. Issue numbers were preserved during migration, but milestone IDs changed; V1 stats is [milestone 13](https://gitea.nessar.fr/nessar/vac-optimizer/milestone/13).
## REST operations for CLI gaps
+85 -150
View File
@@ -1,81 +1,95 @@
# Gitea Actions conversion
# Gitea Actions
[Issue #268](https://gitea.nessar.fr/nessar/vac-optimizer/issues/268) converts the
repository's CI to [`.gitea/workflows/ci.yml`](../.gitea/workflows/ci.yml).
The workflow and merge-message template have passed implementation review.
Repository Actions is enabled with owner approval. Publisher credentials and
live workflow validation are still pending.
The existing `gitlab-to-gitea/ci-conversion-required` status stays in place until
that review, a successful Gitea PR run, and approval of the prepared first merge
message.
[`.gitea/workflows/ci.yml`](../.gitea/workflows/ci.yml) validates pull requests
into `main`, publishes the beta image after each merge, promotes it on a release
tag, and asks Komodo to redeploy. The branching and release steps are in the
[README](../README.md#branches-and-releases).
## Jobs and triggers
## Triggers and jobs
Pushes to `develop` and `main` and `v*` tag pushes run CI. Other branches
(feature, renovate, release, hotfix) run it only through their pull request; a
branch without a PR gets no automatic CI or image, so open a draft PR to get
one. Pull requests run on opening, reopening, synchronization, and title/body
edits. Manual dispatch runs validation without publishing images. There is no
schedule or deployment job in the preserved configuration; the Compose files
remain manual deployment options.
| Event | Jobs |
| ------------------------------------------- | -------------------------------------------------------------- |
| PR opened, reopened or synchronized; manual | `policy`, `validate`, `test`, `benchmark`, `build`, `required` |
| Push to `main` | `publish`: beta image, then Komodo beta |
| Push of a `v*` tag | `publish`: release promotion, then Komodo production |
Editing a PR's title or description runs nothing. There is no schedule.
| Job | Behavior |
| ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `policy` | Tests the policy and publisher with Bun, then validates the checked-out commit, GitFlow, PR title, commits, and stable release version. |
| `policy` | Runs the policy and publisher regression tests, then requires every PR commit from the PR base to its head to be a Conventional Commit, and none to be a merge commit. |
| `validate` | Runs ESLint, Prettier (application, `scripts/ci-*.mjs` and workflow files) and `bun check` type checks of application and test code, all on Bun with the frozen lockfile. |
| `test` | Runs functional coverage with `bun test --isolate` (line coverage only), converts it to HTML and Cobertura, and uploads coverage for seven days even on failure. |
| `benchmark` | Required eight-scenario protocol (one warm-up, two measured repetitions) outside coverage in a container limited to 3 GiB. It times the frozen engine on `two years` (best of three) before and after the protocol, and fails any scenario whose mean planning time exceeds its multiplier times that calibration; the 240-second timeout is only a hang guard. |
| `build` | Builds the client-only Angular production bundle (the only check of Angular templates; `bun check` does not replace it) and the Bun static-server bundle, and retains `dist` for seven days. |
| `security` | Runs Semgrep JavaScript/TypeScript SAST and Trivy dependency/secret scans; retains SARIF reports for seven days. Scanner execution must succeed; findings remain reports rather than a new severity gate. The scanners are not project JavaScript, so this job installs no Bun. |
| `images` | Publishes branch/SHA images after required validation, including the benchmark, or promotes an existing SHA image for a stable tag, running the publisher with Bun. Runs only for pushes and same-repository PRs. |
| `required` | Fails on failed, cancelled, or skipped required validation, including the benchmark. Requires image publication when expected; accepts its intentional skip for fork PRs and manual dispatch. It is shell only and needs no Bun. |
| `required` | Fails unless the five jobs above succeeded. Its `CI / required (pull_request)` status is the one branch protection requires. |
| `publish` | Runs `scripts/ci-image.mjs` in Docker-in-Docker. On `main` it builds one image, pushes `sha-<commit>` and `beta`, and redeploys the Komodo beta stack. On a tag it first checks the tag, pulls `sha-<commit>`, pushes it as `vX.Y.Z` and then `latest`, and redeploys the production stack. |
The benchmark gates image publication (`images.needs` includes `benchmark`) and
the `required` aggregate. The relative gate absorbs a slower runner and load
that lasts through the whole job, because calibration runs in the same job. It
calibrates before and after the protocol and judges against the slower value,
so it also absorbs load that starts during the protocol, such as another run
sharing the runner. It does not absorb load that ends before the second
calibration; the 240-second hang guard still bounds those runs.
A push to `main` revalidates nothing: direct pushes are forbidden and outdated
PRs are blocked, so the pushed commit is the one its PR validated. PRs,
including fork PRs, never run `publish` and never receive registry or Komodo
credentials.
Because branch pushes outside `develop` and `main` do not trigger CI, a commit
on a PR branch runs only on PR events, which carry the PR title and rebase
checks. New runs cancel older runs for the same event/ref. Image jobs serialize
per branch slug; stable promotions share one group and are not cancelled in
progress.
The benchmark's relative gate absorbs a slower runner and load that lasts
through the whole job, because calibration runs in the same job. It calibrates
before and after the protocol and judges against the slower value, so it also
absorbs load that starts during the protocol. It does not absorb load that ends
before the second calibration; the 240-second hang guard still bounds those runs.
## Runners and permissions
A newer run for the same PR cancels the older one. Publications in progress are
never cancelled: runs for `main` wait for the one in progress, and all release
tags share one group. If Gitea, like GitHub, replaces a queued run with a newer
one in the same group, that commit gets no `sha-<commit>` image; rerun its
`publish` job before tagging it.
Every job that runs project commands uses Bun 1.4.5 with the frozen lockfile (see [Bun toolchain and Node](#bun-toolchain-and-node)). Job containers stay on Node 24.22.0. The image
job uses Docker 29.9.1 and its matching Docker-in-Docker service. Scanner
versions are Semgrep 1.180.0 and Trivy 0.75.0; Trivy downloads are checksum-checked.
Trivy downloads its vulnerability database from Aqua's public ECR mirror because
the default registries returned a missing database blob and a download timeout.
Jobs select the `ubuntu-latest` label and require Linux container-job support.
Allow at least the benchmark job's 3 GiB container memory limit plus runner overhead.
## Release tags
The instance currently has an online inherited runner named `srvhome`, labelled
`ubuntu-latest` and `ubuntu-24.04`. Repository runners, secrets, and variables
were empty at implementation time. The owner must verify that this runner can
run the job containers, JavaScript actions, artifact uploads, and the privileged
Docker-in-Docker service before replacing the migration gate. Use isolated runners for untrusted
contributor code; the privileged publishing service belongs to trusted runs.
`publish` refuses a tag that is not stable `vMAJOR.MINOR.PATCH`, that differs
from the tagged commit's `package.json` version, or whose commit is not
reachable from `main`, before any image tag changes. A missing `sha-<commit>`
image fails the pull, so `vX.Y.Z` and `latest` stay unchanged and nothing is
deployed. Tag only a commit whose `main` publication succeeded.
## Komodo
Beta and production are two Komodo stacks on the Gitea host:
`vac-optimizer_beta` runs `gitea.nessar.fr/nessar/vac-optimizer:beta`, and
`vac-optimizer` runs `:latest` or a pinned `:vX.Y.Z`. Their names are the
`KOMODO_*_STACK` values in the workflow. Each stack must pull its image when it
deploys, since `beta` and `latest` move.
After a successful publication, `publish` calls Komodo's API (`POST /execute`
with `DeployStack`), then polls the returned update (`POST /read` with
`GetUpdate`) every three seconds for up to ten minutes. A refused call, a failed
update or a timeout fails the run. A failed publication never calls Komodo.
## Runner and secrets
Jobs select the `ubuntu-latest` label and need Linux container jobs, JavaScript
actions, artifact uploads, and a privileged Docker-in-Docker service for
`publish`. Allow at least the benchmark's 3 GiB container limit plus runner
overhead. Every job that runs project commands uses Bun 1.4.5 with the frozen
lockfile; job containers stay on Node 24.22.0 and `publish` on Docker 29.9.1.
The workflow requests a read-only repository token. Checkout removes persisted
credentials; publication credentials are passed only to the image step. Fork PRs
and manual dispatches cannot run that step. Gitea's job token cannot publish
container packages, so provision the two repository Actions secrets below.
See [job-token permissions](https://docs.gitea.com/usage/actions/token-permissions/)
and [package authorization](https://docs.gitea.com/usage/actions/comparison/).
credentials. Gitea's job token cannot publish container packages, so the
publication step alone receives these repository secrets:
| Secret | Purpose |
| ------------------- | --------------------------------------------------------------------------- |
| `REGISTRY_USERNAME` | The package publisher's Gitea username, authorized to publish for `nessar`. |
| `REGISTRY_PASSWORD` | A dedicated personal access token with `write:package` permission. |
| Secret | Purpose |
| ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `REGISTRY_USERNAME` | The package publisher's Gitea username, authorized to publish for `nessar`. |
| `REGISTRY_PASSWORD` | A dedicated personal access token with `write:package` permission. |
| `KOMODO_URL` | Komodo Core's base URL as the job container reaches it. Komodo and Gitea share the host but not a Docker network, so use Komodo's public URL or the host address, not a Docker container name. |
| `KOMODO_API_KEY` | API key of a Komodo user allowed to execute both stacks. |
| `KOMODO_API_SECRET` | That API key's secret. |
Keep secret values in Gitea's Actions secret store. The configured tea account's
administrator token is not a CI publishing credential. No SSH or deployment
secret is required by this workflow.
## Repository settings
- `main` is the default and only protected branch.
- Required status check: `CI / required (pull_request)`.
- Merge allowlist: the owner and the `renovate` bot.
- Outdated PRs blocked; direct and forced pushes forbidden.
- Rebase and fast-forward-only merges allowed; merge commits and squash disabled.
## Bun toolchain and Node
@@ -88,7 +102,7 @@ only one place fails CI instead of drifting. Renovate groups `bun`, `@types/bun`
and the `oven/bun` image in one PR that it never automerges; finish that PR by
updating the installer's version and checksums.
- **Install.** `policy`, `validate`, `test`, `benchmark`, `build` and `images`
- **Install.** `policy`, `validate`, `test`, `benchmark`, `build` and `publish`
run `sh scripts/install-bun.sh`. It downloads the release zip for the
runner's architecture (x64 or aarch64) and libc (glibc, or musl on Alpine),
verifies its pinned SHA-256, and installs `/opt/bun/bin/bun`. It uses no npm.
@@ -96,38 +110,15 @@ updating the installer's version and checksums.
`defaults.run.shell: env PATH=/opt/bun/bin:/usr/bin:/bin bash -e {0}`. Every
`run:` step then sees Bun but not `/usr/local/bin`, where the `node` image keeps
`node`, `npm` and `yarn`. `bun run` additionally runs Node-shebang tools on Bun
through `bunfig.toml`. The security scanners are not project JavaScript, so
`security` has no Bun and no custom shell.
- **Why the containers keep Node.** `actions/checkout@v4` (`node20`) and
`actions/upload-artifact@v3` (`node16`) are JavaScript actions. The runner
starts them with the container's `node`; the custom shell does not affect
`uses:` steps. This is a platform requirement, not permission to run project
commands on Node.
- **`images` exception.** Alpine's `nodejs` package installs `node` into
through `bunfig.toml`.
- **Why the containers keep Node.** Gitea's checkout and upload-artifact actions
are JavaScript actions. The runner starts them with the container's `node`;
the custom shell does not affect `uses:` steps. This is a platform
requirement, not permission to run project commands on Node.
- **`publish` exception.** Alpine's `nodejs` package installs `node` into
`/usr/bin`, beside `git`, and checkout's post step needs it, so `PATH` cannot
hide it there. The project command is `/opt/bun/bin/bun scripts/ci-image.mjs`;
it starts only `process.execPath`, `docker` and `git`. Hiding Node there needs
an infrastructure decision (for example a runner image that ships Node outside
`PATH`), which this conversion does not make.
- **Needs live validation.** The custom shell template is a GitHub Actions
feature that Gitea's runner implements. A local run of the real engine
(`gitea-runner exec` v5.1.0, with the job containers above) executed it, but
only a live Gitea run confirms the instance's runner version, the checkout
action and the privileged Docker-in-Docker `images` job.
## Images and releases
Images use the [Gitea container registry](https://docs.gitea.com/usage/packages/container/)
at `gitea.nessar.fr/nessar/vac-optimizer`. Pushes to `develop` and `main` and
same-repository PRs publish `branch-<slug>` and `sha-<full commit SHA>`. Slugs
retain the previous lowercase, non-alphanumeric-to-hyphen, 63-byte
normalization; choose distinct branch slugs.
Only stable `vX.Y.Z` tags matching the tagged commit's `package.json` version
and reachable from `main` may promote images. Promotion first pulls the existing
SHA image, then publishes the version tag and `latest`; it never rebuilds.
An absent SHA image fails before either stable tag changes. Wait for the main
image job before tagging. No version increment or deployment is automatic.
it starts only `process.execPath`, `docker` and `git`.
## Claude review
@@ -138,67 +129,11 @@ It runs Claude Code 2.1.314 headless on the PR head with the checked-in
that the PR and its commits reference as the spec. Claude may only read files
and run read-only `git` commands, and never receives the Gitea token. The job
token posts the review, or a failure link, as a PR comment. Gitea reads
`issue_comment` workflows from the default branch, so the workflow takes effect
once it is on `develop`.
| Secret | Purpose |
| ------------------------- | ---------------------------------------------------------------------------- |
| `CLAUDE_CODE_OAUTH_TOKEN` | Output of `claude setup-token`; reviews use the owner's Claude subscription. |
`issue_comment` workflows from the default branch.
The workflow needs live validation of the job token's comment permission and of
the checkout of `refs/pull/<number>/head`.
## Merge messages and activation
The [merge template](../.gitea/default_merge_message/MERGE_TEMPLATE.md) translates
the previous title, closing-issue references, and review reference using
[Gitea's supported variables](https://docs.gitea.com/usage/issues-prs/merge-message-templates/).
For a PR titled `ci: migrate to Gitea Actions`, closing #268, with reference #271,
the checked expansion is:
```text
ci: migrate to Gitea Actions
close #268
See pull request #271
```
The owner has enabled Actions and approved validation before adding publisher
secrets. Complete the remaining activation checks in this order:
1. Review this workflow against the protected administrator exports for runner
requirements, triggers/schedules, permissions, secrets, publishing, and
deployment dependencies. The original CI definition is retained in Git:
`git show 0d900fd72d1a405d257f5a566c55cc0cb3d2bc61:.gitlab-ci.yml`.
2. Publish the reviewed feature branch and open its PR to register the workflow.
Once registered, manual dispatch verifies validation and artifacts without
publishing images. PR validation can also run now; its image and
aggregate checks remain blocked until publisher secrets are provisioned.
3. Verify runner isolation and Docker service support, then provision the two
publisher secrets. Review the package publisher's permissions and registry
namespace before permitting publication. Rerun the PR workflow and require a
successful **pull-request run** on the final commit, including PR title and
rebase checks, artifact handling, and actual image publication. A push run
or manual run alone does not validate the PR policy and publication.
4. Prepare and review the first PR's merge message before replacing the migration
gate. The target branch will not contain the new template until that first
merge, so explicitly use the validated PR title, closing references, and PR
reference for its merge message. Keep the migration gate throughout this
review.
5. After the successful PR run and merge-message approval, replace the migration
status requirement on both protected branches with the **actual reported
pull-request context** for the `required` job. Select it from the PR's reported
checks rather than a push run or a guessed context spelling. Fork PRs must
also be able to satisfy this check without base-repository push permissions.
Keep direct/force pushes disabled, merges restricted to maintainers, outdated
PRs blocked, and administrator protection bypass disabled. Select the rebase
merge method (fast-forward-only may stay enabled) and disable merge commits
and squash.
6. Merge the first PR using the approved message, then verify the resulting merge
commit. Subsequent merges read the committed template. No direct
integration-branch push is needed.
Historical job execution, reports, and downloadable artifacts remain in the
administrator rollback backups. They are not recreated or uploaded by this
conversion.
| Secret | Purpose |
| ------------------------- | ---------------------------------------------------------------------------- |
| `CLAUDE_CODE_OAUTH_TOKEN` | Output of `claude setup-token`; reviews use the owner's Claude subscription. |
+9 -19
View File
@@ -9,27 +9,17 @@ export function readCiContext() {
}
const event = JSON.parse(readFileSync(env.GITHUB_EVENT_PATH, 'utf8'));
const commit = env.GITHUB_SHA;
if (!/^[a-f0-9]{40}$/.test(commit ?? '')) throw new Error('A commit SHA is required.');
const sha = /^[a-f0-9]{40}$/;
if (!sha.test(commit ?? '')) throw new Error('A commit SHA is required.');
const pullRequest = eventName === 'pull_request' ? event.pull_request : undefined;
if (eventName === 'pull_request' && pullRequest?.head?.sha !== commit) {
throw new Error('CI must validate the pull request head commit.');
}
const tag = env.GITHUB_REF?.startsWith('refs/tags/') ? env.GITHUB_REF.slice(10) : '';
const branch = pullRequest
? pullRequest.head.ref
: env.GITHUB_REF?.startsWith('refs/heads/')
? env.GITHUB_REF.slice(11)
: '';
if (!tag && !branch) throw new Error('A branch or tag ref is required.');
const slug = branch
.toLowerCase()
.replace(/[^a-z0-9]/g, '-')
.slice(0, 63)
.replace(/^-+|-+$/g, '');
const publish =
eventName === 'push' ||
(eventName === 'pull_request' &&
Boolean(env.GITHUB_REPOSITORY) &&
pullRequest.head.repo?.full_name === env.GITHUB_REPOSITORY);
return { commit, tag, branch, slug, publish, pullRequest, before: event.before };
if (eventName === 'pull_request' && !sha.test(pullRequest.base?.sha ?? '')) {
throw new Error('A pull request base commit is required.');
}
const ref = env.GITHUB_REF ?? '';
const tag = ref.startsWith('refs/tags/') ? ref.slice(10) : '';
const branch = ref.startsWith('refs/heads/') ? ref.slice(11) : '';
return { eventName, commit, tag, branch, pullRequest };
}
+53 -10
View File
@@ -1,15 +1,58 @@
import { execFileSync } from 'node:child_process';
import { setTimeout as sleep } from 'node:timers/promises';
import { fileURLToPath } from 'node:url';
import { readCiContext } from './ci-context.mjs';
try {
const { commit, tag, slug, publish } = readCiContext();
if (!publish) throw new Error('Images can only be published by pushes or same-repository PRs.');
execFileSync(process.execPath, [fileURLToPath(new URL('./ci-policy.mjs', import.meta.url))]);
const env = process.env;
if (!env.REGISTRY_USERNAME || !env.REGISTRY_PASSWORD) {
throw new Error('REGISTRY_USERNAME and REGISTRY_PASSWORD are required for publication.');
const env = process.env;
// Waits for Komodo's update so that a deployment that did not happen fails the run.
async function deployStack(stack) {
const deadline = Date.now() + 10 * 60_000;
const call = async (path, type, params) => {
const response = await fetch(env.KOMODO_URL.replace(/\/+$/, '') + path, {
method: 'POST',
signal: AbortSignal.timeout(60_000),
headers: {
'content-type': 'application/json',
'x-api-key': env.KOMODO_API_KEY,
'x-api-secret': env.KOMODO_API_SECRET,
},
body: JSON.stringify({ type, params }),
});
if (!response.ok) {
throw new Error(`Komodo ${type} failed: ${response.status} ${await response.text()}`);
}
return response.json();
};
let update = await call('/execute', 'DeployStack', { stack });
const id = update._id?.$oid ?? update._id;
for (let polls = 0; update.status !== 'Complete'; polls++) {
if (Date.now() > deadline) {
throw new Error(`Komodo did not finish deploying ${stack} (update ${id}).`);
}
if (polls) await sleep(3000);
update = await call('/read', 'GetUpdate', { id });
}
if (!update.success) throw new Error(`Komodo failed to deploy ${stack} (update ${id}).`);
console.log(`Komodo deployed ${stack}.`);
}
try {
const { eventName, commit, tag, branch } = readCiContext();
if (eventName !== 'push' || !(tag || branch === 'main')) {
throw new Error('Images are published only by pushes to main and release tags.');
}
execFileSync(process.execPath, [fileURLToPath(new URL('./ci-policy.mjs', import.meta.url))]);
const stackVariable = tag ? 'KOMODO_PRODUCTION_STACK' : 'KOMODO_BETA_STACK';
const missing = [
'REGISTRY_USERNAME',
'REGISTRY_PASSWORD',
'KOMODO_URL',
'KOMODO_API_KEY',
'KOMODO_API_SECRET',
stackVariable,
].filter((name) => !env[name]);
if (missing.length) throw new Error(`Publication requires ${missing.join(', ')}.`);
const registry = new URL(env.GITHUB_SERVER_URL).host;
const image = `${registry}/${env.GITHUB_REPOSITORY.toLowerCase()}`;
const shaImage = `${image}:sha-${commit}`;
@@ -29,11 +72,11 @@ try {
docker('tag', shaImage, `${image}:latest`);
docker('push', `${image}:latest`);
} else {
const branchImage = `${image}:branch-${slug}`;
docker('build', '-t', shaImage, '-t', branchImage, '.');
docker('build', '-t', shaImage, '-t', `${image}:beta`, '.');
docker('push', shaImage);
docker('push', branchImage);
docker('push', `${image}:beta`);
}
await deployStack(env[stackVariable]);
} catch (error) {
console.error(error.message);
process.exitCode = 1;
+112 -72
View File
@@ -1,6 +1,7 @@
import assert from 'node:assert/strict';
import { execFileSync, spawnSync } from 'node:child_process';
import { execFileSync, spawn } from 'node:child_process';
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { createServer } from 'node:http';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -12,31 +13,52 @@ const image = 'gitea.nessar.fr/nessar/vac-optimizer';
const commandsPath = join(directory, 'docker-commands.jsonl');
const bin = join(directory, 'bin');
const run = (variables = {}, expected = 0) => {
// Fake Komodo: records each API call, reports an update in progress, then its result.
let komodoCalls = [];
let komodoAnswer = 'success';
const komodo = createServer((request, response) => {
let body = '';
request.on('data', (chunk) => (body += chunk));
request.on('end', () => {
const { type, params } = JSON.parse(body);
komodoCalls.push({
path: request.url,
key: request.headers['x-api-key'],
secret: request.headers['x-api-secret'],
type,
params,
});
const update =
type === 'DeployStack'
? { _id: { $oid: 'update-1' }, status: 'InProgress', success: false }
: {
_id: { $oid: 'update-1' },
status: 'Complete',
success: komodoAnswer === 'success',
};
response.statusCode = komodoAnswer === 'refused' ? 401 : 200;
response.setHeader('content-type', 'application/json');
response.end(JSON.stringify(update));
});
});
await new Promise((resolve) => komodo.listen(0, '127.0.0.1', resolve));
const run = async (variables = {}, expected = 0) => {
const commit = git('rev-parse', 'HEAD');
const eventName = variables.eventName ?? 'push';
const ref = variables.tag
? `refs/tags/${variables.tag}`
: eventName === 'pull_request'
? 'refs/pull/42/head'
: 'refs/heads/feature/calendar';
: `refs/heads/${variables.branch ?? 'main'}`;
const event = { ref };
if (eventName === 'pull_request') {
event.pull_request = {
title: 'feat: calendar',
head: {
sha: commit,
ref: 'feature/calendar',
repo: { full_name: variables.headRepository ?? 'nessar/vac-optimizer' },
},
base: { ref: 'develop' },
};
}
if (eventName === 'pull_request') event.pull_request = { head: { sha: commit } };
writeFileSync(join(directory, 'event.json'), JSON.stringify(event));
writeFileSync(commandsPath, '');
const result = spawnSync(process.execPath, [script], {
komodoCalls = [];
komodoAnswer = variables.komodo ?? 'success';
const child = spawn(process.execPath, [script], {
cwd: directory,
encoding: 'utf8',
env: {
PATH: `${bin}:${process.env.PATH}`,
GITHUB_EVENT_NAME: eventName,
@@ -47,13 +69,44 @@ const run = (variables = {}, expected = 0) => {
GITHUB_SERVER_URL: 'https://gitea.nessar.fr',
REGISTRY_USERNAME: 'publisher',
REGISTRY_PASSWORD: variables.registryPassword ?? 'test-token',
KOMODO_URL: `http://127.0.0.1:${komodo.address().port}/`,
KOMODO_API_KEY: 'komodo-key',
KOMODO_API_SECRET: variables.komodoSecret ?? 'komodo-secret',
KOMODO_BETA_STACK: 'beta-stack',
KOMODO_PRODUCTION_STACK: 'production-stack',
DOCKER_COMMANDS: commandsPath,
MISSING_IMAGE: variables.missingImage ? 'true' : '',
},
});
assert.equal(result.status, expected, result.stdout + result.stderr);
return readFileSync(commandsPath, 'utf8').trim().split('\n').filter(Boolean).map(JSON.parse);
let output = '';
child.stdout.on('data', (chunk) => (output += chunk));
child.stderr.on('data', (chunk) => (output += chunk));
const status = await new Promise((resolve) => child.on('close', resolve));
assert.equal(status, expected, output);
const docker = readFileSync(commandsPath, 'utf8').trim().split('\n').filter(Boolean);
return {
docker: docker.map(JSON.parse).map(({ args }) => args.join(' ')),
komodo: komodoCalls,
};
};
const deployed = (stack) => [
{
path: '/execute',
key: 'komodo-key',
secret: 'komodo-secret',
type: 'DeployStack',
params: { stack },
},
{
path: '/read',
key: 'komodo-key',
secret: 'komodo-secret',
type: 'GetUpdate',
params: { id: 'update-1' },
},
];
const nothing = { docker: [], komodo: [] };
const login = 'login gitea.nessar.fr --username publisher --password-stdin';
try {
git('init', '--initial-branch=main');
@@ -63,9 +116,6 @@ try {
writeFileSync(join(directory, 'package.json'), '{"version":"1.5.0"}\n');
git('add', 'package.json');
git('commit', '-m', 'chore: initial release');
git('branch', 'develop');
git('switch', '-c', 'feature/calendar');
git('commit', '--allow-empty', '-m', 'feat: calendar');
mkdirSync(bin);
const docker = join(bin, 'docker');
writeFileSync(
@@ -75,63 +125,53 @@ import { appendFileSync, readFileSync } from 'node:fs';
const args = process.argv.slice(2);
const input = args[0] === 'login' ? readFileSync(0, 'utf8') : '';
appendFileSync(process.env.DOCKER_COMMANDS, JSON.stringify({ args, input }) + '\\n');
if (args[0] === 'login' && input !== 'test-token') process.exit(1);
if (args[0] === 'pull' && process.env.MISSING_IMAGE === 'true') process.exit(1);
`,
);
chmodSync(docker, 0o755);
const commit = git('rev-parse', 'HEAD');
const commands = run();
assert.deepEqual(commands, [
{
args: ['login', 'gitea.nessar.fr', '--username', 'publisher', '--password-stdin'],
input: 'test-token',
},
{
args: [
'build',
'-t',
`${image}:sha-${commit}`,
'-t',
`${image}:branch-feature-calendar`,
'.',
],
input: '',
},
{ args: ['push', `${image}:sha-${commit}`], input: '' },
{ args: ['push', `${image}:branch-feature-calendar`], input: '' },
]);
assert.deepEqual(run({ eventName: 'pull_request' }), commands);
assert.deepEqual(
run({ eventName: 'pull_request', headRepository: 'contributor/vac-optimizer' }, 1),
[],
);
assert.deepEqual(run({ eventName: 'workflow_dispatch' }, 1), []);
assert.deepEqual(run({ registryPassword: '' }, 1), []);
assert.deepEqual(run({ tag: 'v1.5.0' }, 1), []);
git('switch', 'main');
assert.deepEqual(await run(), {
docker: [
login,
`build -t ${image}:sha-${commit} -t ${image}:beta .`,
`push ${image}:sha-${commit}`,
`push ${image}:beta`,
],
komodo: deployed('beta-stack'),
});
assert.equal((await run({ komodo: 'failure' }, 1)).komodo.length, 2);
assert.equal((await run({ komodo: 'refused' }, 1)).komodo.length, 1);
assert.deepEqual(await run({ eventName: 'pull_request' }, 1), nothing);
assert.deepEqual(await run({ eventName: 'workflow_dispatch' }, 1), nothing);
assert.deepEqual(await run({ branch: 'feature/calendar' }, 1), nothing);
assert.deepEqual(await run({ registryPassword: '' }, 1), nothing);
assert.deepEqual(await run({ komodoSecret: '' }, 1), nothing);
git('tag', '-a', 'v1.5.0', '-m', 'Release 1.5.0');
const releaseCommit = git('rev-parse', 'HEAD');
assert.deepEqual(run({ tag: 'v1.5.0' }), [
{
args: ['login', 'gitea.nessar.fr', '--username', 'publisher', '--password-stdin'],
input: 'test-token',
},
{ args: ['pull', `${image}:sha-${releaseCommit}`], input: '' },
{ args: ['tag', `${image}:sha-${releaseCommit}`, `${image}:v1.5.0`], input: '' },
{ args: ['push', `${image}:v1.5.0`], input: '' },
{ args: ['tag', `${image}:sha-${releaseCommit}`, `${image}:latest`], input: '' },
{ args: ['push', `${image}:latest`], input: '' },
]);
assert.deepEqual(run({ tag: 'v1.5.0', missingImage: true }, 1), [
{
args: ['login', 'gitea.nessar.fr', '--username', 'publisher', '--password-stdin'],
input: 'test-token',
},
{ args: ['pull', `${image}:sha-${releaseCommit}`], input: '' },
]);
assert.deepEqual(run({ tag: 'v1.5.0-rc.1' }, 1), []);
assert.deepEqual(run({ tag: 'v1.6.0' }, 1), []);
console.log('CI image publication checks passed.');
assert.deepEqual(await run({ tag: 'v1.5.0' }), {
docker: [
login,
`pull ${image}:sha-${commit}`,
`tag ${image}:sha-${commit} ${image}:v1.5.0`,
`push ${image}:v1.5.0`,
`tag ${image}:sha-${commit} ${image}:latest`,
`push ${image}:latest`,
],
komodo: deployed('production-stack'),
});
assert.deepEqual(await run({ tag: 'v1.5.0', missingImage: true }, 1), {
docker: [login, `pull ${image}:sha-${commit}`],
komodo: [],
});
assert.deepEqual(await run({ tag: 'v1.5.0-rc.1' }, 1), nothing);
assert.deepEqual(await run({ tag: 'v1.6.0' }, 1), nothing);
git('switch', '-c', 'feature/calendar');
git('commit', '--allow-empty', '-m', 'feat: calendar');
assert.deepEqual(await run({ tag: 'v1.5.0' }, 1), nothing);
console.log('CI image publication and deployment checks passed.');
} finally {
komodo.close();
rmSync(directory, { recursive: true, force: true });
}
+16 -57
View File
@@ -1,26 +1,16 @@
import { execFileSync, spawnSync } from 'node:child_process';
import { appendFileSync, readFileSync } from 'node:fs';
import { readFileSync } from 'node:fs';
import { readCiContext } from './ci-context.mjs';
const env = process.env;
const git = (...args) => execFileSync('git', args, { encoding: 'utf8' }).trim();
const ancestor = (base, commit) =>
spawnSync('git', ['merge-base', '--is-ancestor', base, commit]).status === 0;
const conventional = /^[a-z]+(?:\([^()\r\n]+\))?!?: \S.*$/i;
const requirePolicy = (condition, message) => {
if (!condition) throw new Error(message);
};
try {
const { commit, tag, branch, slug, pullRequest, before } = readCiContext();
const { commit, tag, pullRequest } = readCiContext();
requirePolicy(commit === git('rev-parse', 'HEAD'), 'CI must validate the checked-out commit.');
git(
'fetch',
'--no-tags',
'origin',
'+refs/heads/main:refs/remotes/origin/main',
'+refs/heads/develop:refs/remotes/origin/develop',
);
if (tag) {
requirePolicy(
@@ -29,47 +19,19 @@ try {
);
const { version } = JSON.parse(readFileSync('package.json', 'utf8'));
requirePolicy(tag === `v${version}`, 'Release tag must match package.json.');
requirePolicy(ancestor(commit, 'origin/main'), 'Release commit must belong to main.');
} else {
const target = pullRequest
? pullRequest.base?.ref
: branch === 'main' || branch?.startsWith('hotfix/')
? 'main'
: 'develop';
requirePolicy(branch, 'A branch name is required.');
git('check-ref-format', `refs/heads/${branch}`);
requirePolicy(['main', 'develop'].includes(target), 'PRs must target main or develop.');
if (pullRequest) {
const title = pullRequest.title?.replace(
/^(?:Draft:|WIP:|\[Draft\]|\[WIP\]|\(Draft\)|\(WIP\))\s*/i,
'',
);
requirePolicy(
conventional.test(title ?? ''),
'PR title must use Conventional Commits.',
);
requirePolicy(
target !== 'main' || /^(release|hotfix)\/.+/.test(branch),
'Only release/* and hotfix/* may merge into main.',
);
if (target === 'develop' && branch !== 'main' && !/^(release|hotfix)\//.test(branch)) {
requirePolicy(
ancestor('origin/develop', commit),
'Rebase the working branch onto origin/develop before merging.',
);
requirePolicy(
!git('rev-list', '--merges', `origin/develop..${commit}`),
'Working branches must use rebase, not merge commits.',
);
}
}
const base =
!pullRequest && before && !/^0+$/.test(before) && ancestor(before, commit)
? before
: git('merge-base', `origin/${target}`, commit);
const subjects = git('log', '--format=%h %s', `${base}..${commit}`);
git('fetch', '--no-tags', 'origin', '+refs/heads/main:refs/remotes/origin/main');
requirePolicy(
spawnSync('git', ['merge-base', '--is-ancestor', commit, 'origin/main']).status === 0,
'Release commit must belong to main.',
);
} else if (pullRequest) {
// Only the PR's own commits, so inherited history never blocks a PR.
const range = `${pullRequest.base.sha}..${commit}`;
requirePolicy(
!git('rev-list', '--merges', range),
'Pull requests must not contain merge commits; rebase instead.',
);
const subjects = git('log', '--format=%h %s', range);
for (const line of subjects ? subjects.split('\n') : []) {
requirePolicy(
conventional.test(line.slice(line.indexOf(' ') + 1)),
@@ -77,10 +39,7 @@ try {
);
}
}
if (env.GITHUB_OUTPUT) {
appendFileSync(env.GITHUB_OUTPUT, `slug=${slug}\ntag=${tag}\n`);
}
console.log('GitFlow, version and commit policy passed.');
console.log('Commit and release policy passed.');
} catch (error) {
console.error(error.message);
process.exitCode = 1;
+23 -68
View File
@@ -1,6 +1,6 @@
import assert from 'node:assert/strict';
import { execFileSync, spawnSync } from 'node:child_process';
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -10,29 +10,21 @@ const script = fileURLToPath(new URL('./ci-policy.mjs', import.meta.url));
const git = (...args) => execFileSync('git', args, { cwd: directory, encoding: 'utf8' }).trim();
const check = (variables = {}, expected = 0) => {
const commit = git('rev-parse', 'HEAD');
const branch = variables.branch ?? 'feature/test';
const eventName = variables.eventName ?? 'push';
const ref = variables.tag
? `refs/tags/${variables.tag}`
: eventName === 'pull_request'
? 'refs/pull/42/head'
: `refs/heads/${branch}`;
const event = { ref, before: variables.before };
: 'refs/heads/main';
const event = { ref };
if (eventName === 'pull_request') {
event.pull_request = {
title: variables.title ?? 'feat(test): add policy checks',
head: {
ref: branch,
sha: variables.headSha ?? commit,
repo: { full_name: variables.headRepository ?? 'nessar/vac-optimizer' },
},
base: { ref: variables.target ?? 'develop' },
head: { sha: variables.headSha ?? commit },
base: { sha: variables.base },
};
}
const eventPath = join(directory, 'event.json');
const outputPath = join(directory, 'outputs');
writeFileSync(eventPath, JSON.stringify(event));
writeFileSync(outputPath, '');
const result = spawnSync(process.execPath, [script], {
cwd: directory,
encoding: 'utf8',
@@ -42,14 +34,10 @@ const check = (variables = {}, expected = 0) => {
GITHUB_EVENT_PATH: eventPath,
GITHUB_REF: ref,
GITHUB_SHA: variables.sha ?? commit,
GITHUB_REPOSITORY: 'nessar/vac-optimizer',
GITHUB_OUTPUT: outputPath,
},
});
assert.equal(result.status, expected, result.stdout + result.stderr);
return readFileSync(outputPath, 'utf8');
};
const pr = { eventName: 'pull_request' };
try {
git('init', '--initial-branch=main');
@@ -59,70 +47,37 @@ try {
writeFileSync(join(directory, 'package.json'), '{"version":"1.5.0"}\n');
git('add', 'package.json');
git('commit', '-m', 'Legacy history is allowed');
git('branch', 'develop');
const main = git('rev-parse', 'HEAD');
git('switch', '-c', 'feature/test');
git('commit', '--allow-empty', '-m', 'feat(test)!: add checks');
check({});
const pr = { eventName: 'pull_request', base: main };
check(pr);
check({ ...pr, headRepository: 'contributor/vac-optimizer' });
check({});
check({ eventName: 'workflow_dispatch' });
assert.match(check({ branch: 'Feature/My_calendar' }), /slug=feature-my-calendar\n/);
check({ ...pr, base: undefined }, 1);
check({ ...pr, headSha: '0'.repeat(40) }, 1);
check({ eventName: 'pull_request_target' }, 1);
check({ ...pr, title: 'Draft: feat: test policy' });
check({ ...pr, title: '(Draft) feat: test policy' });
check({ ...pr, target: 'main' }, 1);
check({ ...pr, title: 'Add checks' }, 1);
check({ tag: 'v1.5.0' }, 1);
check({ sha: '0'.repeat(40) }, 1);
git('switch', 'develop');
git('commit', '--allow-empty', '-m', 'fix: another change');
git('switch', 'feature/test');
check(pr, 1);
git('rebase', 'develop');
check(pr);
const before = git('rev-parse', 'HEAD');
// The range starts at whatever base the PR names.
git('commit', '--allow-empty', '-m', 'not conventional');
check({ before: before }, 1);
const stacked = git('rev-parse', 'HEAD');
git('commit', '--allow-empty', '-m', 'fix: follow up');
check(pr, 1);
git('commit', '--amend', '--allow-empty', '-m', 'ci: fix the commit title');
check({ before: before });
check({ ...pr, base: stacked });
git('switch', 'develop');
git('merge', '--no-ff', 'feature/test', '-m', 'feat(test): add policy checks');
git('switch', '-c', 'release/1.6.0');
writeFileSync(join(directory, 'package.json'), '{"version":"1.6.0"}\n');
git('add', 'package.json');
git('commit', '-m', 'chore(release): prepare 1.6.0');
check({
...pr,
branch: 'release/1.6.0',
target: 'main',
});
check({ ...pr, branch: 'release/1.6.0' });
git('switch', 'main');
git('merge', '--no-ff', 'release/1.6.0', '-m', 'chore(release): publish 1.6.0');
check({ tag: 'v1.6.0' });
check({ tag: 'v1.5.0' }, 1);
check({ tag: 'v01.6.0' }, 1);
check({ tag: 'v1.6.0-rc.1' }, 1);
check({ ...pr, branch: 'main' });
git('switch', '-c', 'hotfix/1.6.1');
git('commit', '--allow-empty', '-m', 'fix: production issue');
check({
...pr,
branch: 'hotfix/1.6.1',
target: 'main',
});
check({ ...pr, branch: 'hotfix/1.6.1' });
// The working branch must not pass by merging develop instead of rebasing.
git('commit', '--allow-empty', '-m', 'fix: on main');
git('switch', 'feature/test');
git('commit', '--allow-empty', '-m', 'feat: keep working');
git('merge', '--no-ff', 'develop', '-m', 'chore: merge develop');
check(pr, 1);
git('merge', '--no-ff', 'main', '-m', 'chore: merge main');
check({ ...pr, base: stacked }, 1);
check({ tag: 'v1.5.0' }, 1);
git('switch', 'main');
check({ tag: 'v1.5.0' });
check({ tag: 'v1.6.0' }, 1);
check({ tag: 'v01.5.0' }, 1);
check({ tag: 'v1.5.0-rc.1' }, 1);
console.log('CI policy integration checks passed.');
} finally {