Compare commits

..
Author SHA1 Message Date
Matthijs IriksandClaude Sonnet 5.5 c502c9c2c0 CI: composer-cache en herhaalpogingen in alle jobs
PR CI / ledger (pull_request) Successful in 3s
PR CI / flow (pull_request) Successful in 4s
PR CI / test (stable) (pull_request) Successful in 36s
PR CI / test (lowest) (pull_request) Successful in 40s
PR CI / security (pull_request) Successful in 52s
PR CI / pr-ci (pull_request) Successful in 1s
PR CI / release-automerge (pull_request) Successful in 3s
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-12-04 02:20:25 +01:00
lil-koneko 2539dfcc3e Merge pull request 'Release v0.1.0' (#9) from release/v0.1.0 into production
Release / verify (push) Successful in 23s
Release / tag (push) Successful in 4s
Release / packagist (push) Successful in 3s
Release / sync-develop (push) Successful in 4s
Reviewed-on: #9
2026-12-04 01:07:49 +00:00
deploy-bot 98d12db241 Merge pull request 'Changelog-kop van v0.1.0 herstellen' (#10) from fix/changelog-heading into release/v0.1.0
PR CI / flow (pull_request) Successful in 4s
PR CI / ledger (pull_request) Successful in 4s
PR CI / test (stable) (pull_request) Successful in 21s
PR CI / test (lowest) (pull_request) Successful in 30s
PR CI / security (pull_request) Successful in 43s
PR CI / pr-ci (pull_request) Successful in 2s
PR CI / release-automerge (pull_request) Skipped
2026-12-04 01:04:46 +00:00
Matthijs Iriks 498ffd4462 Fix the changelog heading of v0.1.0
PR CI / ledger (pull_request) Successful in 4s
PR CI / flow (pull_request) Successful in 4s
PR CI / test (lowest) (pull_request) Successful in 17s
PR CI / test (stable) (pull_request) Successful in 29s
PR CI / security (pull_request) Successful in 41s
PR CI / pr-ci (pull_request) Successful in 1s
PR CI / release-automerge (pull_request) Successful in 3s
2026-12-04 02:01:01 +01:00
deploy-bot 5a0b53025b Merge pull request 'Changelog voor v0.1.0' (#8) from feature/changelog-v0.1.0 into release/v0.1.0
PR CI / ledger (pull_request) Successful in 3s
PR CI / flow (pull_request) Failing after 4s
PR CI / test (lowest) (pull_request) Failing after 26s
PR CI / test (stable) (pull_request) Successful in 28s
PR CI / security (pull_request) Successful in 46s
PR CI / pr-ci (pull_request) Failing after 2s
PR CI / release-automerge (pull_request) Skipped
2026-12-04 00:58:19 +00:00
Matthijs Iriks da5bace656 TOKENS: row with real numbers
PR CI / flow (pull_request) Successful in 4s
PR CI / ledger (pull_request) Successful in 4s
PR CI / test (lowest) (pull_request) Successful in 34s
PR CI / test (stable) (pull_request) Successful in 35s
PR CI / security (pull_request) Successful in 43s
PR CI / pr-ci (pull_request) Successful in 1s
PR CI / release-automerge (pull_request) Successful in 3s
2026-12-04 01:57:29 +01:00
Matthijs Iriks 5c0eec9477 Changelog for v0.1.0
PR CI / ledger (pull_request) Successful in 3s
PR CI / flow (pull_request) Successful in 4s
PR CI / test (lowest) (pull_request) Successful in 27s
PR CI / test (stable) (pull_request) Successful in 37s
PR CI / security (pull_request) Successful in 45s
PR CI / pr-ci (pull_request) Successful in 1s
PR CI / release-automerge (pull_request) Successful in 3s
2026-12-04 01:57:22 +01:00
deploy-bot 22cbe043f1 Merge pull request 'LICENSE toevoegen' (#7) from feature/license into release/v0.1.0 2026-12-04 00:57:06 +00:00
Matthijs Iriks a0d7840158 TOKENS: row with real numbers
PR CI / flow (pull_request) Successful in 4s
PR CI / ledger (pull_request) Successful in 3s
PR CI / test (stable) (pull_request) Successful in 30s
PR CI / test (lowest) (pull_request) Successful in 31s
PR CI / security (pull_request) Successful in 44s
PR CI / pr-ci (pull_request) Successful in 2s
PR CI / release-automerge (pull_request) Successful in 4s
2026-12-04 01:56:16 +01:00
Matthijs Iriks 16fdfc887c Add the MIT license file
PR CI / flow (pull_request) Successful in 3s
PR CI / ledger (pull_request) Successful in 4s
PR CI / test (lowest) (pull_request) Successful in 29s
PR CI / test (stable) (pull_request) Successful in 33s
PR CI / security (pull_request) Successful in 43s
PR CI / pr-ci (pull_request) Successful in 1s
PR CI / release-automerge (pull_request) Successful in 3s
2026-12-04 01:56:05 +01:00
lil-koneko 02f0ec5149 Merge pull request 'Checkout zonder git repareren en oude branches opruimen' (#6) from fix/checkout-without-git into develop
Reviewed-on: #6
2026-12-04 00:54:35 +00:00
Matthijs Iriks eb93e890d6 Fix checkout in jobs without git (export-ignore); prune quiet feature branches after 30 days
PR CI / pr-ci (pull_request) Skipped
2026-12-04 01:53:20 +01:00
lil-koneko 86ecde31ea Merge pull request 'CI en releasecyclus' (#5) from feature/ci-release-flow into develop
Reviewed-on: #5
2026-12-04 00:51:08 +00:00
Matthijs Iriks 476311544f README: what Composer installs
PR CI / pr-ci (pull_request) Skipped
2026-12-04 01:49:01 +01:00
Matthijs Iriks fb0caac84e Keep repository-only files out of the Composer package (export-ignore) 2026-12-04 01:48:55 +01:00
Matthijs Iriks ee29c41363 Merge develop into feature/ci-release-flow 2026-12-04 01:46:08 +01:00
Matthijs Iriks 302a1c699d CI and release cycle: release branches, tag, Packagist, sync, tests, audit, Trivy 2026-12-04 01:45:44 +01:00
lil-koneko 7a979bb081 Merge pull request 'Posts in develop brengen' (#4) from feature/users-and-media into develop
Reviewed-on: #4
2026-12-04 00:42:02 +00:00
Matthijs Iriks f34e3d312e Merge develop into feature/users-and-media 2026-12-04 01:40:26 +01:00
lil-koneko f74ab3a94b Merge pull request 'Token-script: helper-agents meetellen' (#3) from fix/token-usage-helper-agents into develop
Reviewed-on: #3
2026-12-04 00:38:18 +00:00
Matthijs Iriks 2768234739 Token script: count helper agents in the row, one row per model 2026-12-04 01:37:13 +01:00
lil-koneko bf8201059f Merge pull request 'Posts overzetten' (#2) from feature/posts into feature/users-and-media
Reviewed-on: #2
2026-12-04 00:35:58 +00:00
lil-koneko 7105cfc239 Merge pull request 'Gebruikers en media overzetten' (#1) from feature/users-and-media into develop
Reviewed-on: #1
2026-12-04 00:35:51 +00:00
25 changed files with 1331 additions and 30 deletions

No files matched your search

+17
View File
@@ -0,0 +1,17 @@
# Normalise line endings in the repository.
* text=auto eol=lf
# What stays in the repository but is not part of the package that Composer installs (Packagist builds
# the dist archive from `git archive`, which leaves these out).
# Because of that, every CI job that checks out must run in an image with git (webdevops/php has it):
# without git, actions/checkout downloads that same archive and the .gitea/ scripts are missing.
/.gitattributes export-ignore
/.gitea export-ignore
/.gitignore export-ignore
/dev export-ignore
/scripts export-ignore
/TOKENS.md export-ignore
/AGENTS.md export-ignore
/tests export-ignore
/phpunit.xml export-ignore
/pint.json export-ignore
+26
View File
@@ -0,0 +1,26 @@
## Vraag
<!-- Wat was de vraag of de opdracht? Eén of twee zinnen, in de woorden van wie het vroeg. -->
## Wat is er gedaan
<!-- Beknopte lijst: per punt één regel. -->
-
## Zo test je het
<!-- Een checklist die af te vinken is: waar klik je, wat moet je zien. -->
- [ ]
## Zelf getest
<!-- Wat is er al gecontroleerd, en hoe (tests, handmatig, op welke omgeving). Ook wat niet getest is. -->
-
## Tijd en tokens
<!-- De regel(s) uit TOKENS.md van deze PR: uren, tokens, model. -->
## Onderhoud
<!-- Is er onderhoud meegenomen (updates, opruimen, documentatie)? Anders: Niets. -->
## Met de hand te doen
<!-- Wat moet er na het mergen nog met de hand gebeuren (secrets, .env, instellingen)? Anders: Niets. -->
## Vervolgstappen
<!-- Wat ligt er nog, wat is bewust niet gedaan? Anders: Geen. -->
+76
View File
@@ -0,0 +1,76 @@
#!/usr/bin/env python3
"""Turns on auto-merge for a pull request to a release branch (`release/vX.Y.Z`).
Run by the `release-automerge` job whenever such a pull request is opened or updated. Gitea then
merges it by itself once the required check is green, so features flow into the release branch
without anyone pressing the button. A pull request to anything else is left alone: `production`
is merged by hand.
Environment: GT_URL, GT_OWNER, GT_REPO, GT_TOKEN (a token that may edit pull requests),
PULL_REQUEST_NUMBER. Optional: AUTO_MERGE_PREFIX (default "release/"), MERGE_STYLE (default "merge").
Standard library only.
"""
import json
import os
import sys
import urllib.error
import urllib.request
URL = os.environ.get("GT_URL", "").rstrip("/")
OWNER = os.environ.get("GT_OWNER", "")
REPO = os.environ.get("GT_REPO", "")
TOKEN = os.environ.get("GT_TOKEN", "")
NUMBER = os.environ.get("PULL_REQUEST_NUMBER", "").lstrip("#")
PREFIX = os.environ.get("AUTO_MERGE_PREFIX") or "release/"
MERGE_STYLE = os.environ.get("MERGE_STYLE") or "merge"
ALREADY_ON = object()
def api(method, path, body=None):
request = urllib.request.Request(
f"{URL}/api/v1/repos/{OWNER}/{REPO}/{path}",
data=json.dumps(body).encode() if body is not None else None,
method=method,
headers={"Authorization": f"token {TOKEN}", "Content-Type": "application/json"},
)
try:
with urllib.request.urlopen(request, timeout=30) as response:
text = response.read().decode()
except urllib.error.HTTPError as e:
detail = e.read().decode()
# A second push runs this job again while auto-merge is still on: that is what was wanted.
if e.code == 409 and "already scheduled to auto merge" in detail:
return ALREADY_ON
sys.exit(f"Gitea API {method} {path} failed: {e.code} {detail}")
return json.loads(text) if text else None
def main():
if not (URL and OWNER and REPO and TOKEN and NUMBER.isdigit()):
sys.exit("GT_URL, GT_OWNER, GT_REPO, GT_TOKEN and PULL_REQUEST_NUMBER are required.")
pull = api("GET", f"pulls/{NUMBER}") or {}
base_ref = (pull.get("base") or {}).get("ref", "")
if not base_ref.startswith(PREFIX):
print(f"Pull request #{NUMBER} targets {base_ref}, not {PREFIX}*: left alone.")
return
if pull.get("state") != "open" or pull.get("merged"):
print(f"Pull request #{NUMBER} is not open: nothing to do.")
return
answer = api("POST", f"pulls/{NUMBER}/merge", {
"do": MERGE_STYLE,
"merge_when_checks_succeed": True,
"delete_branch_after_merge": False,
})
if answer is ALREADY_ON:
print(f"Auto-merge was already on for pull request #{NUMBER}.")
return
print(f"Auto-merge is on for pull request #{NUMBER}: it merges once the required check is green.")
if __name__ == "__main__":
main()
+85
View File
@@ -0,0 +1,85 @@
#!/usr/bin/env python3
"""PR CI: does this pull request follow the development cycle?
develop -> feature/*, fix/*, ... -> release/vX.Y.Z -> production
(collects features) (release: tag + Packagist)
production -> develop (the sync after a release, by the pipeline)
Pull requests go to a release branch or to production, never to develop.
- to `release/vX.Y.Z`: the release must not be out yet (its version is above the latest tag),
and the pull request does not come from production, develop or another release branch.
- to `production`: only from `release/vX.Y.Z`, with a version above the latest tag, a section
for it in CHANGELOG.md, and no "version" in composer.json (Packagist reads the tag).
Environment: BASE_REF, HEAD_REF. Run in a checkout with the tags (fetch-depth 0).
Standard library + git only.
"""
import json
import os
import subprocess
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import semver # noqa: E402
def tags():
result = subprocess.run(["git", "tag", "--list", "v*"], capture_output=True, text=True)
return result.stdout.split()
def problems(base, head, existing_tags, changelog, composer):
found = []
newest = semver.latest(existing_tags)
if base == "production":
version = semver.release_version(head)
if version is None:
return [f"A pull request to production comes from a branch named release/vX.Y.Z, not from {head or '?'}."]
found += above_latest(version, newest)
if changelog is None or semver.changelog_section(changelog, version) is None:
found.append(f"CHANGELOG.md has no section '## v{semver.text(version)}' for this release.")
if isinstance(composer, dict) and "version" in composer:
found.append("composer.json must not have a \"version\": Packagist takes the version from the tag.")
return found
if base.startswith("release/"):
version = semver.release_version(base)
if version is None:
return [f"{base} is not a release branch name: use release/vX.Y.Z."]
found += above_latest(version, newest, "That release is already out: start the next one.")
if head in ("production", "develop") or head.startswith("release/"):
found.append(f"A release branch takes features (feature/*, fix/*), not {head}.")
return found
return [f"Pull requests go to release/vX.Y.Z or to production, not to {base or '?'}: develop only takes the sync after a release."]
def above_latest(version, newest, hint="The version of a release must be above the latest tag."):
if newest is not None and version <= newest:
return [f"v{semver.text(version)} is not above the latest tag v{semver.text(newest)}. {hint}"]
return []
def main():
base = os.environ.get("BASE_REF", "").strip()
head = os.environ.get("HEAD_REF", "").strip()
changelog = open("CHANGELOG.md", encoding="utf-8").read() if os.path.exists("CHANGELOG.md") else None
try:
composer = json.load(open("composer.json", encoding="utf-8"))
except (OSError, ValueError):
composer = None
found = problems(base, head, tags(), changelog, composer)
for line in found:
print(f"::error::{line}")
if found:
return 1
print(f"{head} -> {base}: follows the development cycle.")
return 0
if __name__ == "__main__":
sys.exit(main())
+82
View File
@@ -0,0 +1,82 @@
#!/usr/bin/env python3
"""PR CI: a pull request must add its row to TOKENS.md.
TOKENS.md holds one row per piece of work: the tokens of the AI model that
went into it and the hours that were worked on it. This check compares the
rows of the pull request with the rows on the branch it goes to, and fails
when the pull request brings no new row. The new rows are printed, so every
pull request shows in its log what it cost.
Exempt, because nobody worked on them: the release pull request of the
pipeline (release/*), the dependency updates (renovate/*), and a pull
request that only carries one long-lived branch into another (production
into staging, staging into production, develop).
Environment (set by the workflow):
BASE_REF the branch the pull request goes to
HEAD_REF the branch the pull request comes from
PR_AUTHOR who opened it
Standard library only.
"""
import os
import subprocess
import sys
LEDGER = "TOKENS.md"
EXEMPT_PREFIXES = ("release/", "renovate/")
EXEMPT_BRANCHES = ("production", "staging", "develop")
EXEMPT_AUTHORS = ("deploy-bot", "renovate-bot")
def rows(text):
"""The rows of the table: the lines that start with a date."""
return [line.strip() for line in text.splitlines() if line.startswith("| 20")]
def git(*args):
return subprocess.run(["git", *args], capture_output=True, text=True)
def main():
base = os.environ.get("BASE_REF", "").strip()
head = os.environ.get("HEAD_REF", "").strip()
author = os.environ.get("PR_AUTHOR", "").strip()
if head.startswith(EXEMPT_PREFIXES) or head in EXEMPT_BRANCHES or author in EXEMPT_AUTHORS:
print(f"No row needed: {head or 'this pull request'} by {author or 'unknown'} is not a piece of work.")
return 0
if not base:
print("BASE_REF is not set: cannot tell which branch this pull request goes to.")
return 1
if not os.path.exists(LEDGER):
print(f"{LEDGER} is missing. See AGENTS.md, 'Token usage and hours'.")
return 1
fetch = git("fetch", "--quiet", "--no-tags", "--depth=1", "origin", base)
if fetch.returncode != 0:
print(f"Could not fetch {base}: {fetch.stderr.strip()}")
return 1
shown = git("show", f"FETCH_HEAD:{LEDGER}")
before = set(rows(shown.stdout)) if shown.returncode == 0 else set()
with open(LEDGER, encoding="utf-8") as handle:
new = [row for row in rows(handle.read()) if row not in before]
if not new:
print(f"This pull request adds no row to {LEDGER}.")
print("Every pull request records what went into it: the tokens of the AI model and the hours.")
print("Add the row with dev/token-usage.py (see AGENTS.md, 'Token usage and hours') and push again.")
return 1
print(f"{len(new)} new row(s) in {LEDGER}:")
for row in new:
print(" " + row)
return 0
if __name__ == "__main__":
sys.exit(main())
+13
View File
@@ -0,0 +1,13 @@
#!/bin/sh
# Installs Trivy at a fixed version, checked against a fixed checksum, so a changed download fails the
# job instead of running. To update: take the version and the checksum of the Linux-64bit tarball from
# https://github.com/aquasecurity/trivy/releases (the checksums file of that release).
set -eu
VERSION=0.77.0
SHA256=c9504e6ff8184b91e8e7266c84ad8538f76347f1e5488e07cb083855883cd9a6
curl -fsSL -o /tmp/trivy.tar.gz "https://github.com/aquasecurity/trivy/releases/download/v${VERSION}/trivy_${VERSION}_Linux-64bit.tar.gz"
echo "${SHA256} /tmp/trivy.tar.gz" | sha256sum -c -
tar -xzf /tmp/trivy.tar.gz -C /usr/local/bin trivy
trivy --version
+49
View File
@@ -0,0 +1,49 @@
#!/usr/bin/env python3
"""Tells Packagist that the package has a new version.
Packagist reads the tags of the repository; this asks it to do that now, instead of waiting for its
own poll. The package must have been submitted on packagist.org once (by hand); until then, and
while PACKAGIST_USERNAME and PACKAGIST_TOKEN are not set, this only says so and succeeds.
Environment: PACKAGIST_USERNAME, PACKAGIST_TOKEN (the API token of the Packagist account, a secret
of the repository), PACKAGE_URL (the public address of the repository).
The token goes in the request and never in the log. Standard library only.
"""
import json
import os
import sys
import urllib.error
import urllib.parse
import urllib.request
USER = os.environ.get("PACKAGIST_USERNAME", "").strip()
TOKEN = os.environ.get("PACKAGIST_TOKEN", "").strip()
PACKAGE_URL = os.environ.get("PACKAGE_URL", "").strip()
def main():
if not (USER and TOKEN):
print("PACKAGIST_USERNAME / PACKAGIST_TOKEN are not set: Packagist was not told. "
"Set both as secrets of the repository once the package is submitted on packagist.org.")
return
if not PACKAGE_URL.startswith("https://"):
sys.exit("PACKAGE_URL must be the public https address of the repository.")
query = urllib.parse.urlencode({"username": USER, "apiToken": TOKEN})
request = urllib.request.Request(
f"https://packagist.org/api/update-package?{query}",
data=json.dumps({"repository": {"url": PACKAGE_URL}}).encode(),
method="POST",
headers={"Content-Type": "application/json"},
)
try:
with urllib.request.urlopen(request, timeout=30) as response:
print(f"Packagist answered {response.status}: it will read the new tag.")
except urllib.error.HTTPError as e:
# Never echo the request (it holds the token); the answer of Packagist says enough.
sys.exit(f"Packagist refused: {e.code} {e.read().decode()[:300]}")
if __name__ == "__main__":
main()
+93
View File
@@ -0,0 +1,93 @@
#!/usr/bin/env python3
"""Removes feature branches that nobody has touched for 30 days.
A branch is removed when all of this is true:
- its name starts with one of PRUNE_PREFIXES (default `feature/,fix/`): production, develop and the
release branches are never touched;
- its last commit is older than PRUNE_DAYS (default 30);
- no pull request from it is open (an open pull request is work in progress, however quiet).
A branch that had a pull request can be brought back from that pull request in Gitea ("Restore branch"),
and a merged one is in its target anyway. DRY_RUN=1 only says what would be removed.
Environment: GT_URL, GT_OWNER, GT_REPO, GT_TOKEN (may delete branches), and optionally PRUNE_DAYS,
PRUNE_PREFIXES, DRY_RUN. Standard library only.
"""
import json
import os
import sys
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime, timedelta, timezone
URL = os.environ.get("GT_URL", "").rstrip("/")
OWNER = os.environ.get("GT_OWNER", "")
REPO = os.environ.get("GT_REPO", "")
TOKEN = os.environ.get("GT_TOKEN", "")
DAYS = int(os.environ.get("PRUNE_DAYS") or 30)
PREFIXES = tuple(p.strip() for p in (os.environ.get("PRUNE_PREFIXES") or "feature/,fix/").split(",") if p.strip())
DRY_RUN = os.environ.get("DRY_RUN", "").strip().lower() in ("1", "true", "yes")
NEVER = ("production", "develop")
def api(method, path):
request = urllib.request.Request(
f"{URL}/api/v1/repos/{OWNER}/{REPO}/{path}",
method=method,
headers={"Authorization": f"token {TOKEN}"},
)
try:
with urllib.request.urlopen(request, timeout=30) as response:
text = response.read().decode()
except urllib.error.HTTPError as e:
sys.exit(f"Gitea API {method} {path} failed: {e.code} {e.read().decode()}")
return json.loads(text) if text else None
def pages(path):
"""Every item of a paged list."""
page, found = 1, []
while True:
items = api("GET", f"{path}{'&' if '?' in path else '?'}page={page}&limit=50") or []
found += items
if len(items) < 50:
return found
page += 1
def stale(branches, open_heads, now):
"""The names to remove, with how many days they were quiet."""
limit = now - timedelta(days=DAYS)
names = []
for branch in branches:
name = branch["name"]
if name in NEVER or name.startswith("release/") or not name.startswith(PREFIXES) or name in open_heads:
continue
moment = datetime.fromisoformat(branch["commit"]["timestamp"].replace("Z", "+00:00"))
if moment < limit:
names.append((name, (now - moment).days))
return names
def main():
if not (URL and OWNER and REPO and TOKEN):
sys.exit("GT_URL, GT_OWNER, GT_REPO and GT_TOKEN are required.")
open_heads = {(pull.get("head") or {}).get("ref") for pull in pages("pulls?state=open")}
old = stale(pages("branches"), open_heads, datetime.now(timezone.utc))
if not old:
print(f"No {'/'.join(p.rstrip('/') for p in PREFIXES)} branch has been quiet for {DAYS} days.")
return
for name, days in old:
if DRY_RUN:
print(f"Would remove {name} (quiet for {days} days).")
else:
api("DELETE", "branches/" + urllib.parse.quote(name, safe=""))
print(f"Removed {name} (quiet for {days} days).")
if __name__ == "__main__":
main()
+100
View File
@@ -0,0 +1,100 @@
#!/usr/bin/env python3
"""Release step of the `Release` workflow: tag what was just merged into production.
A push to production is a release when it is the merge of a `release/vX.Y.Z` pull request. This
finds that version (from the pull request Gitea knows for the commit, or from the merge message),
and makes the release `vX.Y.Z` on that commit, with the changelog section as its text. Gitea
makes the tag; Packagist picks the tag up in the next step.
Runs again on the same commit without harm: a tag that is already there on that commit is fine.
A push that is not a release merge (a hotfix pushed by an admin, say) makes no release and says so.
Environment: GT_URL, GT_OWNER, GT_REPO, GT_TOKEN (may create releases), COMMIT_HASH.
Standard library + git only.
"""
import json
import os
import re
import subprocess
import sys
import urllib.error
import urllib.request
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import semver # noqa: E402
URL = os.environ.get("GT_URL", "").rstrip("/")
OWNER = os.environ.get("GT_OWNER", "")
REPO = os.environ.get("GT_REPO", "")
TOKEN = os.environ.get("GT_TOKEN", "")
COMMIT = os.environ.get("COMMIT_HASH", "").strip()
def api(method, path, body=None, allow=()):
request = urllib.request.Request(
f"{URL}/api/v1/repos/{OWNER}/{REPO}/{path}",
data=json.dumps(body).encode() if body is not None else None,
method=method,
headers={"Authorization": f"token {TOKEN}", "Content-Type": "application/json"},
)
try:
with urllib.request.urlopen(request, timeout=30) as response:
text = response.read().decode()
except urllib.error.HTTPError as e:
if e.code in allow:
return None
sys.exit(f"Gitea API {method} {path} failed: {e.code} {e.read().decode()}")
return json.loads(text) if text else None
def release_branch_of(commit):
"""The release branch whose pull request made this commit, or None."""
pull = api("GET", f"commits/{commit}/pull", allow=(404,))
head = ((pull or {}).get("head") or {}).get("ref", "")
if semver.release_version(head):
return head
# Gitea's own merge message: "Merge pull request 'title' (#7) from release/v1.2.0 into production".
message = subprocess.run(["git", "log", "-1", "--pretty=%s", commit], capture_output=True, text=True).stdout
found = re.search(r"from (release/v\d+\.\d+\.\d+) into production", message)
return found.group(1) if found else None
def main():
if not (URL and OWNER and REPO and TOKEN):
sys.exit("GT_URL, GT_OWNER, GT_REPO and GT_TOKEN are required.")
if not re.fullmatch(r"[0-9a-f]{40}", COMMIT):
sys.exit("COMMIT_HASH must be the full commit hash.")
branch = release_branch_of(COMMIT)
if branch is None:
print(f"{COMMIT[:8]} is not the merge of a release/vX.Y.Z pull request: no release made.")
return
version = semver.release_version(branch)
tag = f"v{semver.text(version)}"
existing = api("GET", f"releases/tags/{tag}", allow=(404,))
if existing:
print(f"{tag} already exists: nothing to do.")
return
changelog = open("CHANGELOG.md", encoding="utf-8").read() if os.path.exists("CHANGELOG.md") else ""
notes = semver.changelog_section(changelog, version)
if notes is None:
sys.exit(f"CHANGELOG.md has no section for {tag}: the release pull request should have been stopped by PR CI.")
api("POST", "releases", {
"tag_name": tag,
"target_commitish": COMMIT,
"name": tag,
"body": notes,
"draft": False,
"prerelease": False,
})
print(f"Released {tag} on {COMMIT[:8]}.")
if __name__ == "__main__":
main()
+44
View File
@@ -0,0 +1,44 @@
"""Version helpers shared by the release scripts. Standard library only."""
import re
# A version is always three numbers: 1.4.0. The tag has a v in front (v1.4.0), the branch is release/v1.4.0.
VERSION = re.compile(r"(\d+)\.(\d+)\.(\d+)")
RELEASE_BRANCH = re.compile(r"release/v(\d+)\.(\d+)\.(\d+)")
TAG = re.compile(r"v(\d+)\.(\d+)\.(\d+)")
def release_version(branch):
"""The version of a `release/vX.Y.Z` branch as a tuple, or None when it is not one."""
match = RELEASE_BRANCH.fullmatch(branch or "")
return tuple(int(part) for part in match.groups()) if match else None
def tag_version(tag):
match = TAG.fullmatch(tag or "")
return tuple(int(part) for part in match.groups()) if match else None
def latest(tags):
"""The highest version among the tags that are versions, or None."""
versions = [version for version in (tag_version(tag) for tag in tags) if version]
return max(versions) if versions else None
def text(version):
return ".".join(str(part) for part in version)
def changelog_section(changelog, version):
"""The body under `## vX.Y.Z` of the changelog, up to the next `## `; None when there is no such heading."""
heading = re.compile(rf"^##\s+v?{re.escape(text(version))}(\s|$)")
lines = changelog.splitlines()
for index, line in enumerate(lines):
if heading.match(line):
body = []
for following in lines[index + 1:]:
if following.startswith("## "):
break
body.append(following)
return "\n".join(body).strip()
return None
+67
View File
@@ -0,0 +1,67 @@
#!/usr/bin/env python3
"""Starts a release: makes the branch release/vX.Y.Z from develop.
Features are pull requests to that branch (they merge by themselves when CI is green). When the release
is ready, a pull request from it to production makes the release.
Environment: GT_URL, GT_OWNER, GT_REPO, GT_TOKEN (may create branches), VERSION (1.4.0, or v1.4.0).
Standard library only.
"""
import json
import os
import re
import sys
import urllib.error
import urllib.request
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import semver # noqa: E402
URL = os.environ.get("GT_URL", "").rstrip("/")
OWNER = os.environ.get("GT_OWNER", "")
REPO = os.environ.get("GT_REPO", "")
TOKEN = os.environ.get("GT_TOKEN", "")
def api(method, path, body=None, allow=()):
request = urllib.request.Request(
f"{URL}/api/v1/repos/{OWNER}/{REPO}/{path}",
data=json.dumps(body).encode() if body is not None else None,
method=method,
headers={"Authorization": f"token {TOKEN}", "Content-Type": "application/json"},
)
try:
with urllib.request.urlopen(request, timeout=30) as response:
text = response.read().decode()
except urllib.error.HTTPError as e:
if e.code in allow:
return None
sys.exit(f"Gitea API {method} {path} failed: {e.code} {e.read().decode()}")
return json.loads(text) if text else None
def main():
if not (URL and OWNER and REPO and TOKEN):
sys.exit("GT_URL, GT_OWNER, GT_REPO and GT_TOKEN are required.")
given = os.environ.get("VERSION", "").strip().lstrip("v")
if not semver.VERSION.fullmatch(given):
sys.exit(f"'{given}' is not a version: use three numbers, like 1.4.0.")
version = tuple(int(part) for part in given.split("."))
tags = [tag["name"] for tag in api("GET", "tags?limit=50") or []]
newest = semver.latest(tags)
if newest is not None and version <= newest:
sys.exit(f"v{given} is not above the latest tag v{semver.text(newest)}.")
name = f"release/v{given}"
if api("GET", f"branches/{name}", allow=(404,)):
sys.exit(f"{name} already exists.")
api("POST", "branches", {"new_branch_name": name, "old_branch_name": "develop"})
print(f"{name} made from develop. Make features as pull requests to it; when it is ready, open one to production.")
if __name__ == "__main__":
main()
+82
View File
@@ -0,0 +1,82 @@
#!/usr/bin/env python3
"""Sync step of the `Release` workflow: merge production into develop.
Runs after a release, so `develop` always contains what is live. Features are made from develop, so
it must be on the latest production before the next release is started.
`develop` takes direct pushes (only `production` and the release branches are protected),
so this is a plain merge and push: fast-forward when possible, otherwise a
merge commit `chore: sync production into develop`.
A conflict fails the step on purpose. The release itself is done by then; the
red build is the signal that `develop` holds something production does not
and needs a merge by hand.
Environment: GT_URL, GT_OWNER, GT_REPO, GT_TOKEN (an access token
that may push to develop), COMMIT_HASH (the commit this job released; defaults
to the tip of production). SYNC_REMOTE overrides the clone URL (local testing).
Standard library + git only.
"""
import json
import os
import re
import subprocess
import tempfile
import urllib.request
URL = os.environ.get("GT_URL", "").rstrip("/")
OWNER = os.environ.get("GT_OWNER", "")
REPO = os.environ.get("GT_REPO", "")
TOKEN = os.environ.get("GT_TOKEN", "")
REMOTE = os.environ.get("SYNC_REMOTE", "")
MESSAGE = "chore: sync production into develop"
def git(repo, *args, check=True):
result = subprocess.run(["git", "-C", repo, *args], capture_output=True, text=True)
if check and result.returncode != 0:
raise SystemExit(f"git {' '.join(args[:2])} failed: {result.stderr.strip()}")
return result
def main():
user = os.environ.get("GT_BOT_USER") or "sync"
remote = REMOTE
if not remote:
if not (URL and OWNER and REPO and TOKEN):
raise SystemExit("GT_URL, GT_OWNER, GT_REPO and GT_TOKEN are required")
remote = f"https://{user}:{TOKEN}@{URL.split('://', 1)[1]}/{OWNER}/{REPO}.git"
repo = os.path.join(tempfile.mkdtemp(), "repo")
result = subprocess.run(["git", "clone", "--quiet", "--branch", "develop", remote, repo],
capture_output=True, text=True)
if result.returncode != 0:
raise SystemExit(f"Could not clone develop: {result.stderr.strip()}")
git(repo, "config", "user.name", user)
git(repo, "config", "user.email", f"{user}@iriks-it.nl")
commit = os.environ.get("COMMIT_HASH", "").strip()
source = commit if re.fullmatch(r"[0-9a-f]{40}", commit) else "origin/production"
short = git(repo, "rev-parse", "--short", source).stdout.strip()
if git(repo, "merge-base", "--is-ancestor", source, "HEAD", check=False).returncode == 0:
print(f"develop already contains production ({short}) — nothing to do.")
return
merge = git(repo, "merge", "--no-edit", "-m", MESSAGE, source, check=False)
if merge.returncode != 0:
conflicts = git(repo, "diff", "--name-only", "--diff-filter=U", check=False).stdout.strip()
raise SystemExit(
f"production ({short}) does not merge cleanly into develop — merge it by hand.\n"
f"Conflicting files:\n{conflicts or merge.stdout.strip() or merge.stderr.strip()}"
)
push = git(repo, "push", "--quiet", "origin", "HEAD:refs/heads/develop", check=False)
if push.returncode != 0:
raise SystemExit(f"Could not push develop: {push.stderr.strip()}")
print(f"develop now contains production ({short}).")
if __name__ == "__main__":
main()
+101
View File
@@ -0,0 +1,101 @@
"""Tests of the release scripts: `python3 -m unittest discover -s .gitea/scripts` (run by the `flow` job)."""
import os
import sys
import unittest
from datetime import datetime, timezone
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import check_flow # noqa: E402
import prune_branches # noqa: E402
import semver # noqa: E402
TAGS = ["v0.1.0", "v0.2.0", "v0.10.0", "not-a-version"]
CHANGELOG = "# Changelog\n\n## v0.11.0 - 2026-12-10\n\n- A feature\n- Another\n\n## v0.10.0 - 2026-12-01\n\n- Older\n"
class Versions(unittest.TestCase):
def test_release_branch(self):
self.assertEqual(semver.release_version("release/v1.2.3"), (1, 2, 3))
for wrong in ("release/1.2.3", "release/v1.2", "feature/x", "release/v1.2.3-rc1", "", None):
self.assertIsNone(semver.release_version(wrong))
def test_latest_is_numeric_not_alphabetical(self):
self.assertEqual(semver.latest(TAGS), (0, 10, 0))
self.assertIsNone(semver.latest(["x"]))
def test_changelog_section(self):
self.assertEqual(semver.changelog_section(CHANGELOG, (0, 11, 0)), "- A feature\n- Another")
self.assertEqual(semver.changelog_section(CHANGELOG, (0, 10, 0)), "- Older")
self.assertIsNone(semver.changelog_section(CHANGELOG, (0, 1, 0)))
self.assertIsNone(semver.changelog_section(CHANGELOG, (0, 1, 1)))
class Flow(unittest.TestCase):
def check(self, base, head, tags=TAGS, changelog=CHANGELOG, composer=None):
return check_flow.problems(base, head, tags, changelog, composer or {"name": "x/y"})
def test_release_to_production(self):
self.assertEqual(self.check("production", "release/v0.11.0"), [])
def test_production_only_from_a_release_branch(self):
self.assertTrue(self.check("production", "feature/x"))
self.assertTrue(self.check("production", "develop"))
def test_release_must_be_above_the_latest_tag(self):
self.assertTrue(self.check("production", "release/v0.10.0"))
self.assertTrue(self.check("production", "release/v0.9.0"))
def test_release_needs_its_changelog_section(self):
self.assertTrue(self.check("production", "release/v0.12.0"))
self.assertTrue(self.check("production", "release/v0.11.0", changelog=None))
def test_composer_json_has_no_version(self):
self.assertTrue(self.check("production", "release/v0.11.0", composer={"version": "0.11.0"}))
def test_features_into_an_open_release_branch(self):
self.assertEqual(self.check("release/v0.11.0", "feature/x"), [])
self.assertEqual(self.check("release/v0.11.0", "fix/y"), [])
def test_nothing_into_a_release_that_is_out(self):
self.assertTrue(self.check("release/v0.10.0", "feature/x"))
def test_a_release_branch_takes_no_long_lived_branch(self):
for head in ("production", "develop", "release/v0.12.0"):
self.assertTrue(self.check("release/v0.11.0", head))
def test_nothing_goes_to_develop_or_anything_else(self):
self.assertTrue(self.check("develop", "feature/x"))
self.assertTrue(self.check("main", "feature/x"))
def test_first_release_without_tags(self):
self.assertEqual(self.check("production", "release/v0.1.0", tags=[], changelog="## v0.1.0 - x\n\n- a\n"), [])
class Prune(unittest.TestCase):
NOW = datetime(2026, 12, 4, tzinfo=timezone.utc)
def branch(self, name, day):
return {"name": name, "commit": {"timestamp": f"{day}T10:00:00Z"}}
def names(self, branches, open_heads=()):
return [name for name, _ in prune_branches.stale(branches, set(open_heads), self.NOW)]
def test_removes_only_quiet_feature_and_fix_branches(self):
branches = [
self.branch("feature/old", "2026-10-01"), self.branch("fix/old", "2026-11-01"),
self.branch("feature/new", "2026-11-20"), self.branch("feature/edge", "2026-11-05"),
]
self.assertEqual(self.names(branches), ["feature/old", "fix/old"])
def test_never_removes_the_long_lived_branches(self):
old = "2025-01-01"
branches = [self.branch(n, old) for n in ("production", "develop", "release/v0.1.0", "renovate/x", "other")]
self.assertEqual(self.names(branches), [])
def test_keeps_a_branch_with_an_open_pull_request(self):
self.assertEqual(self.names([self.branch("feature/old", "2026-01-01")], open_heads=["feature/old"]), [])
if __name__ == "__main__":
unittest.main()
+163 -8
View File
@@ -1,18 +1,173 @@
name: PR CI name: PR CI
# Pull requests go to a release branch (features) or to production (the release). develop only takes
# the sync after a release. See README.md, "Development cycle".
on: on:
pull_request: pull_request:
branches: [production, staging] branches: ['release/**', production]
env:
COMPOSER_NO_INTERACTION: '1'
jobs: jobs:
pr-ci: # Does the pull request follow the cycle: right branches, a version above the latest tag, a changelog
# section for a release.
flow:
runs-on: docker runs-on: docker
container: container:
image: webdevops/php:8.4 image: webdevops/php:8.4
steps: steps:
- uses: actions/checkout@v4 - name: checkout
- run: composer validate uses: actions/checkout@v4
- run: composer install --no-interaction --prefer-dist with:
- run: vendor/bin/pint --test fetch-depth: 0
- run: vendor/bin/pest
- run: composer audit - name: tests of the release scripts
run: python3 -m unittest discover -s .gitea/scripts
- name: development cycle
run: |
git config --global --add safe.directory "$(pwd)"
python3 .gitea/scripts/check_flow.py
env:
BASE_REF: ${{ github.base_ref }}
HEAD_REF: ${{ github.head_ref }}
# Every piece of work records its tokens and hours (TOKENS.md). Exempt: release/*, renovate/*, bots.
ledger:
runs-on: docker
container:
image: webdevops/php:8.4
steps:
- name: checkout
uses: actions/checkout@v4
- name: token ledger updated
run: |
git config --global --add safe.directory "$(pwd)"
python3 .gitea/scripts/check_tokens.py
env:
BASE_REF: ${{ github.base_ref }}
HEAD_REF: ${{ github.head_ref }}
PR_AUTHOR: ${{ github.event.pull_request.user.login }}
# Style and tests, with the newest dependencies the constraints allow and with the oldest: a package
# has to work for everyone in between.
test:
runs-on: docker
container:
image: webdevops/php:8.4
strategy:
fail-fast: false
matrix:
dependencies: [stable, lowest]
steps:
- name: checkout
uses: actions/checkout@v4
- name: cache composer downloads
uses: actions/cache@v4
with:
path: ~/.composer/cache
key: composer-${{ matrix.dependencies }}-${{ hashFiles('composer.json') }}
restore-keys: |
composer-${{ matrix.dependencies }}-
- name: composer validate
run: composer validate --strict --no-check-lock
- name: install dependencies (${{ matrix.dependencies }})
env:
COMPOSER_MAX_PARALLEL_HTTP: '4'
run: |
flags="--prefer-stable --prefer-dist"
[ "${{ matrix.dependencies }}" = "lowest" ] && flags="--prefer-lowest $flags"
for attempt in 1 2 3; do
composer update $flags && exit 0
echo "composer failed (attempt $attempt of 3), trying again" >&2
sleep $((attempt * 10))
done
exit 1
- name: lint (pint)
if: matrix.dependencies == 'stable'
run: vendor/bin/pint --test
- name: pest tests
run: vendor/bin/pest
# Known vulnerabilities in the dependencies, and secrets or bad settings in the repository.
security:
runs-on: docker
container:
image: webdevops/php:8.4
steps:
- name: checkout
uses: actions/checkout@v4
- name: cache composer downloads
uses: actions/cache@v4
with:
path: ~/.composer/cache
key: composer-security-${{ hashFiles('composer.json') }}
restore-keys: |
composer-security-
- name: install dependencies
env:
COMPOSER_MAX_PARALLEL_HTTP: '4'
run: |
for attempt in 1 2 3; do
composer update --prefer-stable --prefer-dist --no-scripts && exit 0
echo "composer failed (attempt $attempt of 3), trying again" >&2
sleep $((attempt * 10))
done
exit 1
- name: composer audit
run: composer audit
- name: install trivy
run: .gitea/scripts/install-trivy.sh
# Fails on HIGH and CRITICAL. vendor/ is left out of the secret and settings scan (it is other
# people's code); the lock file made above is what the vulnerability scan reads.
- name: trivy
run: |
trivy fs --no-progress --scanners vuln,secret,misconfig --severity HIGH,CRITICAL --exit-code 1 --skip-dirs vendor .
# Pull requests to a release branch merge by themselves when the check below is green.
# Every job that checks out runs in an image with git: without git the checkout is the archive of the
# repository, which leaves out what .gitattributes export-ignores (.gitea/ with these scripts).
release-automerge:
runs-on: docker
needs: pr-ci
if: startsWith(github.base_ref, 'release/') && needs.pr-ci.result == 'success'
container:
image: webdevops/php:8.4
steps:
- name: checkout
uses: actions/checkout@v4
- name: enable auto-merge
run: python3 .gitea/scripts/auto_merge.py
env:
GT_URL: https://git.iriks.casa
GT_OWNER: iriks-it
GT_REPO: laravel-manager
GT_TOKEN: ${{ secrets.DEPLOY_TOKEN }}
PULL_REQUEST_NUMBER: ${{ github.event.pull_request.number }}
# The one check the branch protection asks for (`PR CI / pr-ci (pull_request)`): green only when
# every job above is. Do not rename it without changing the protection rule.
pr-ci:
runs-on: docker
needs: [flow, ledger, test, security]
if: always()
container:
image: alpine:3.20
steps:
- name: all checks green
run: |
echo "flow=${{ needs.flow.result }} ledger=${{ needs.ledger.result }} test=${{ needs.test.result }} security=${{ needs.security.result }}"
[ "${{ needs.flow.result }}" = "success" ] && [ "${{ needs.ledger.result }}" = "success" ] && [ "${{ needs.test.result }}" = "success" ] && [ "${{ needs.security.result }}" = "success" ]
+30
View File
@@ -0,0 +1,30 @@
name: Prune branches
# Every night: remove feature/* and fix/* branches that nobody touched for 30 days and that have no
# open pull request. production, develop and the release branches are never removed.
on:
schedule:
- cron: '15 4 * * *'
workflow_dispatch:
inputs:
dry_run:
description: 'Only say what would be removed (1) or remove it (0)'
default: '1'
jobs:
prune:
runs-on: docker
container:
image: webdevops/php:8.4
steps:
- name: checkout
uses: actions/checkout@v4
- name: remove quiet branches
run: python3 .gitea/scripts/prune_branches.py
env:
GT_URL: https://git.iriks.casa
GT_OWNER: iriks-it
GT_REPO: laravel-manager
GT_TOKEN: ${{ secrets.DEPLOY_TOKEN }}
DRY_RUN: ${{ inputs.dry_run }}
+106
View File
@@ -0,0 +1,106 @@
name: Release
# A push to production is the merge of a release pull request. Check it once more, tag it, tell
# Packagist, and bring develop up to date, so the next features start from what was released.
on:
push:
branches: [production]
concurrency:
group: release
cancel-in-progress: false
jobs:
verify:
runs-on: docker
container:
image: webdevops/php:8.4
steps:
- name: checkout
uses: actions/checkout@v4
- name: cache composer downloads
uses: actions/cache@v4
with:
path: ~/.composer/cache
key: composer-release-${{ hashFiles('composer.json') }}
restore-keys: |
composer-release-
- name: install dependencies
env:
COMPOSER_MAX_PARALLEL_HTTP: '4'
run: |
for attempt in 1 2 3; do
composer update --prefer-stable --prefer-dist && exit 0
echo "composer failed (attempt $attempt of 3), trying again" >&2
sleep $((attempt * 10))
done
exit 1
- name: pest tests
run: vendor/bin/pest
- name: composer audit
run: composer audit
tag:
runs-on: docker
needs: verify
container:
image: webdevops/php:8.4
steps:
- name: checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: release
run: |
git config --global --add safe.directory "$(pwd)"
python3 .gitea/scripts/release.py
env:
GT_URL: https://git.iriks.casa
GT_OWNER: iriks-it
GT_REPO: laravel-manager
GT_TOKEN: ${{ secrets.DEPLOY_TOKEN }}
COMMIT_HASH: ${{ github.sha }}
# Needs the secrets PACKAGIST_USERNAME and PACKAGIST_TOKEN on the repository, and the package
# submitted on packagist.org once. Without them this step only says so.
packagist:
runs-on: docker
needs: tag
container:
image: webdevops/php:8.4
steps:
- name: checkout
uses: actions/checkout@v4
- name: tell Packagist
run: python3 .gitea/scripts/packagist.py
env:
PACKAGIST_USERNAME: ${{ secrets.PACKAGIST_USERNAME }}
PACKAGIST_TOKEN: ${{ secrets.PACKAGIST_TOKEN }}
PACKAGE_URL: https://git.iriks.casa/iriks-it/laravel-manager
# Last: merge what was released into develop. Runs even when Packagist could not be told.
sync-develop:
runs-on: docker
needs: [tag, packagist]
if: always() && needs.tag.result == 'success'
container:
image: webdevops/php:8.4
steps:
- name: checkout
uses: actions/checkout@v4
- name: sync develop
run: python3 .gitea/scripts/sync_develop.py
env:
GT_URL: https://git.iriks.casa
GT_OWNER: iriks-it
GT_REPO: laravel-manager
GT_TOKEN: ${{ secrets.DEPLOY_TOKEN }}
GT_BOT_USER: deploy-bot
COMMIT_HASH: ${{ github.sha }}
+48
View File
@@ -0,0 +1,48 @@
name: Scheduled checks
# What was released does not stay safe: new vulnerabilities are found in old dependencies. Every
# Monday the released code is checked again; a red run is the signal.
on:
schedule:
- cron: '30 5 * * 1'
workflow_dispatch:
jobs:
audit:
runs-on: docker
container:
image: webdevops/php:8.4
steps:
- name: checkout production
uses: actions/checkout@v4
with:
ref: production
- name: cache composer downloads
uses: actions/cache@v4
with:
path: ~/.composer/cache
key: composer-scheduled-${{ hashFiles('composer.json') }}
restore-keys: |
composer-scheduled-
- name: install dependencies
env:
COMPOSER_MAX_PARALLEL_HTTP: '4'
run: |
for attempt in 1 2 3; do
composer update --prefer-stable --prefer-dist --no-scripts && exit 0
echo "composer failed (attempt $attempt of 3), trying again" >&2
sleep $((attempt * 10))
done
exit 1
- name: composer audit
run: composer audit
- name: install trivy
run: .gitea/scripts/install-trivy.sh
- name: trivy
run: |
trivy fs --no-progress --scanners vuln,secret,misconfig --severity HIGH,CRITICAL --exit-code 1 --skip-dirs vendor .
+27
View File
@@ -0,0 +1,27 @@
name: Start release
# By hand (Actions → Start release → Run workflow): makes release/vX.Y.Z from develop.
on:
workflow_dispatch:
inputs:
version:
description: 'Version of the release, like 0.2.0'
required: true
jobs:
start:
runs-on: docker
container:
image: webdevops/php:8.4
steps:
- name: checkout
uses: actions/checkout@v4
- name: make the release branch
run: python3 .gitea/scripts/start_release.py
env:
GT_URL: https://git.iriks.casa
GT_OWNER: iriks-it
GT_REPO: laravel-manager
GT_TOKEN: ${{ secrets.DEPLOY_TOKEN }}
VERSION: ${{ inputs.version }}
+1
View File
@@ -2,3 +2,4 @@ vendor/
composer.lock composer.lock
.phpunit.result.cache .phpunit.result.cache
.env .env
__pycache__/
+2 -2
View File
@@ -9,8 +9,8 @@ between lil-koneko.com, CarsHub, iriks-it.nl and bouwbedrijf.iriks-it.nl, as one
- Core modules (users, media) are on by default; the rest is off or on per `config/manager.php`. - Core modules (users, media) are on by default; the rest is off or on per `config/manager.php`.
- Nothing site-specific in the package. A site's own part is its own module class. - Nothing site-specific in the package. A site's own part is its own module class.
- Tests: `composer test` (Pest + Testbench); style: `composer lint` (Pint). - Tests: `composer test` (Pest + Testbench); style: `composer lint` (Pint).
- Branches: `production` is main, work on `feature/…` from `develop`; I never merge to `production`. - Branches: `production` is what is released, `develop` is production plus nothing (the sync), `release/vX.Y.Z` collects the features of a release. Work on `feature/…` or `fix/…` from `develop` and open the pull request to the **release branch**; never to `develop` or `production`. A release is a pull request from the release branch to `production`, merged by hand: never by me. See the README, "Development cycle".
- No mention of an AI in commits or PRs. Keep a row per piece of work in `TOKENS.md` (`dev/token-usage.py`). - No mention of an AI in commits or PRs. Keep a row per piece of work in `TOKENS.md` (`dev/token-usage.py`; helper agents are counted in the row, one row per model).
## Open decisions ## Open decisions
+17
View File
@@ -0,0 +1,17 @@
# Changelog
Every release has a section here, named after its version (for example `v0.1.0 - 2026-12-04`, as a second-level
heading). The release pull request to `production` is stopped by PR CI when its section is missing, and the text of
the section is the text of the release in Gitea.
## v0.1.0 - 2026-12-04
First version.
- The module registry, with a switch per part of the manager. A part that is off has no routes, tables, menu
item or permissions.
- Users: accounts, groups and permissions (a permission can need another), and `manager:create-user`.
- Media: the library on a Laravel disk and the public file route `/media-files/{id}/{name}/view`.
- Posts: drafts, scheduling, Markdown, categories and tags.
- MIT license; the development cycle with release branches, tags and Packagist, and CI with tests, `composer audit`
and Trivy.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Iriks IT
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+36
View File
@@ -89,3 +89,39 @@ The answers of every action are JSON, in the shape the screens of bouwbedrijf.ir
Inertia props. The screens themselves are not in the package yet: the frontend is an open decision Inertia props. The screens themselves are not in the package yet: the frontend is an open decision
(`AGENTS.md`). Pages and reviews are still skeletons (a list), and login, profile, the audit log and revisions are not (`AGENTS.md`). Pages and reviews are still skeletons (a list), and login, profile, the audit log and revisions are not
ported yet. ported yet.
## Development cycle
```
develop ── feature/*, fix/* ──► release/vX.Y.Z ──► production ──► tag vX.Y.Z ──► Packagist
▲ (pull request, (collects the (pull request, │
│ merges by itself) features) merged by hand) │
└──────────────────────── sync: production into develop ◄─────────────────────────┘
```
1. **Start a release:** Actions → *Start release* → version (`0.2.0`). That makes `release/v0.2.0` from `develop`.
2. **Features:** branch `feature/…` or `fix/…` from `develop`, open a pull request to the release branch. It
merges by itself when *PR CI* is green. Every pull request adds its row to `TOKENS.md`.
3. **Ready:** add a section `## v0.2.0 - date` to `CHANGELOG.md` and open a pull request from the release branch
to `production`. A person merges it.
4. **Release (automatic, on the merge):** tests and audit once more, the tag `v0.2.0` and a Gitea release with the
changelog text, Packagist is told, and `production` is merged into `develop`.
Nobody opens a pull request to `develop`, and `production` and the release branches take no direct pushes.
| When | What runs |
|---|---|
| Pull request to a release branch or to production | *flow* (right branches, version above the latest tag, changelog section, tests of these scripts), *ledger* (`TOKENS.md`), *test* (Pint, Pest with the newest and the oldest dependencies, `composer validate`), *security* (`composer audit`, Trivy on the dependencies, secrets and settings). The check `PR CI / pr-ci` is green when all are. |
| Push to production | verify (Pest, audit), tag and release, Packagist, sync develop |
| Every Monday | `composer audit` and Trivy on production |
| Every night | *Prune branches*: removes `feature/*` and `fix/*` branches whose last commit is over 30 days old and that have no open pull request (a branch of a pull request can be restored from it in Gitea) |
Secrets of the repository for this: `DEPLOY_TOKEN` (the organisation has it), and `PACKAGIST_USERNAME` and
`PACKAGIST_TOKEN` once the package is submitted on packagist.org (until then that step only says so).
## What Composer installs
`.gitattributes` leaves what only belongs to the repository out of the package (`export-ignore`): `.gitea/`,
`dev/`, `scripts/`, `tests/`, `TOKENS.md`, `AGENTS.md`, `phpunit.xml` and the dotfiles. They stay in the repository.
Packagist builds the archive from `git archive`, so what a site installs is `src/`, `config/`, `routes/`,
`resources/`, `composer.json`, `README.md` and `CHANGELOG.md`. Check it with `git archive HEAD | tar -t`.
+7
View File
@@ -6,3 +6,10 @@ Per stuk werk een rij; zie `dev/token-usage.py`.
|---|---|---|---|---:|---:|---:|---:|---:|---:| |---|---|---|---|---:|---:|---:|---:|---:|---:|
| 2026-12-04 | Eerste opzet van het pakket: modules, schakelaars, rechten. Gebruikers en media uit bouwbedrijf overgezet | - | claude-sonnet-5-5 | 34 | 57.433 | 76 | 131.194 | 3.225.205 | 0,18 | | 2026-12-04 | Eerste opzet van het pakket: modules, schakelaars, rechten. Gebruikers en media uit bouwbedrijf overgezet | - | claude-sonnet-5-5 | 34 | 57.433 | 76 | 131.194 | 3.225.205 | 0,18 |
| 2026-12-04 | Posts overgezet: berichten met concepten, inplannen, categorieën en tags | - | claude-sonnet-5-5 | 9 | 19.897 | 20 | 35.420 | 1.584.858 | 0,03 | | 2026-12-04 | Posts overgezet: berichten met concepten, inplannen, categorieën en tags | - | claude-sonnet-5-5 | 9 | 19.897 | 20 | 35.420 | 1.584.858 | 0,03 |
| 2026-12-04 | Token-script telt de tokens van helper-agents mee in de rij, per model | - | claude-sonnet-5-5 | 16 | 27.013 | 36 | 45.155 | 2.982.056 | 0,06 |
| 2026-12-04 | CI en releaseproces opgezet: releasebranch, tag, Packagist, sync naar develop, tests, audit en Trivy | - | claude-sonnet-5-5 | 14 | 31.242 | 30 | 48.735 | 3.520.606 | 0,09 |
| 2026-12-04 | Opstart van de release gerepareerd en oude featurebranches na 30 dagen automatisch opruimen | - | claude-sonnet-5-5 | 14 | 14.499 | 32 | 14.175 | 4.138.947 | 0,08 |
| 2026-12-04 | De eerste release gestart en het LICENSE-bestand (MIT) toegevoegd voor Packagist | - | claude-sonnet-5-5 | 13 | 14.884 | 32 | 14.810 | 3.953.265 | 0,07 |
| 2026-12-04 | Changelog van de eerste release ingevuld en de release klaargezet | - | claude-sonnet-5-5 | 8 | 7.421 | 16 | 15.226 | 2.534.041 | 0,02 |
| 2026-12-04 | De changelog van de eerste release hersteld, de kop stond verkeerd | - | claude-sonnet-5-5 | 5 | 3.535 | 10 | 6.917 | 1.656.465 | 0,03 |
| 2026-12-04 | Composer-cache en herhaalpogingen in alle CI-jobs, zodat haperende downloads de pipeline niet meer breken | - | claude-sonnet-5-5 | 74 | 80.637 | 164 | 167.489 | 21.208.458 | 0,65 |
+38 -20
View File
@@ -4,14 +4,18 @@
Usage: dev/token-usage.py LOG.jsonl [--since 2026-12-02T07:00] [--until 2026-12-02T12:00] Usage: dev/token-usage.py LOG.jsonl [--since 2026-12-02T07:00] [--until 2026-12-02T12:00]
[--row "Wat er is gemaakt" [--version v0.2.0]] [--row "Wat er is gemaakt" [--version v0.2.0]]
With --row it also prints the line for the table of TOKENS.md, with the hours as its last cell. With --row it also prints the line(s) for the table of TOKENS.md, with the hours as the last cell.
Helper agents (subagents) are part of the work: their tokens are added to the row. The row is made
per model, because the price differs per model: when helper agents ran on another model than the
session, there is one row for each, and the hours are on the first row only.
The hours are the time that was worked in the period: from one entry of the log to the next, The hours are the time that was worked in the period: from one entry of the log to the next,
the time between an answer and the next request included, pauses of more than half an hour the time between an answer and the next request included, pauses of more than half an hour
left out. left out.
LOG.jsonl is the log of the session (~/.claude/projects/<folder>/<session>.jsonl); the logs of LOG.jsonl is the log of the session (~/.claude/projects/<folder>/<session>.jsonl); the logs of
helper agents in the folder `<session>/subagents` next to it are counted separately. The moments helper agents in the folder `<session>/subagents` next to it are shown separately and also counted in the row. The moments
are UTC, as in the log. An answer of the model can be in the log more than once; it is counted are UTC, as in the log. An answer of the model can be in the log more than once; it is counted
once, by its message id. once, by its message id.
@@ -70,20 +74,28 @@ def hours(path, since, until):
def total(found, since, until): def total(found, since, until):
"""Steps, output, input, written to the cache, read from the cache; and the models seen.""" """Steps, output, input, written to the cache, read from the cache; and the same per model."""
row = [0, 0, 0, 0, 0] row = [0, 0, 0, 0, 0]
models = {} per_model = {}
for usage, moment, model in found.values(): for usage, moment, model in found.values():
if (since and moment[:16] < since) or (until and moment[:16] >= until): if (since and moment[:16] < since) or (until and moment[:16] >= until):
continue continue
row[0] += 1 # Entries the client made itself (model "<synthetic>") hold no tokens and no work.
row[1] += usage.get("output_tokens", 0) if model and model.startswith("<"):
row[2] += usage.get("input_tokens", 0) continue
row[3] += usage.get("cache_creation_input_tokens", 0) add = [
row[4] += usage.get("cache_read_input_tokens", 0) 1,
if model and not model.startswith("<"): usage.get("output_tokens", 0),
models[model] = models.get(model, 0) + 1 usage.get("input_tokens", 0),
return row, models usage.get("cache_creation_input_tokens", 0),
usage.get("cache_read_input_tokens", 0),
]
model = model or "?"
mine = per_model.setdefault(model, [0, 0, 0, 0, 0])
for index, value in enumerate(add):
row[index] += value
mine[index] += value
return row, per_model
def number(value): def number(value):
@@ -105,9 +117,11 @@ def main():
if len(paths) != 1: if len(paths) != 1:
sys.exit(__doc__) sys.exit(__doc__)
row, models = total(answers(paths[0]), since, until) session = answers(paths[0])
row, _ = total(session, since, until)
show("session", row) show("session", row)
print(f"hours worked: {hours(paths[0], since, until):.2f}") worked_hours = hours(paths[0], since, until)
print(f"hours worked: {worked_hours:.2f}")
helpers = {} helpers = {}
for path in glob.glob(os.path.join(os.path.splitext(paths[0])[0], "subagents", "*.jsonl")): for path in glob.glob(os.path.join(os.path.splitext(paths[0])[0], "subagents", "*.jsonl")):
@@ -116,13 +130,17 @@ def main():
show("helper agents", total(helpers, since, until)[0]) show("helper agents", total(helpers, since, until)[0])
if option("--row"): if option("--row"):
if len(models) > 1: # Session and helper agents together, one row per model.
print("More than one model in this period: make a row per model (--since/--until).", file=sys.stderr) everything = {**session, **{"helper:" + key: value for key, value in helpers.items()}}
model = max(models, key=models.get) if models else "?" _, per_model = total(everything, since, until)
if not per_model:
per_model = {"?": [0, 0, 0, 0, 0]}
day = (since or "")[:10] or "JJJJ-MM-DD" day = (since or "")[:10] or "JJJJ-MM-DD"
worked = f"{hours(paths[0], since, until):.2f}".replace(".", ",") # The model with the most steps first; the hours go on that row only.
cells = [day, option("--row"), option("--version") or "", model] + [number(value) for value in row] + [worked] for position, model in enumerate(sorted(per_model, key=lambda name: -per_model[name][0])):
print("| " + " | ".join(cells) + " |") worked = f"{worked_hours:.2f}" if position == 0 else "0.00"
cells = [day, option("--row"), option("--version") or "", model] + [number(value) for value in per_model[model]] + [worked.replace(".", ",")]
print("| " + " | ".join(cells) + " |")
if __name__ == "__main__": if __name__ == "__main__":