diff --git a/.github/PULL_REQUEST_TEMPLATE/knowledge-sync.md b/.github/PULL_REQUEST_TEMPLATE/knowledge-sync.md index 66c80ff..19b28ac 100644 --- a/.github/PULL_REQUEST_TEMPLATE/knowledge-sync.md +++ b/.github/PULL_REQUEST_TEMPLATE/knowledge-sync.md @@ -1,10 +1,6 @@ - + ## Reviewer checklist -- [ ] The diff touches only the sidecar's copies, the site's copies, `.lokf/pyproject.toml`, `.lokf/uv.lock` and `CHANGELOG.md`. -- [ ] `.lokf/pyproject.toml` changes on the `ktl` line alone, to the release, and `.lokf/uv.lock` on the `ktl` entry alone. -- [ ] Any workflow changes held above are read and applied on this branch, or left for the next sync on purpose. -- [ ] You read the [release notes of Knowledge Trust Ladder](https://w3id.org/ktl/changelog/) for a step the sync cannot do, such as setting a new variable or secret. If there is one, you do it in this pull request or straight after the merge. -- [ ] Where the gate fails on a convention the release adds or tightens, such as rule 16's one `excerpt` for each source `id`, the bundle is fixed through the pen in a pull request of its own, and this one runs again once that merges. -- [ ] `CHANGELOG.md` has the entry under `## [Unreleased]` and `### Security`, and the title carries `security(sidecar):`, so the merge releases. +- [ ] The diff changes only the sidecar's copies, the site's copies, the `ktl` pin and its lock, and `CHANGELOG.md`. +- [ ] Any workflow changes held above are read and applied on this branch. diff --git a/.github/workflows/knowledge-release.yaml b/.github/workflows/knowledge-release.yaml index 668303c..550295c 100644 --- a/.github/workflows/knowledge-release.yaml +++ b/.github/workflows/knowledge-release.yaml @@ -86,6 +86,14 @@ jobs: with: egress-policy: audit + # The input is held to the shape of a tag before anything names a ref by it. + - name: Check the tag is a release tag + run: | + if [[ ! "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + echo "::error::'$TAG' is not vMAJOR.MINOR.PATCH." + exit 1 + fi + # The bundle as it stood at the tag, not at the branch head. - name: Checkout uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -643,5 +651,11 @@ jobs: GH_REPO: ${{ github.repository }} run: | shopt -s nullglob - gh release upload "$TAG" ./*.zip ./*.yaml ./*.tsv ./*.sha256 ./*.intoto.jsonl --clobber + # gh retries a slow upload itself, and a retry of one that reached + # GitHub fails with "already exists"; --clobber makes a new attempt safe. + for attempt in 1 2 3; do + gh release upload "$TAG" ./*.zip ./*.yaml ./*.tsv ./*.sha256 ./*.intoto.jsonl --clobber && exit 0 + [ "$attempt" = 3 ] || { echo "::warning::The upload to $TAG failed (attempt $attempt); trying again."; sleep 15; } + done + exit 1 working-directory: ${{ runner.temp }}/release diff --git a/.github/workflows/knowledge-sync.yaml b/.github/workflows/knowledge-sync.yaml index 7929478..ad59eb0 100644 --- a/.github/workflows/knowledge-sync.yaml +++ b/.github/workflows/knowledge-sync.yaml @@ -1,7 +1,7 @@ name: Knowledge sync # Keeps this host's sidecar copies and skills pin at the newest release of -# Knowledge Trust Ladder. Each week it reads the ktl pin in +# Knowledge Trust Ladder. Each day it reads the ktl pin in # .lokf/pyproject.toml and asks this host's package index for the newest ktl. # When the pin is behind, the host's own .lokf/scripts/knowledge-sync.sh # moves the pin, relocks, reads the release's manifest and templates from the @@ -10,54 +10,55 @@ name: Knowledge sync # or release code, and changes the default branch only through that pull # request. # +# This file holds only the triggers, each job's permissions, Environment +# and secrets, and the actions. The steps' logic is in the script +# (`--workflow `), so a fix to it reaches a host in its next sync pull +# request, and this file seldom changes. +# # One pull request at a time, refreshed until it is merged. The pull request # comes from this workflow's own branch, knowledge-sync. While it is open, a # later run that finds a newer release replaces the branch's commits with a -# sync to that release, and sets the title and body to match, so the week's -# releases fold into one pull request. A pull request a person added a commit -# to is left alone, and so is the branch when it holds a commit of a -# person's and no pull request. A tag whose pull request a person closed without merging -# is not proposed again by the schedule. A run a person starts from the -# Actions tab may name a tag, and goes ahead in every case but one: a pull -# request that proposes that tag and is still open. +# sync to that release, and sets the title and body to match. A pull request +# a person added a commit to is left alone, and so is the branch when it +# holds a commit of a person's and no pull request. A tag whose pull request +# a person closed without merging is not proposed again by the schedule. A +# run a person starts from the Actions tab may name a tag, and goes ahead in +# every case but one: a pull request that proposes that tag and is still +# open. # -# Three jobs, for least privilege, and two more a host may turn on. -# `earlier` reads the pin, the newest release and the state of this -# workflow's branch and last pull request, with a token that reads the -# repository and its pull requests. `sync` runs the host's sync script with -# a read-only token and no git credentials on disk, and hands the change to -# `publish` as a patch artifact. Both run in the knowledge-sync Environment -# for one thing: the credential of a private index, the secrets +# Three jobs, for least privilege. `earlier` reads the pin, the newest +# release and the state of this workflow's branch and last pull request, +# with a token that reads the repository and its pull requests. `sync` runs +# the sync with a read-only token and no git credentials on disk, and hands +# the change to `publish` as a patch artifact. Both run in the knowledge-sync +# Environment for one thing: the credential of a private index, the secrets # UV_INDEX_KNOWLEDGE_USERNAME and UV_INDEX_KNOWLEDGE_PASSWORD. # -# `publish` puts the patch on with the default branch's copy of the script -# (--apply), which checks its paths and pin, checks the lock against the -# index, and keeps every workflow as it is here. It writes the pull -# request's body from that patch, and opens or refreshes the pull request. -# The pull request's own checks run the synced scripts and site files with a -# read-only token, as they run on any change here. +# `publish` puts the patch on with the default branch's copy of the script, +# which checks its paths and pin, checks the lock against the index, and +# keeps every workflow as it is here. It writes the pull request's body from +# that patch, and opens or refreshes the pull request. The pull request's own +# checks run the synced scripts and site files with a read-only token, as +# they run on any change here. # # The workflow changes a release brings are held, not pushed. A workflow on # a branch pushed with a token runs on that push, can read every repository -# secret, and can raise its own token with a permissions: key. So the -# pushed branch carries no workflow the release wrote. The held changes are -# attached to the run as `knowledge-sync-workflows`, shown in the pull -# request, and applied by a person who has read them. Or, with the -# repository variable KNOWLEDGE_SYNC_REVIEW_ENVIRONMENT naming an -# Environment with required reviewers, `review` waits for one of them and -# `push-workflows` then pushes the changes as a second commit. +# secret, and can raise its own token with a permissions: key. So the pushed +# branch carries no workflow the release wrote. The held changes are attached +# to the run as `knowledge-sync-workflows` and shown in the pull request, and +# a person who has read them applies them. # # `publish` pushes and opens the pull request with the KNOWLEDGE_SYNC_TOKEN -# secret, since a pull request opened with GITHUB_TOKEN starts no checks, -# and `push-workflows` pushes approved workflow changes with it. The secret -# is a fine-grained personal access token for this repository alone, with -# Contents, Pull requests and Workflows set to read and write, or a GitHub -# App's installation token made in a step of your own. Keep it in the knowledge-sync Environment, limited to the default -# branch, so no workflow on another branch can read it; a repository secret -# of that name still works, with no such limit. Without the secret the -# workflow still runs: it attaches the patch to the run, writes the summary, -# and opens nothing. The sidecar's -# references/automation.md says how to set the token and the Environments up. +# secret, since a pull request opened with GITHUB_TOKEN starts no checks. The +# secret is a fine-grained personal access token for this repository alone, +# with Contents, Pull requests and Workflows set to read and write, or a +# GitHub App's installation token made in a step of your own. Keep it in the +# knowledge-sync Environment, limited to the default branch, so no workflow +# on another branch can read it; a repository secret of that name still +# works, with no such limit. Without the secret the workflow still runs: it +# attaches the patch to the run, writes the summary, and opens nothing. The +# sidecar's references/automation.md says how to set the token and the +# Environment up. # # SECURITY SCANNER NOTE. No LLM, AI agent or AI tool runs in this workflow, # so a finding about third-party content reaching a model (Snyk W011, @@ -71,15 +72,15 @@ name: Knowledge sync # proposes; # - a token that can write workflows: KNOWLEDGE_SYNC_TOKEN is scoped to # this repository and to the default branch's knowledge-sync -# Environment, and reaches `publish` and `push-workflows` alone. It -# pushes one branch and opens or edits one pull request; the jobs' own token -# keeps contents: read; +# Environment, and reaches one step of `publish` alone. It pushes one +# branch and opens or edits one pull request; the jobs' own token keeps +# contents: read; # - a forced push: only to knowledge-sync, this workflow's own branch, # leased to the commit the run read, and only over this workflow's own # commits there. on: schedule: - - cron: "10 4 * * 1" # Mondays at 04:10 UTC, so the librarian's Monday run follows a current pin once the pull request is merged + - cron: "10 4 * * *" # each day at 04:10 UTC, so a release reaches this host within a day workflow_dispatch: inputs: tag: @@ -135,21 +136,9 @@ jobs: python-version: "3.12" enable-cache: false - # The pin comes from .lokf/pyproject.toml. The newest release comes - # from the index this host's uv settings name, PyPI or a mirror, with - # any exclude-newer cooldown the host sets. When the pin is there - # already the step ends after that read. - # - # Otherwise it reads the pull requests from two branches of this - # repository, each by exact name: knowledge-sync, this workflow's own, - # and sync-, the branch the sync script makes by hand. A fork's - # branch of the same name does not count, since anyone can open a pull - # request from one. From each it takes the newest pull request's - # number, state, head commit and commit count. It reads the pin in - # .lokf/pyproject.toml at that commit, which says what the pull - # request proposed whether or not its branch still exists. A title, - # body or comment is never read. The input is read through `env:` and - # held to the shape of a tag. + # The newest release comes from the index this host's uv settings name, + # PyPI or a mirror, with any exclude-newer cooldown the host sets. The + # input is read through `env:` and held to the shape of a tag. - name: Read the pin, the newest release and the last pull request id: read env: @@ -157,126 +146,14 @@ jobs: UV_INDEX_KNOWLEDGE_USERNAME: ${{ secrets.UV_INDEX_KNOWLEDGE_USERNAME }} UV_INDEX_KNOWLEDGE_PASSWORD: ${{ secrets.UV_INDEX_KNOWLEDGE_PASSWORD }} WANTED: ${{ inputs.tag }} - run: | - set -euo pipefail - # The ktl pin of a pyproject.toml on stdin, as vX.Y.Z, or nothing. - pinned() { sed -nE 's/^[[:space:]]*"ktl==([0-9]+\.[0-9]+\.[0-9]+)".*/v\1/p' | head -n 1; } - pin="" - [ ! -f .lokf/pyproject.toml ] || pin="$(pinned < .lokf/pyproject.toml)" - if [ -z "$pin" ]; then - echo "::error::.lokf/pyproject.toml pins no ktl. Pin it once, at the release this host's copies came from, with uv add --project .lokf \"ktl==X.Y.Z\", and merge pyproject.toml and uv.lock. This workflow moves the pin from then on." - exit 1 - fi - if [ -n "$WANTED" ]; then - if ! printf '%s\n' "$WANTED" | grep -qE '^v[0-9]+\.[0-9]+\.[0-9]+$'; then - echo "::error::'$WANTED' is not a release tag (vMAJOR.MINOR.PATCH)." - exit 1 - fi - tag="$WANTED" - else - if ! found="$(cd .lokf && echo ktl | uv pip compile --quiet --no-deps --no-header --no-annotate - 2>"$RUNNER_TEMP/newest.err")"; then - echo "::error::The newest ktl could not be read from this host's index ($(tr '\n' ' ' < "$RUNNER_TEMP/newest.err" | cut -c1-200)). A private index needs its credential in UV_INDEX_KNOWLEDGE_USERNAME and UV_INDEX_KNOWLEDGE_PASSWORD." - exit 1 - fi - tag="v$(printf '%s\n' "$found" | sed -n 's/^ktl==//p' | head -n 1)" - if ! printf '%s\n' "$tag" | grep -qE '^v[0-9]+\.[0-9]+\.[0-9]+$'; then - echo "::error::The newest ktl on this host's index is '$found', which is not a release this workflow can sync to." - exit 1 - fi - fi - if [ -z "$WANTED" ] && [ -n "$pin" ] && [ "$(printf '%s\n%s\n' "$pin" "$tag" | sort -V | tail -n 1)" = "$pin" ]; then - echo "::notice::The pin is at $pin and the newest release is $tag, so there is nothing to sync." - tag="" - fi - # The newest pull request from a branch of this repository, as - # one line: number, state, merged or not, head commit. - newest() { - gh api "repos/${GITHUB_REPOSITORY}/pulls?head=${GITHUB_REPOSITORY_OWNER}:$1&state=all&sort=created&direction=desc&per_page=5" \ - --jq '.[] | [.number, .state, (.merged_at != null), .head.sha, (.head.repo.full_name // "-")] | @tsv' \ - | awk -F'\t' -v repo="$GITHUB_REPOSITORY" '$1 ~ /^[0-9]+$/ && $4 ~ /^[0-9a-f]{40}$/ && $5 == repo { print; exit }' - } - # The pin .lokf/pyproject.toml carries at a commit, or nothing. - pin_at() { - gh api "repos/${GITHUB_REPOSITORY}/contents/.lokf/pyproject.toml?ref=$1" --jq .content 2>/dev/null | tr -d '\n' | base64 -d 2>/dev/null \ - | pinned || true - } - open=""; open_tag=""; declined=""; branch="" - if [ -n "$tag" ]; then - mine="$(newest knowledge-sync)" - hand="$(newest "sync-$tag")" - if [ -n "$mine" ]; then - n="$(printf '%s' "$mine" | cut -f1)"; state="$(printf '%s' "$mine" | cut -f2)"; merged="$(printf '%s' "$mine" | cut -f3)"; sha="$(printf '%s' "$mine" | cut -f4)" - proposed="$(pin_at "$sha")" - if [ "$state" = open ]; then - if [ "$proposed" = "$tag" ]; then - echo "::notice::Pull request #$n from this workflow already proposes $tag and is still open, so this run stops here." - tag="" - else - # Only this workflow's own commits are replaced: the sync, - # and the held workflow changes a reviewer approved. A - # person's commit on the branch is a change in review. - others="$(gh api "repos/${GITHUB_REPOSITORY}/pulls/$n/commits?per_page=100" --jq '[.[] | select(.commit.committer.name != "knowledge-sync[bot]")] | length')" - if [ "$others" = 0 ]; then - open="$n"; open_tag="$proposed"; branch="$sha" - echo "Pull request #$n from this workflow proposes ${proposed:-an unknown release} and is still open, so this run refreshes it to $tag." - else - echo "::notice::Pull request #$n from this workflow is still open and carries a commit a person added, so this run leaves it alone and stops here. Merge or close it first." - tag="" - fi - fi - elif [ "$merged" = false ] && [ "$proposed" = "$tag" ]; then - declined="$n" - fi - fi - if [ -n "$tag" ] && [ -n "$hand" ]; then - n="$(printf '%s' "$hand" | cut -f1)"; state="$(printf '%s' "$hand" | cut -f2)"; merged="$(printf '%s' "$hand" | cut -f3)" - if [ "$state" = open ]; then - echo "::notice::Pull request #$n, opened by hand from sync-$tag, already proposes $tag and is still open, so this run stops here." - tag="" - elif [ "$merged" = false ]; then - declined="$n" - fi - fi - # With no open pull request, a branch of that name may still - # hold commits: a person's after a merge, or one with no pull - # request. It is written over only when every commit on it - # that the default branch lacks is this workflow's own. The - # push is leased to the commit read here, so a commit added - # since is never lost. - if [ -n "$tag" ] && [ -z "$open" ]; then - tip="$(gh api "repos/${GITHUB_REPOSITORY}/git/ref/heads/knowledge-sync" --jq .object.sha 2>/dev/null || true)" - if printf '%s' "$tip" | grep -qE '^[0-9a-f]{40}$'; then - base="$(gh api "repos/${GITHUB_REPOSITORY}" --jq .default_branch)" - others="$(gh api "repos/${GITHUB_REPOSITORY}/compare/$base...$tip" --jq '[.commits[] | select(.commit.committer.name != "knowledge-sync[bot]")] | length')" - if [ "$others" != 0 ]; then - echo "::notice::The knowledge-sync branch holds a commit this workflow did not make and has no open pull request, so this run leaves it alone and stops here. Merge it or delete the branch first." - tag="" - else - branch="$tip" - fi - fi - fi - if [ -n "$tag" ] && [ -n "$declined" ] && [ "$GITHUB_EVENT_NAME" = "schedule" ]; then - echo "::notice::A person closed pull request #$declined, which proposed $tag, without merging. A scheduled run proposes it no more. A run a person starts takes it up again." - tag="" - fi - fi - { - echo "tag=$tag" - echo "from=$pin" - echo "open=$open" - echo "open_tag=$open_tag" - echo "declined=$declined" - echo "branch=$branch" - } >> "$GITHUB_OUTPUT" - [ -z "$tag" ] || echo "Syncing to $tag, from ${pin:-no pin}." + run: bash .lokf/scripts/knowledge-sync.sh --workflow read "$WANTED" sync: name: Sync the copies and the pin (read-only) needs: earlier if: needs.earlier.outputs.tag != '' runs-on: ${{ vars.KNOWLEDGE_RUNNER || 'ubuntu-latest' }} - timeout-minutes: 15 + timeout-minutes: 20 # For the index credential alone; see the header. environment: name: knowledge-sync @@ -307,45 +184,15 @@ jobs: python-version: "3.12" enable-cache: false - # The host's own copy of the script moves the pin, relocks and reads - # the release. The pull request's own checks run the synced copies, so - # this run skips them. Exit 2, an unusable release, fails the run. The - # script's lines go to this job's summary alone. + # The host's own copy of the script moves the pin, relocks, reads the + # release and writes the patch. An unusable release fails the run. - name: Run the sync script id: run env: TAG: ${{ needs.earlier.outputs.tag }} UV_INDEX_KNOWLEDGE_USERNAME: ${{ secrets.UV_INDEX_KNOWLEDGE_USERNAME }} UV_INDEX_KNOWLEDGE_PASSWORD: ${{ secrets.UV_INDEX_KNOWLEDGE_PASSWORD }} - run: | - set -euo pipefail - script=.lokf/scripts/knowledge-sync.sh - if [ ! -f "$script" ]; then - echo "::error::No $script here. ktl-sidecar's Step 5 installs it beside this workflow." - exit 1 - fi - bash "$script" --no-checks --changed "$RUNNER_TEMP/changed.txt" --report "$RUNNER_TEMP/report.md" "$TAG" - if [ -s "$RUNNER_TEMP/changed.txt" ]; then - echo "changed=true" >> "$GITHUB_OUTPUT" - { echo "## Knowledge sync to $TAG"; echo; cat "$RUNNER_TEMP/report.md"; } >> "$GITHUB_STEP_SUMMARY" - else - echo "changed=false" >> "$GITHUB_OUTPUT" - echo "::notice::The copies and the pin match $TAG already, so there is nothing to sync." - fi - - # Hand the change to the privileged job as a patch: the files the - # script changed or added, by name, and nothing else. - - name: Package the change - if: steps.run.outputs.changed == 'true' - run: | - set -euo pipefail - # The script refuses a copy into .git, and git is told here, too, to - # run no command a configuration could name. - g() { git -c core.fsmonitor=false -c core.hooksPath=/dev/null -c diff.external= "$@"; } - while IFS= read -r path; do - [ -n "$path" ] && g add -- "$path" - done < "$RUNNER_TEMP/changed.txt" - g diff --cached --binary --no-ext-diff --no-textconv > "$RUNNER_TEMP/sync.patch" + run: bash .lokf/scripts/knowledge-sync.sh --workflow sync "$TAG" - name: Upload the patch if: steps.run.outputs.changed == 'true' @@ -363,9 +210,9 @@ jobs: needs: [earlier, sync] if: needs.sync.outputs.changed == 'true' runs-on: ${{ vars.KNOWLEDGE_RUNNER || 'ubuntu-latest' }} - timeout-minutes: 10 - # The two jobs that push take turns. A run waiting for the review - # Environment holds no turn, so it blocks no later sync. + timeout-minutes: 20 + # One publish at a time. No job waits for a person, so a run holds the + # turn only while it pushes. concurrency: group: knowledge-sync cancel-in-progress: false @@ -377,9 +224,6 @@ jobs: deployment: false permissions: contents: read # the push and the pull request use the sync token, not this one - outputs: - held: ${{ steps.check.outputs.held }} - commit: ${{ steps.push.outputs.commit }} steps: - name: Harden the runner uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 @@ -411,17 +255,14 @@ jobs: # The default branch's copy of the sync script puts the patch on. It # checks the paths, takes a pin at this run's tag alone, has uv resolve # the lock again from the index, and holds every workflow change in a - # patch of its own for a person to read and apply. + # patch of its own. The sync token is not in this step. - name: Check the patch and apply it id: check env: TAG: ${{ needs.earlier.outputs.tag }} UV_INDEX_KNOWLEDGE_USERNAME: ${{ secrets.UV_INDEX_KNOWLEDGE_USERNAME }} UV_INDEX_KNOWLEDGE_PASSWORD: ${{ secrets.UV_INDEX_KNOWLEDGE_PASSWORD }} - run: | - set -euo pipefail - bash .lokf/scripts/knowledge-sync.sh --apply "$RUNNER_TEMP/sync.patch" --held "$RUNNER_TEMP/workflows.patch" "$TAG" - if [ -s "$RUNNER_TEMP/workflows.patch" ]; then echo "held=true" >> "$GITHUB_OUTPUT"; else echo "held=false" >> "$GITHUB_OUTPUT"; fi + run: bash .lokf/scripts/knowledge-sync.sh --workflow apply "$TAG" - name: Attach the held workflow changes if: steps.check.outputs.held == 'true' @@ -432,275 +273,16 @@ jobs: retention-days: 30 if-no-files-found: error - # The body is written here, from the patch this job applied and this - # checkout: the files the patch changes, the workflow changes it held - # and the pin it sets. - # Then comes the pull request template as the default branch has it, - # whose checklist is the reviewer's. The commit is made under a bot - # identity, which the AI covenant asks of a repository's own - # automation, and carries no trailer. The push and the pull request - # use the sync token (see the header), and the push is leased to the - # commit the `earlier` job read, so a commit added since is never - # lost. Without the token the run ends here, green, with the patches - # attached and the summary written. + # The push is leased to the commit the `earlier` job read, so a commit + # added since is never lost. Without the token the run ends here, + # green, with the patches attached and the summary written. - name: Commit, push and open or refresh the pull request - id: push env: - SYNC_TOKEN: ${{ secrets.KNOWLEDGE_SYNC_TOKEN }} TAG: ${{ needs.earlier.outputs.tag }} - FROM: ${{ needs.earlier.outputs.from }} - OPEN_PR: ${{ needs.earlier.outputs.open }} - OPEN_TAG: ${{ needs.earlier.outputs.open_tag }} - DECLINED_PR: ${{ needs.earlier.outputs.declined }} - LEASE: ${{ needs.earlier.outputs.branch }} - HELD: ${{ steps.check.outputs.held }} - REVIEW_ENV: ${{ vars.KNOWLEDGE_SYNC_REVIEW_ENVIRONMENT }} - run: | - set -euo pipefail - branch="knowledge-sync" - subject="security(sidecar): sync copies and skills pin from $TAG" - held="$RUNNER_TEMP/workflows.patch" - bt="$(printf '\140')" # a backtick, for the code spans below - # The held workflow changes, as the summary and the body show them. - heldmd="$RUNNER_TEMP/held.md" - : > "$heldmd" - if [ "$HELD" = true ]; then - { - echo "### Workflow changes held for a person" - echo - echo "This release also changes these workflows. They are not on the branch: a workflow pushed with a token runs on that push, with this repository's secrets, before anyone has read it." - echo - git -c core.quotePath=false apply --numstat "$held" | cut -f3- | sed "s/.*/- ${bt}&${bt}/" - echo - if [ "$(wc -c < "$held")" -le 50000 ]; then - # A fence longer than any run of backticks in the diff, so - # the release's text cannot close it and write the body. - fence='````' - while grep -qF "$fence" "$held"; do fence="$fence$bt"; done - echo "
The held diff" - echo - echo "${fence}diff" - cat "$held" - echo "$fence" - echo - echo "
" - else - echo "The diff is too long to show here. It is the run's ${bt}knowledge-sync-workflows${bt} artifact." - fi - echo - echo "Once you have read them, apply them on this branch:" - echo - echo '```sh' - echo "gh run download ${GITHUB_RUN_ID} --repo ${GITHUB_REPOSITORY} --name knowledge-sync-workflows" - echo "git switch $branch && git pull" - echo "git apply workflows.patch && git add .github/workflows" - echo "git commit -m \"security(sidecar): sync workflows from $TAG\" && git push" - echo '```' - echo - echo "Without gh, the artifact is on the run's page: ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}." - if [ -n "$REVIEW_ENV" ]; then - echo - echo "Or approve the run's ${bt}Approve the held workflow changes${bt} job as a reviewer of the ${bt}${REVIEW_ENV}${bt} Environment, and the workflow pushes them here as a second commit." - fi - } > "$heldmd" - cat "$heldmd" >> "$GITHUB_STEP_SUMMARY" - fi - if [ -z "$SYNC_TOKEN" ]; then - { - echo "## No pull request opened" - echo - echo "This workflow opens the pull request with the secret ${bt}KNOWLEDGE_SYNC_TOKEN${bt}, which is not set in the ${bt}knowledge-sync${bt} Environment or the repository. The change is attached to this run as ${bt}sync.patch${bt}. To open it by hand, run ${bt}.lokf/scripts/knowledge-sync.sh --pr $TAG${bt} in a clone; to let the workflow open it, set the secret as the sidecar's references/automation.md says." - } >> "$GITHUB_STEP_SUMMARY" - echo "::warning::KNOWLEDGE_SYNC_TOKEN is not set, so no pull request was opened; the patch is attached to this run." - exit 0 - fi - repo="https://github.com/noelmcloughlin/knowledge-trust-ladder" - link="$repo/blob/$TAG/CHANGELOG.md" - if [ -n "$FROM" ] && [ "$FROM" != "$TAG" ]; then link="$repo/compare/$FROM...$TAG"; fi - # The workflows are held, so the copies are the changed files but - # the changelog and the pin's two. - copies="$(git -c core.quotePath=false diff --cached --name-status | awk -F'\t' '$1 == "M" && $2 != "CHANGELOG.md" && $2 != ".lokf/pyproject.toml" && $2 != ".lokf/uv.lock" { print $2 }')" - added="$(git -c core.quotePath=false diff --cached --name-status | awk -F'\t' '$1 == "A" { print $2 }')" - body="$RUNNER_TEMP/body.md" - { - if [ -n "$FROM" ] && [ "$FROM" != "$TAG" ]; then - echo "Brings the sidecar copies and the skills pin of this repository to Knowledge Trust Ladder [$TAG]($link), from $FROM." - else - echo "Brings the sidecar copies and the skills pin of this repository to Knowledge Trust Ladder [$TAG]($link)." - fi - if [ -n "$OPEN_PR" ]; then - echo - echo "**Refreshed on $(date -u +%Y-%m-%d).** This pull request proposed ${OPEN_TAG:-an earlier release} before. This run replaced its commits with a sync to $TAG, so read the diff again." - fi - if [ -n "$copies" ]; then - echo; echo "The sync writes the release's copy over these files. The sync job's summary on the run's page names any that held a local edit:"; echo - printf '%s\n' "$copies" | sed "s/.*/- ${bt}&${bt}/" - fi - if [ -n "$added" ]; then - echo; echo "Added, because a file here needs it:"; echo - printf '%s\n' "$added" | sed "s/.*/- ${bt}&${bt}/" - fi - echo - echo "The skills pin, ${bt}ktl${bt} in ${bt}.lokf/pyproject.toml${bt}, moves from $FROM to $TAG, and ${bt}.lokf/uv.lock${bt} holds the hashes uv resolved for it in this run." - if [ -s "$heldmd" ]; then - echo - cat "$heldmd" - fi - echo - echo "This repository's own checks run on this pull request, on the synced copies, with a read-only token. A failure there is a bundle to fix in this pull request, or the gate fails on it after the merge." - echo - if git diff --cached --name-only | grep -qx 'CHANGELOG.md'; then - echo "CHANGELOG.md has the entry under its Unreleased heading and Security." - else - echo "CHANGELOG.md is unchanged: it has the entry already, or it has no Unreleased heading, in which case add the entry by hand." - fi - echo - if [ -n "$DECLINED_PR" ]; then - echo "Pull request #$DECLINED_PR proposed this release and was closed without merging. A person started this run, so it proposes the release again." - echo - fi - git show HEAD:.github/PULL_REQUEST_TEMPLATE/knowledge-sync.md 2>/dev/null || true - } > "$body" - git config user.name "knowledge-sync[bot]" - git config user.email "knowledge-sync[bot]@users.noreply.github.com" - git checkout --quiet -b "$branch" - git commit --quiet -m "$subject" - echo "commit=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" - # The branch is this workflow's own: a refresh writes over the - # last run's commits, and so does a run a person starts after a - # declined pull request. An empty lease means the branch must not - # exist yet. The token travels in the push address, which GitHub - # masks in the log. - if ! git push --quiet --force-with-lease="refs/heads/$branch:$LEASE" "https://x-access-token:${SYNC_TOKEN}@${GITHUB_SERVER_URL#https://}/${GITHUB_REPOSITORY}.git" "HEAD:refs/heads/$branch"; then - echo "::error::The push was refused. Either the branch moved since this run read it, or KNOWLEDGE_SYNC_TOKEN lacks Contents set to read and write on this repository." - exit 1 - fi - if [ -n "$OPEN_PR" ]; then - GH_TOKEN="$SYNC_TOKEN" gh pr edit "$OPEN_PR" --title "$subject" --body-file "$body" >/dev/null - url="$(GH_TOKEN="$SYNC_TOKEN" gh pr view "$OPEN_PR" --json url --jq .url)" - echo "Refreshed $url" - else - base="$(GH_TOKEN="$SYNC_TOKEN" gh api "repos/${GITHUB_REPOSITORY}" --jq .default_branch)" - url="$(GH_TOKEN="$SYNC_TOKEN" gh pr create --title "$subject" --body-file "$body" --head "$branch" --base "$base")" - echo "Opened $url" - fi - { echo; echo "Pull request: $url"; } >> "$GITHUB_STEP_SUMMARY" - - # The optional route for the held workflow changes. With the repository - # variable KNOWLEDGE_SYNC_REVIEW_ENVIRONMENT set to the name of an - # Environment with required reviewers, this job waits for one of them. - # The run's summary shows the held diff they approve. Then the next job - # pushes those changes onto the pull request's branch as a second commit, - # and they run from that push on. Set the Environment up under Settings -> - # Environments: add required reviewers and limit it to the default - # branch. It holds no secret. "Prevent self-review" helps only where a - # second person can approve. An Environment with no required reviewers - # would approve itself, so the next job checks for them before it pushes - # anything. - review: - name: Approve the held workflow changes - needs: [publish] - if: needs.publish.outputs.held == 'true' && needs.publish.outputs.commit != '' && vars.KNOWLEDGE_SYNC_REVIEW_ENVIRONMENT != '' - runs-on: ${{ vars.KNOWLEDGE_RUNNER || 'ubuntu-latest' }} - timeout-minutes: 5 - permissions: {} - environment: - name: ${{ vars.KNOWLEDGE_SYNC_REVIEW_ENVIRONMENT }} - deployment: false - steps: - - name: Harden the runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 - with: - egress-policy: audit - - - name: Record the approval - env: - REVIEW_ENV: ${{ vars.KNOWLEDGE_SYNC_REVIEW_ENVIRONMENT }} - run: echo "A reviewer of the '${REVIEW_ENV}' Environment approved the held workflow changes." - - push-workflows: - name: Push the approved workflow changes (privileged) - needs: [earlier, publish, review] - runs-on: ${{ vars.KNOWLEDGE_RUNNER || 'ubuntu-latest' }} - timeout-minutes: 10 - concurrency: - group: knowledge-sync - cancel-in-progress: false - environment: - name: knowledge-sync - deployment: false - permissions: - actions: read # read the review Environment's protection rules - contents: read # the push uses the sync token, not this one - steps: - - name: Harden the runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 - with: - egress-policy: audit - - # An approval means something only from an Environment that needs a - # reviewer, so one with none pushes nothing. - - name: Check the review Environment has required reviewers - env: - GH_TOKEN: ${{ github.token }} - REVIEW_ENV: ${{ vars.KNOWLEDGE_SYNC_REVIEW_ENVIRONMENT }} - run: | - set -euo pipefail - name="$(jq -rn --arg e "$REVIEW_ENV" '$e | @uri')" - n="$(gh api "repos/${GITHUB_REPOSITORY}/environments/${name}" --jq '[.protection_rules[]? | select(.type == "required_reviewers") | .reviewers[]?] | length' 2>/dev/null || echo 0)" - if [ "$n" = 0 ]; then - echo "::error::The '${REVIEW_ENV}' Environment has no required reviewers, so its approval proves nothing. Nothing is pushed; apply the held changes by hand as the pull request says." - exit 1 - fi - - - name: Checkout the pull request's commit - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - ref: ${{ needs.publish.outputs.commit }} - persist-credentials: false - - - name: Download the held workflow changes - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 - with: - name: knowledge-sync-workflows - path: ${{ runner.temp }} - - # The held patch touches workflows and nothing else, and only edits - # and adds plain files. The push is leased to the commit the publish - # job pushed, so a branch that moved since is left alone. - - name: Commit and push the workflow changes - env: SYNC_TOKEN: ${{ secrets.KNOWLEDGE_SYNC_TOKEN }} - TAG: ${{ needs.earlier.outputs.tag }} - LEASE: ${{ needs.publish.outputs.commit }} - run: | - set -euo pipefail - held="$RUNNER_TEMP/workflows.patch" - wrong="$(git -c core.quotePath=false apply --numstat "$held" | cut -f3- | grep -Ev '^\.github/workflows/knowledge-[a-z]+\.yaml$' || true)" - wrong+=$'\n'"$(git apply --summary "$held" | grep -E '^ (delete mode|rename|copy|mode change) ' || true)" - wrong+=$'\n'"$(git apply --summary "$held" | grep -E '^ create mode ' | grep -vE '^ create mode 100644 ' || true)" - if [ -n "${wrong//[$'\n\t ']/}" ]; then - echo "::error::The held patch does more than edit and add workflows:" - printf '%s\n' "$wrong" | sed '/^$/d; s/^/ /' - exit 1 - fi - # A pull request merged, closed or refreshed while the approval - # waited leaves these changes stale; the next sync carries them. - tip="$(git ls-remote "https://x-access-token:${SYNC_TOKEN}@${GITHUB_SERVER_URL#https://}/${GITHUB_REPOSITORY}.git" refs/heads/knowledge-sync | cut -f1)" - if [ -z "$tip" ]; then - echo "::warning::The knowledge-sync branch is gone: its pull request was merged or closed while this approval waited. Nothing is pushed; the next sync proposes any workflow change still missing." - exit 0 - fi - if [ "$tip" != "$LEASE" ]; then - echo "::error::The knowledge-sync branch moved from $LEASE to $tip while this approval waited, so these held changes are stale. Nothing is pushed; apply the ones the pull request lists now, or let the next sync propose them." - exit 1 - fi - git apply --index "$held" - git config user.name "knowledge-sync[bot]" - git config user.email "knowledge-sync[bot]@users.noreply.github.com" - git commit --quiet -m "security(sidecar): sync workflows from $TAG" - if ! git push --quiet --force-with-lease="refs/heads/knowledge-sync:$LEASE" "https://x-access-token:${SYNC_TOKEN}@${GITHUB_SERVER_URL#https://}/${GITHUB_REPOSITORY}.git" "HEAD:refs/heads/knowledge-sync"; then - echo "::error::The push was refused: the branch moved since the pull request was opened, or KNOWLEDGE_SYNC_TOKEN cannot write workflows." - exit 1 - fi - echo "Pushed the workflow changes from $TAG onto knowledge-sync." >> "$GITHUB_STEP_SUMMARY" + SYNC_FROM: ${{ needs.earlier.outputs.from }} + SYNC_OPEN_PR: ${{ needs.earlier.outputs.open }} + SYNC_OPEN_TAG: ${{ needs.earlier.outputs.open_tag }} + SYNC_DECLINED_PR: ${{ needs.earlier.outputs.declined }} + SYNC_LEASE: ${{ needs.earlier.outputs.branch }} + run: bash .lokf/scripts/knowledge-sync.sh --workflow publish "$TAG" diff --git a/.lokf/pyproject.toml b/.lokf/pyproject.toml index b3d827f..ceed5d0 100644 --- a/.lokf/pyproject.toml +++ b/.lokf/pyproject.toml @@ -12,7 +12,7 @@ description = "LOKF knowledge-bundle tooling for SLSA." # Keep in sync with the `lokf` toolkit's own requires-python floor. requires-python = ">=3.11" dependencies = [ - "ktl==0.70.1", + "ktl==0.70.3", "lokf[build]>=0.9.0", "rust-just==1.59.0", ] diff --git a/.lokf/scripts/knowledge-sync.sh b/.lokf/scripts/knowledge-sync.sh index ccd9d32..95846ee 100755 --- a/.lokf/scripts/knowledge-sync.sh +++ b/.lokf/scripts/knowledge-sync.sh @@ -22,7 +22,8 @@ # # The host's own copy runs, from a person or knowledge-sync.yaml. A manifest # rule it does not know is reported for the run after the newer copy is -# merged. +# merged. The workflow's steps are here too (--workflow), so a fix to a step +# reaches a host in its next sync pull request. # # Usage: knowledge-sync.sh [options] # --host the host; by default the nearest parent holding .lokf/ @@ -42,11 +43,14 @@ # lock the pin again from the index and compare, and move # every workflow change into --held for a person to apply # --held where --apply writes the held workflow changes +# --workflow run one step of knowledge-sync.yaml (read, sync, apply +# or publish), with its inputs in the job's environment; +# only read may leave out the tag # # KNOWLEDGE_SYNC_INDEX_WAIT, a number of seconds, keeps asking the index for # a release it does not show yet, for a sync asked right after the release: # a mirror trails PyPI by a minute or so. Unset or 0, a missing release is -# final. +# final. In a workflow step it defaults to 600. # # Exit 0 when the host is synced or already was. Exit 1 when the host was # skipped (no .lokf/, no git, no ktl pin, uncommitted changes, the branch @@ -66,6 +70,9 @@ website_in="ktl/skills/ktl-website/templates" librarian_in="ktl/skills/ktl-librarian/SKILL.md" # The pin, as the template writes it: one dependency line naming one release. pin_re='^[[:space:]]*"ktl==([0-9]+\.[0-9]+\.[0-9]+)"[[:space:]]*,?[[:space:]]*(#.*)?$' +# The workflow's own branch, and the name its commits carry. +sync_branch="knowledge-sync" +bot="knowledge-sync[bot]" # The manifest's header says what each rule means. The rules this copy of # the script knows: @@ -123,8 +130,9 @@ cleanup() { [[ -z "$work" ]] || rm -rf "$work" } -# The version a host's pyproject.toml pins ktl to, or nothing: . -pinned() { sed -nE "s/$pin_re/\\1/p" "$1" | head -n 1; } +# The version a host's pyproject.toml pins ktl to, or nothing: , or +# the file's text on stdin. +pinned() { sed -nE "s/$pin_re/\\1/p" "$@" | head -n 1; } # The ktl entry of a project's lock, with its hashes, as a requirements file # uv reads: . Nothing when the lock does not name ktl. @@ -261,9 +269,322 @@ apply_patch() { for f in $(git -c core.quotePath=false diff --name-only "$lane" "$full"); do echo " held $f (a workflow change, for a person to apply)"; done } +# The steps of knowledge-sync.yaml. Each runs from the host's root, reads its +# inputs from the job's environment and writes its outputs to $GITHUB_OUTPUT. +# references/automation.md describes the jobs. + +# One output of the step: . +output() { printf '%s=%s\n' "$1" "$2" >> "$GITHUB_OUTPUT"; } + +# Print the newest pull request from of this repository as number, +# state, merged and head commit. A fork's branch of that name is ignored. +last_pull_request() { + gh api "repos/${GITHUB_REPOSITORY}/pulls?head=${GITHUB_REPOSITORY%%/*}:$1&state=all&sort=created&direction=desc&per_page=5" \ + --jq '.[] | [.number, .state, (.merged_at != null), .head.sha, (.head.repo.full_name // "-")] | @tsv' \ + | awk -F'\t' -v repo="$GITHUB_REPOSITORY" '!done && $1 ~ /^[0-9]+$/ && $4 ~ /^[0-9a-f]{40}$/ && $5 == repo { print; done = 1 }' +} + +# Print the ktl pin pyproject.toml holds at , as vX.Y.Z, or nothing. +pin_at() { + local version + version="$(gh api "repos/${GITHUB_REPOSITORY}/contents/$pyproject?ref=$1" --jq .content 2>/dev/null | tr -d '\n' | base64 -d 2>/dev/null | pinned || true)" + [[ -z "$version" ]] || echo "v$version" +} + +# The `earlier` job: pick the release to sync to, or none: []. It reads +# the pin, the newest release on the host's index, and the state of this +# workflow's branch and last pull request, never a title, body or comment. +workflow_read() { + local wanted="$1" pin tag found + pin="$(pinned "$pyproject" 2>/dev/null || true)" + if [[ -z "$pin" ]]; then + echo "::error::$pyproject pins no ktl. Pin it once, at the release this host's copies came from, with uv add --project .lokf \"ktl==X.Y.Z\", and merge pyproject.toml and uv.lock. This workflow moves the pin from then on." + return 1 + fi + pin="v$pin" + if [[ -n "$wanted" ]]; then + tag="$wanted" + else + if ! found="$(cd .lokf && echo ktl | uv pip compile --quiet --no-deps --no-header --no-annotate - 2>"$RUNNER_TEMP/newest.err")"; then + echo "::error::The newest ktl could not be read from this host's index ($(tr '\n' ' ' < "$RUNNER_TEMP/newest.err" | cut -c1-200)). A private index needs its credential in UV_INDEX_KNOWLEDGE_USERNAME and UV_INDEX_KNOWLEDGE_PASSWORD." + return 1 + fi + tag="v$(printf '%s\n' "$found" | sed -n 's/^ktl==//p' | head -n 1)" + if [[ ! "$tag" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + echo "::error::The newest ktl on this host's index is '$found', which is not a release this workflow can sync to." + return 1 + fi + if [[ "$(printf '%s\n%s\n' "$pin" "$tag" | sort -V | tail -n 1)" == "$pin" ]]; then + echo "::notice::The pin is at $pin and the newest release is $tag, so there is nothing to sync." + tag="" + fi + fi + local open="" open_tag="" declined="" branch="" mine hand n state merged sha proposed others tip base + if [[ -n "$tag" ]]; then + mine="$(last_pull_request "$sync_branch")" + hand="$(last_pull_request "sync-$tag")" + if [[ -n "$mine" ]]; then + IFS=$'\t' read -r n state merged sha _ <<< "$mine" + proposed="$(pin_at "$sha")" + if [[ "$state" == open && "$proposed" == "$tag" ]]; then + echo "::notice::Pull request #$n from this workflow already proposes $tag and is still open, so this run stops here." + tag="" + elif [[ "$state" == open ]]; then + # Only this workflow's own commits are replaced. + others="$(gh api "repos/${GITHUB_REPOSITORY}/pulls/$n/commits?per_page=100" --jq "[.[] | select(.commit.committer.name != \"$bot\")] | length")" + if [[ "$others" == 0 ]]; then + open="$n"; open_tag="$proposed"; branch="$sha" + echo "Pull request #$n from this workflow proposes ${proposed:-an unknown release} and is still open, so this run refreshes it to $tag." + else + echo "::notice::Pull request #$n from this workflow is still open and carries a commit a person added, so this run leaves it alone and stops here. Merge or close it first." + tag="" + fi + elif [[ "$merged" == false && "$proposed" == "$tag" ]]; then + declined="$n" + fi + fi + if [[ -n "$tag" && -n "$hand" ]]; then + IFS=$'\t' read -r n state merged _ <<< "$hand" + if [[ "$state" == open ]]; then + echo "::notice::Pull request #$n, opened by hand from sync-$tag, already proposes $tag and is still open, so this run stops here." + tag="" + elif [[ "$merged" == false ]]; then + declined="$n" + fi + fi + # With no open pull request, overwrite the branch only when every commit + # on it is this workflow's own, and lease the push to the tip read here. + if [[ -n "$tag" && -z "$open" ]]; then + tip="$(gh api "repos/${GITHUB_REPOSITORY}/git/ref/heads/$sync_branch" --jq .object.sha 2>/dev/null || true)" + if [[ "$tip" =~ ^[0-9a-f]{40}$ ]]; then + base="$(gh api "repos/${GITHUB_REPOSITORY}" --jq .default_branch)" + others="$(gh api "repos/${GITHUB_REPOSITORY}/compare/$base...$tip" --jq "[.commits[] | select(.commit.committer.name != \"$bot\")] | length")" + if [[ "$others" != 0 ]]; then + echo "::notice::The $sync_branch branch holds a commit this workflow did not make and has no open pull request, so this run leaves it alone and stops here. Merge it or delete the branch first." + tag="" + else + branch="$tip" + fi + fi + fi + if [[ -n "$tag" && -n "$declined" && "${GITHUB_EVENT_NAME:-}" == schedule ]]; then + echo "::notice::A person closed pull request #$declined, which proposed $tag, without merging. A scheduled run proposes it no more. A run a person starts takes it up again." + tag="" + fi + fi + output tag "$tag" + output from "$pin" + output open "$open" + output open_tag "$open_tag" + output declined "$declined" + output branch "$branch" + [[ -z "$tag" ]] || echo "Syncing to $tag, from $pin." +} + +# The `sync` job: run the sync and write the changed files as a patch: +# . It skips the checks, which the pull request runs. +workflow_sync() { + local tag="$1" changed="$RUNNER_TEMP/changed.txt" report="$RUNNER_TEMP/report.md" path + ( main --host "$PWD" --no-checks --changed "$changed" --report "$report" "$tag" ) + if [[ ! -s "$changed" ]]; then + output changed false + echo "::notice::The copies and the pin match $tag already, so there is nothing to sync." + return 0 + fi + output changed true + { echo "## Knowledge sync to $tag"; echo; cat "$report"; } >> "$GITHUB_STEP_SUMMARY" + # Stop git from running any command a config file names. + g() { git -c core.fsmonitor=false -c core.hooksPath=/dev/null -c diff.external= "$@"; } + while IFS= read -r path; do + [[ -z "$path" ]] || g add -- "$path" + done < "$changed" + g diff --cached --binary --no-ext-diff --no-textconv > "$RUNNER_TEMP/sync.patch" +} + +# The `publish` job, without the token: check and apply the patch, and hold +# the workflow changes: . +workflow_apply() { + local held="$RUNNER_TEMP/workflows.patch" + apply_patch "$RUNNER_TEMP/sync.patch" "$held" "$1" + if [[ -s "$held" ]]; then output held true; else output held false; fi +} + +# Write the held workflow changes as Markdown for the summary and the pull +# request: <1 if the sync has a branch, else 0>. +held_section() { + local held="$1" tag="$2" on_branch="$3" bt='`' fence='````' + echo "### Workflow changes held for a person" + echo + if [[ "$on_branch" -eq 1 ]]; then + echo "This release also changes these workflows. They are not on the branch: a workflow pushed with a token runs on that push, with this repository's secrets, before anyone has read it." + else + echo "This release changes these workflows and nothing else here, so no pull request was opened. A workflow pushed with a token runs on that push, with this repository's secrets, before anyone has read it." + fi + echo + git -c core.quotePath=false apply --numstat "$held" | cut -f3- | sed "s/.*/- ${bt}&${bt}/" + echo + if [[ "$(wc -c < "$held")" -le 50000 ]]; then + # Use a fence longer than any run of backticks in the diff, so the diff + # cannot close it. + while grep -qF "$fence" "$held"; do fence="$fence$bt"; done + echo "
The held diff" + echo + echo "${fence}diff" + cat "$held" + echo "$fence" + echo + echo "
" + else + echo "The diff is too long to show here. It is the run's ${bt}knowledge-sync-workflows${bt} artifact." + fi + echo + if [[ "$on_branch" -eq 1 ]]; then + echo "Once you have read them, apply them on this branch. If you merge without them, the workflows stay as they are until the next sync offers them again." + else + echo "Once you have read them, apply them on a branch from the default branch, and open its pull request:" + fi + echo + echo '```sh' + echo "gh run download ${GITHUB_RUN_ID:-} --repo ${GITHUB_REPOSITORY} --name knowledge-sync-workflows" + if [[ "$on_branch" -eq 1 ]]; then + echo "git switch $sync_branch && git pull" + else + echo "git switch -c sync-workflows-$tag" + fi + echo "git apply workflows.patch && git add .github/workflows" + if [[ "$on_branch" -eq 1 ]]; then + echo "git commit -m \"security(sidecar): sync workflows from $tag\" && git push" + else + echo "git commit -m \"security(sidecar): sync workflows from $tag\" && git push -u origin HEAD" + fi + echo '```' + echo + echo "Without gh, the artifact is on the run's page: ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID:-}." +} + +# The `publish` job, with the token: commit the staged change, push the +# branch, and open or refresh the pull request: . The body comes from +# the staged change and the default branch's checklist, never from the +# `sync` job. Without the token the run succeeds with the patches attached. +workflow_publish() { + local tag="$1" token="${SYNC_TOKEN:-}" from="${SYNC_FROM:-}" open="${SYNC_OPEN_PR:-}" open_tag="${SYNC_OPEN_TAG:-}" + local declined="${SYNC_DECLINED_PR:-}" lease="${SYNC_LEASE:-}" + local held="$RUNNER_TEMP/workflows.patch" heldmd="$RUNNER_TEMP/held.md" body="$RUNNER_TEMP/body.md" + local subject="security(sidecar): sync copies and skills pin from $tag" + local bt='`' staged=1 link copies added url base + ! git diff --cached --quiet || staged=0 + : > "$heldmd" + if [[ -s "$held" ]]; then + held_section "$held" "$tag" "$staged" > "$heldmd" + cat "$heldmd" >> "$GITHUB_STEP_SUMMARY" + fi + if [[ "$staged" -eq 0 ]]; then + echo "::notice::$tag changes nothing here but workflows, which are held for a person, so no pull request was opened." + return 0 + fi + if [[ -z "$token" ]]; then + { + echo "## No pull request opened" + echo + echo "This workflow opens the pull request with the secret ${bt}KNOWLEDGE_SYNC_TOKEN${bt}, which is not set in the ${bt}knowledge-sync${bt} Environment or the repository. The change is attached to this run as ${bt}sync.patch${bt}. To open it by hand, run ${bt}.lokf/scripts/knowledge-sync.sh --pr $tag${bt} in a clone; to let the workflow open it, set the secret as the sidecar's references/automation.md says." + } >> "$GITHUB_STEP_SUMMARY" + echo "::warning::KNOWLEDGE_SYNC_TOKEN is not set, so no pull request was opened; the patch is attached to this run." + return 0 + fi + link="$repo_url/blob/$tag/CHANGELOG.md" + [[ -z "$from" || "$from" == "$tag" ]] || link="$repo_url/compare/$from...$tag" + # The copies are the staged files other than the changelog and the pin's. + copies="$(git -c core.quotePath=false diff --cached --name-status | awk -F'\t' -v p="$pyproject" -v l="$lock" '$1 == "M" && $2 != "CHANGELOG.md" && $2 != p && $2 != l { print $2 }')" + added="$(git -c core.quotePath=false diff --cached --name-status | awk -F'\t' '$1 == "A" { print $2 }')" + { + if [[ -n "$from" && "$from" != "$tag" ]]; then + echo "Brings the sidecar copies and the skills pin of this repository to Knowledge Trust Ladder [$tag]($link), from $from." + else + echo "Brings the sidecar copies and the skills pin of this repository to Knowledge Trust Ladder [$tag]($link)." + fi + if [[ -n "$open" ]]; then + echo + echo "**Refreshed on $(date -u +%Y-%m-%d).** This pull request proposed ${open_tag:-an earlier release} before. This run replaced its commits with a sync to $tag, so read the diff again." + fi + if [[ -n "$copies" ]]; then + echo; echo "The sync writes the release's copy over these files. The sync job's summary on the run's page names any that held a local edit:"; echo + printf '%s\n' "$copies" | sed "s/.*/- ${bt}&${bt}/" + fi + if [[ -n "$added" ]]; then + echo; echo "Added, because a file here needs it:"; echo + printf '%s\n' "$added" | sed "s/.*/- ${bt}&${bt}/" + fi + echo + if [[ -n "$from" && "$from" != "$tag" ]]; then + echo "The skills pin, ${bt}ktl${bt} in ${bt}$pyproject${bt}, moves from $from to $tag, and ${bt}$lock${bt} holds the hashes uv resolved for it in this run." + else + echo "The skills pin, ${bt}ktl${bt} in ${bt}$pyproject${bt}, is at $tag already." + fi + if [[ -s "$heldmd" ]]; then + echo + cat "$heldmd" + fi + echo + echo "This repository's own checks run on this pull request, on the synced copies, with a read-only token. A failure there is a bundle to fix in this pull request, or the gate fails on it after the merge." + echo + if git diff --cached --quiet -- CHANGELOG.md; then + echo "CHANGELOG.md is unchanged: it has the entry already, or it has no Unreleased heading, in which case add the entry by hand." + else + echo "CHANGELOG.md has the entry under its Unreleased heading and Security." + fi + echo + if [[ -n "$declined" ]]; then + echo "Pull request #$declined proposed this release and was closed without merging. A person started this run, so it proposes the release again." + echo + fi + git show HEAD:.github/PULL_REQUEST_TEMPLATE/knowledge-sync.md 2>/dev/null || true + } > "$body" + # Commit as the bot, as the AI covenant asks of a repository's automation, + # with no trailer. The read step finds its own commits by this name, so it + # overrides any identity the runner sets. + git checkout --quiet -b "$sync_branch" + GIT_AUTHOR_NAME="$bot" GIT_AUTHOR_EMAIL="$bot@users.noreply.github.com" \ + GIT_COMMITTER_NAME="$bot" GIT_COMMITTER_EMAIL="$bot@users.noreply.github.com" \ + git commit --quiet -m "$subject" + # A refresh writes over the last run's commits. An empty lease means the + # branch must not exist yet. GitHub masks the token in the push address. + if ! git push --quiet --force-with-lease="refs/heads/$sync_branch:$lease" "https://x-access-token:${token}@${GITHUB_SERVER_URL#https://}/${GITHUB_REPOSITORY}.git" "HEAD:refs/heads/$sync_branch"; then + echo "::error::The push was refused. Either the branch moved since this run read it, or KNOWLEDGE_SYNC_TOKEN lacks Contents set to read and write on this repository." + return 1 + fi + if [[ -n "$open" ]]; then + GH_TOKEN="$token" gh pr edit "$open" --title "$subject" --body-file "$body" >/dev/null + url="$(GH_TOKEN="$token" gh pr view "$open" --json url --jq .url)" + echo "Refreshed $url" + else + base="$(GH_TOKEN="$token" gh api "repos/${GITHUB_REPOSITORY}" --jq .default_branch)" + url="$(GH_TOKEN="$token" gh pr create --title "$subject" --body-file "$body" --head "$sync_branch" --base "$base")" + echo "Opened $url" + fi + { echo; echo "Pull request: $url"; } >> "$GITHUB_STEP_SUMMARY" +} + +# One step of knowledge-sync.yaml: []. +workflow_step() { + local step="$1" tag="$2" name + for name in GITHUB_OUTPUT GITHUB_STEP_SUMMARY GITHUB_REPOSITORY GITHUB_SERVER_URL RUNNER_TEMP; do + [[ -n "${!name:-}" ]] || die "--workflow runs as a step of knowledge-sync.yaml, and $name is not set" + done + [[ -n "$tag" || "$step" == read ]] || die "--workflow $step needs the tag the run syncs to" + # A new release may not be in every cache of the index yet. + export KNOWLEDGE_SYNC_INDEX_WAIT="${KNOWLEDGE_SYNC_INDEX_WAIT:-600}" + case "$step" in + read) workflow_read "$tag" ;; + sync) workflow_sync "$tag" ;; + apply) workflow_apply "$tag" ;; + publish) workflow_publish "$tag" ;; + *) die "--workflow takes read, sync, apply or publish, not '$step'" ;; + esac +} + main() { local host="" source="" tag="" changed_out="" report_out="" out - local apply="" held="" + local apply="" held="" step="" local branch_mode=0 commit=0 push=0 pr=0 checks=1 while [[ $# -gt 0 ]]; do case "$1" in @@ -278,13 +599,16 @@ main() { --no-checks) checks=0; shift ;; --apply) [[ $# -ge 2 ]] || usage; apply="$2"; shift 2 ;; --held) [[ $# -ge 2 ]] || usage; held="$2"; shift 2 ;; + --workflow) [[ $# -ge 2 ]] || usage; step="$2"; shift 2 ;; -h|--help) usage ;; -*) echo "knowledge-sync: unknown option $1" >&2; usage ;; *) [[ -z "$tag" ]] || usage; tag="$1"; shift ;; esac done - [[ -n "$tag" ]] || usage - if [[ ! "$tag" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + # Only the workflow's read step may come with no tag: it finds the newest. + [[ -n "$tag" || "$step" == read ]] || usage + if [[ -n "$tag" && ! "$tag" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + [[ -z "$step" ]] || echo "::error::'$tag' is not a release tag (vMAJOR.MINOR.PATCH)." die "'$tag' is not a release tag (vMAJOR.MINOR.PATCH); a branch or a commit would let unreleased instructions into this host" fi local version="${tag#v}" @@ -306,6 +630,11 @@ main() { echo " $host is not a git work tree: the sync leaves a diff for review, and there is no diff to leave here; skipped" >&2 return 1 fi + if [[ -n "$step" ]]; then + cd "$host" + workflow_step "$step" "$tag" + return + fi if [[ -n "$apply" ]]; then [[ -n "$held" ]] || die "--apply needs --held " apply="$(cd "$(dirname "$apply")" && pwd -P)/$(basename "$apply")" diff --git a/.lokf/uv.lock b/.lokf/uv.lock index fed4623..5cbc952 100644 --- a/.lokf/uv.lock +++ b/.lokf/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 5 +revision = 3 requires-python = ">=3.11" resolution-markers = [ "python_full_version >= '3.14'", @@ -796,11 +796,11 @@ wheels = [ [[package]] name = "ktl" -version = "0.70.1" +version = "0.70.3" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a4/fb/862f7b7667793c0016e2b369c68c20c60fe6852efda7c06938685a689bfb/ktl-0.70.1.tar.gz", hash = "sha256:766e4c224a74b83eca1c0888783ecb59f898ec0c9a85e6ade146cd014e778ca2", size = 865903, upload-time = "2026-11-19T02:21:15.672Z" } +sdist = { url = "https://files.pythonhosted.org/packages/85/13/edbba4c4ce6a8056b1491ad2f015e475f40cb91cc138077b311f69c1135f/ktl-0.70.3.tar.gz", hash = "sha256:088160e4444fbdfd17f79aaeaf07adea7082af5a034d1d48902a86807c682048", size = 863036, upload-time = "2026-11-19T21:10:01.133Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/51/ec/aac103aafc809e4072c80044bd849aa1552a8945f01d0490d5380fc8fd33/ktl-0.70.1-py3-none-any.whl", hash = "sha256:5fd25df258e66830cb7cfdb82460ba6d15b733b008922e8a1d9ac4280991699c", size = 981664, upload-time = "2026-11-19T02:21:13.769Z" }, + { url = "https://files.pythonhosted.org/packages/73/56/1cc4ec68be344c19f77bb3a354b4c294038d3cea994291e2355bbf943ffd/ktl-0.70.3-py3-none-any.whl", hash = "sha256:b750466f5e55aeeef04ce3722751314b75e69cc7dd3548167752537639e14578", size = 978558, upload-time = "2026-11-19T21:09:59.607Z" }, ] [[package]] @@ -2027,7 +2027,7 @@ dependencies = [ [package.metadata] requires-dist = [ - { name = "ktl", specifier = "==0.70.1" }, + { name = "ktl", specifier = "==0.70.3" }, { name = "lokf", extras = ["build"], specifier = ">=0.9.0" }, { name = "rust-just", specifier = "==1.59.0" }, ] diff --git a/CHANGELOG.md b/CHANGELOG.md index e44eb20..bd52617 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ The `v0.1.0` tag is a baseline, not a release: it marks where versioning starts ## [Unreleased] +### Security + +- **The sidecar copies and the skills pin are at Knowledge Trust Ladder [v0.70.3](https://github.com/noelmcloughlin/knowledge-trust-ladder/compare/v0.70.1...v0.70.3).** The release changed `.github/PULL_REQUEST_TEMPLATE/knowledge-sync.md` and `.lokf/scripts/knowledge-sync.sh` here. The sync also wrote the template over a local edit of `.github/workflows/knowledge-release.yaml` and `.github/workflows/knowledge-sync.yaml`. + ## [0.11.5] - 2026-11-19 ### Security