Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .claude/hooks/verify-on-stop.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ const TESTS = [
[/^knowledge\/|^bin\/knowledge-|^bin\/lib\/knowledge\.mjs$/, ["knowledge-parity", "knowledge-report"]],
[/^blueprint\/sync\.json$|^bin\/(lib\/)?template-sync|^bin\/sync-parity\.mjs$|^workflow-templates\//, ["template-sync", "sync-parity"]],
// What the public repository publishes from these must stay counts only.
[/^\.github\/workflows\/(freshness|template-sync)\.yml$|^bin\/template-sync\.mjs$/, ["freshness-public"]],
[/^\.github\/workflows\/(freshness|template-sync)\.yml$|^bin\/template-sync(-pr\.sh|\.mjs)$/, ["freshness-public", "sync-log-public"]],
[/^bin\/new-repo\.sh$/, ["new-repo"]],
// The guard starters in blueprint/files/ and the push guard's helper are copies of, or used by, the hooks.
[/^\.claude\/hooks\/|^bin\/lib\/signed-range\.mjs$|^blueprint\/files\//, ["harness-"]],
Expand Down
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ Needs `gh` (repo admin) and `jq`. Validate edits with `bash -n bin/apply-repo-ba

## Blueprint script internals

- This repository is public: `org-audit.yml` publishes counts only (`org-audit.sh --public`), and so does the `copies` job of `freshness.yml` (`template-sync.mjs --public`). Never put per-repository drift, or which copy is behind, in an issue, summary, logs or artifacts: `guard-public-issues.mjs` denies both kinds of line for an org repository name.
- This repository is public: `org-audit.yml` publishes counts only (`org-audit.sh --public`), and so does the `copies` job of `freshness.yml` (`template-sync.mjs --public`). The log of `template-sync.yml` has counts only too: in a workflow run (`GITHUB_ACTIONS=true`) `template-sync.mjs --write` prints `refreshed N copies` and `template-sync-pr.sh` how many files and bytes, and their errors name no file, branch, title or `gh` text; by hand they print the full detail. What a public log still shows is the repository name (from the step environment, the token action and checkout), that a leg ran for it, and the URL of the pull request the script prints itself. `tests/sync-log-public.test.mjs` runs both scripts through their failure paths to hold this. Never put per-repository drift, or which copy is behind, in an issue, summary, logs or artifacts: `guard-public-issues.mjs` denies both kinds of line for an org repository name.
- Exit codes: 0 clean, 1 drift in `--check`, 2 usage or a missing tool, 3 any failed call (`trap 'exit 3' ERR`). Keep 1 for drift only: `org-audit.yml` reads 3 as "could not be checked".
- `settle LABEL CURRENT DESIRED METHOD PATH [BODY]` is the single compare-then-act primitive: both sides are `jq -S`-normalized and compared; only on mismatch does it diff/print/apply. `pick` reduces live API JSON to just the keys the blueprint file names — so **a blueprint JSON file owns exactly the keys it lists**; adding a key extends what's enforced, keys not listed are never touched.
- Rulesets are matched to live ones **by `name`** (POST if absent, PUT by id if present) and compared after `normalize_ruleset` (rules sorted by `type`). Renaming a ruleset in a file creates a second ruleset rather than renaming the old one.
Expand Down
87 changes: 69 additions & 18 deletions bin/template-sync-pr.sh
Original file line number Diff line number Diff line change
Expand Up @@ -55,20 +55,34 @@ title='ci: refresh workflow copies from the org templates'
title_mixed='chore: refresh copies of the org templates and starters'
here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
max_bytes=1000000
# In a workflow run the log of this public repository is readable by anyone. Say how many files and
# bytes, never which files: that is which copy is behind. A run by hand prints the full detail.
ci=0
if [[ "${GITHUB_ACTIONS:-}" == true ]]; then ci=1; fi

die() {
printf 'error: %s\n' "$*" >&2
exit 1
}

# A failed `gh` call names the repository, the branch or the pull request title in its message. In a
# workflow that log is public, so the call's stderr is dropped and the script says only that it failed.
gh_() {
if [[ "$ci" == 1 ]]; then
gh "$@" 2>/dev/null || die "a GitHub call failed"
else
gh "$@"
fi
}

cd "$dir"
git rev-parse --is-inside-work-tree >/dev/null 2>&1 || die "$dir is not a git checkout"

# Stage only to read the change set: nothing is committed locally, and the
# checkout holds no credential.
git add -A
if git diff --cached --quiet; then
printf '%s: every copy is current: nothing to do\n' "$repo"
if [[ "$ci" == 1 ]]; then printf 'every copy is current: nothing to do\n'; else printf '%s: every copy is current: nothing to do\n' "$repo"; fi
exit 0
fi

Expand All @@ -89,13 +103,24 @@ while IFS= read -r changed; do
other+="$changed "
fi
done < <(git diff --cached --name-only --no-renames)
[[ -z "$other" ]] || die "these changes are neither a workflow file nor a starter a sync may refresh, so none is sent: $other"
if [[ -n "$other" ]]; then
if [[ "$ci" == 1 ]]; then
die "$(wc -w <<<"$other" | tr -d ' ') change(s) are neither a workflow file nor a starter a sync may refresh, so none is sent"
fi
die "these changes are neither a workflow file nor a starter a sync may refresh, so none is sent: $other"
fi
[[ "$only_workflows" -eq 1 ]] || title="$title_mixed"
# Only a change to a file the repository already has: a sync refreshes, never adds or removes.
nonmod="$(git diff --cached --raw --no-renames | awk '$5 != "M" { print $5, $NF }')"
[[ -z "$nonmod" ]] || die "a sync only modifies existing files, got: $nonmod"
if [[ -n "$nonmod" ]]; then
if [[ "$ci" == 1 ]]; then die "a sync only modifies existing files, got $(wc -l <<<"$nonmod" | tr -d ' ') that are not"; fi
die "a sync only modifies existing files, got: $nonmod"
fi
bad_mode="$(git diff --cached --raw --no-renames | awk '$2 != "100644" { print $2, $NF }')"
[[ -z "$bad_mode" ]] || die "these files are not plain 100644 files, so the API cannot commit them: $bad_mode"
if [[ -n "$bad_mode" ]]; then
if [[ "$ci" == 1 ]]; then die "$(wc -l <<<"$bad_mode" | tr -d ' ') file(s) are not plain 100644 files, so the API cannot commit them"; fi
die "these files are not plain 100644 files, so the API cannot commit them: $bad_mode"
fi

work="$(mktemp -d)"
trap 'rm -rf "$work"' EXIT
Expand All @@ -114,27 +139,39 @@ done < <(git diff --cached --name-only --no-renames -z)
((total <= max_bytes)) || die "the change adds $total bytes, over the $max_bytes the API call is kept to"
# Same files, same content: same branch, so a repeated run finds its own pull request.
branch="$prefix$(printf '%s' "$fingerprint" | git hash-object --stdin | cut -c1-12)"
printf '%s: %d file(s), %d bytes: %s\n' "$repo" "${#files[@]}" "$total" "${files[*]}"
if [[ "$ci" == 1 ]]; then
printf '%d file(s), %d bytes\n' "${#files[@]}" "$total"
else
printf '%s: %d file(s), %d bytes: %s\n' "$repo" "${#files[@]}" "$total" "${files[*]}"
fi

if [[ "$dry_run" == 1 ]]; then
git diff --cached --stat --no-renames
printf 'dry run: would commit %s to %s and open "%s"\n' "$branch" "$repo" "$title"
if [[ "$ci" == 1 ]]; then
printf 'dry run: would commit and open a pull request\n'
else
git diff --cached --stat --no-renames
printf 'dry run: would commit %s to %s and open "%s"\n' "$branch" "$repo" "$title"
fi
exit 0
fi

default="$(gh api "repos/$repo" --jq .default_branch)"
base="$(gh api "repos/$repo/git/ref/heads/$default" --jq .object.sha)"
default="$(gh_ api "repos/$repo" --jq .default_branch)"
base="$(gh_ api "repos/$repo/git/ref/heads/$default" --jq .object.sha)"
[[ "$(git rev-parse HEAD)" == "$base" ]] || die "$default moved while the run was working: run it again"

existing="$(gh pr list -R "$repo" --head "$branch" --state all --json state --jq 'map(.state) | join(",")')"
existing="$(gh_ pr list -R "$repo" --head "$branch" --state all --json state --jq 'map(.state) | join(",")')"
if [[ -n "$existing" ]]; then
printf '%s already has a pull request for these files (%s): not opening another\n' "$repo" "$existing"
if [[ "$ci" == 1 ]]; then
printf 'a pull request for these files already exists (%s): not opening another\n' "$existing"
else
printf '%s already has a pull request for these files (%s): not opening another\n' "$repo" "$existing"
fi
exit 0
fi
# A branch with no pull request is what a run that failed half way leaves.
gh api -X DELETE "repos/$repo/git/refs/heads/$branch" >/dev/null 2>&1 || true

gh api -X POST "repos/$repo/git/refs" -f "ref=refs/heads/$branch" -f "sha=$base" >/dev/null
gh_ api -X POST "repos/$repo/git/refs" -f "ref=refs/heads/$branch" -f "sha=$base" >/dev/null
# shellcheck disable=SC2016 # the dollar signs are GraphQL variables
query='mutation($input: CreateCommitOnBranchInput!) { createCommitOnBranch(input: $input) { commit { oid } } }'
if ! jq -n \
Expand All @@ -146,12 +183,15 @@ if ! jq -n \
message: {headline: $title, body: $signoff},
expectedHeadOid: $oid,
fileChanges: {additions: $additions}}}}' |
gh api graphql --input - >"$work/commit.json"; then
gh api graphql --input - >"$work/commit.json" 2>"$work/commit.err"; then
gh api -X DELETE "repos/$repo/git/refs/heads/$branch" >/dev/null 2>&1 || true
if [[ "$ci" == 1 ]]; then die "could not commit the files"; fi
cat "$work/commit.err" >&2
die "could not commit to $branch"
fi
if jq -e '.errors' "$work/commit.json" >/dev/null 2>&1; then
gh api -X DELETE "repos/$repo/git/refs/heads/$branch" >/dev/null 2>&1 || true
if [[ "$ci" == 1 ]]; then die "the API refused the commit ($(jq '.errors | length' "$work/commit.json") error(s))"; fi
die "the API refused the commit: $(jq -c '.errors' "$work/commit.json")"
fi

Expand All @@ -163,18 +203,29 @@ body="$(
printf 'Each file is the current template or starter for this repository. For a workflow, **the action pins are the template'"'"'s**: a pin can be tied to an input in the same file, so they move together. Dependabot here keeps them current afterwards. Read the diff, as a template change can alter what a workflow does. The required checks run on this pull request as on any other.\n\n'
printf 'Opened by `template-sync.yml` in `monte3l/.github`. Rules: [Workflow template sync](https://github.com/monte3l/.github/blob/main/blueprint/README.md#workflow-template-sync).\n'
)"
url="$(gh pr create -R "$repo" --head "$branch" --base "$default" --title "$title" --body "$body")"
url="$(gh_ pr create -R "$repo" --head "$branch" --base "$default" --title "$title" --body "$body")"
printf 'opened %s\n' "$url"
new_number="${url##*/}"

# An older pull request of this script is replaced by this one, which is computed
# from the current files, but only when the bot alone committed to it.
while IFS=$'\t' read -r number; do
[[ "$number" != "$new_number" ]] || continue
authors="$(gh pr view "$number" -R "$repo" --json commits --jq '[.commits[].authors[].login] | unique | join(",")')"
authors="$(gh_ pr view "$number" -R "$repo" --json commits --jq '[.commits[].authors[].login] | unique | join(",")')"
if [[ "$authors" == "$bot" ]]; then
gh pr close "$number" -R "$repo" --delete-branch --comment "Superseded by $url, which refreshes the same files from the current templates."
if [[ "$ci" == 1 ]]; then
# `gh pr close` reports the pull request's title and the deleted branch: say neither in a public log.
gh pr close "$number" -R "$repo" --delete-branch --comment "Superseded by $url, which refreshes the same files from the current templates." >/dev/null 2>&1 ||
die "could not close an older pull request"
printf 'closed an older pull request\n'
else
gh pr close "$number" -R "$repo" --delete-branch --comment "Superseded by $url, which refreshes the same files from the current templates."
fi
else
printf 'left #%s open: it has commits by %s\n' "$number" "$authors"
if [[ "$ci" == 1 ]]; then
printf 'left an older pull request open: it has commits by someone else\n'
else
printf 'left #%s open: it has commits by %s\n' "$number" "$authors"
fi
fi
done < <(gh pr list -R "$repo" --state open --author "app/monte3l-sync" --json number,headRefName --jq ".[] | select(.headRefName | startswith(\"$prefix\")) | .number")
done < <(gh_ pr list -R "$repo" --state open --author "app/monte3l-sync" --json number,headRefName --jq ".[] | select(.headRefName | startswith(\"$prefix\")) | .number")
33 changes: 27 additions & 6 deletions bin/template-sync.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,13 @@
* summary and its logs are readable by anyone. It cannot be combined with --json or
* --write, which carry names.
*
* In a workflow (GITHUB_ACTIONS=true) the log of a public repository must not say
* which file of which repository is behind. So an error message there names no
* repository, file or `gh` text, whatever the options (the plan job runs it with
* --json), and a --write run prints only how many copies it refreshed. A copy held
* back for its job names is not mentioned there either. The same run by hand prints
* the full table and the full messages.
*
* It must not be able to report "nothing found" by failing quietly, because a
* workflow closes its tracking issue on that. So it stops with exit 3 when a
* repository cannot be read in full (private, renamed, missing) and with exit 2
Expand Down Expand Up @@ -94,6 +101,14 @@ for (let i = 0; i < args.length; i++) {
}
if (publicOutput && (asJson || writeDir !== null)) fail(2, `--public prints counts only, so it cannot be combined with --json or --write\n${USAGE}`);
if (writeDir !== null && (only === null || only.length !== 1)) fail(2, `--write needs --repos with exactly one repository\n${USAGE}`);
// In a workflow run (GITHUB_ACTIONS=true) the log of a public repository is readable by anyone, and which
// file of which repository is behind must stay out of it. So under CI an error message names no repository,
// file or `gh` text (`redact`), and a --write leg prints only how many copies it refreshed (`ciWrite`).
// A run by hand keeps the full table and the full messages, which is the audit view.
const inCi = process.env.GITHUB_ACTIONS === "true";
const redact = publicOutput || inCi;
const ciWrite = writeDir !== null && inCi;
let written = 0;
for (const name of [owner, ...(only ?? [])]) if (!NAME_RE.test(name)) fail(2, `not an owner or repository name: ${name}`);

const run = (cmd, argv) => execFileSync(cmd, argv, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: 16 * 1024 * 1024 });
Expand Down Expand Up @@ -183,10 +198,10 @@ function assertReadable(repo) {
try {
info = JSON.parse(run("gh", ["api", `repos/${owner}/${repo}`, "--jq", "{private, archived}"]));
} catch (error) {
if (missing(error)) fail(3, `${publicOutput ? "a repository" : `${owner}/${repo}`} does not exist, or this token cannot see it`);
if (missing(error)) fail(3, `${redact ? "a repository" : `${owner}/${repo}`} does not exist, or this token cannot see it`);
throw error;
}
if (info.private) fail(3, `${publicOutput ? "a repository" : `${owner}/${repo}`} is private, and this token reads public repositories only`);
if (info.private) fail(3, `${redact ? "a repository" : `${owner}/${repo}`} is private, and this token reads public repositories only`);
}

const repos = Object.keys(config.repos).filter((name) => only === null || only.includes(name)).sort();
Expand Down Expand Up @@ -226,7 +241,7 @@ try {
try {
current = render(versions[unit.source].current, params);
} catch (error) {
fail(3, `${unit.source}: ${error.message}`);
fail(3, redact ? "a template could not be rendered (run it by hand for the detail)" : `${unit.source}: ${error.message}`);
}
const old = [];
for (const version of versions[unit.source].old) {
Expand All @@ -248,7 +263,9 @@ try {
const { unit, found, current } = copy;
// Only a workflow has jobs: a starter has no required check to rename.
if (unit.kind === "workflow" && jobNames(found.text).join("\n") !== jobNames(current).join("\n")) {
console.error(`template-sync: left out ${repo} ${unit.name}.yml: the refresh would change its job names, which a required check depends on. A person does this one`);
// A copy held back for its job names says so by hand only: in a public log it would tell an outsider
// which repository renamed a required check. The pull request body says a rename is never refreshed.
if (!redact) console.error(`template-sync: left out ${repo} ${unit.name}.yml: the refresh would change its job names, which a required check depends on. A person does this one`);
continue;
}
const target = path.join(writeDir, found.path);
Expand All @@ -257,12 +274,13 @@ try {
// repository that checks its licence headers inline fails on a workflow that lost them.
const refreshed = keepHeader(current, found.text);
writeFileSync(target, refreshed.endsWith("\n") ? refreshed : `${refreshed}\n`);
written++;
}
}
}
} catch (error) {
// The message of a failed `gh` call usually holds the repository's path, so a public run leaves it out.
fail(3, publicOutput ? "a read failed (run without --public for the detail)" : `a read failed: ${String(error.stderr ?? error.message).trim().split("\n")[0]}`);
fail(3, publicOutput ? "a read failed (run without --public for the detail)" : redact ? "a read failed (run it by hand for the detail)" : `a read failed: ${String(error.stderr ?? error.message).trim().split("\n")[0]}`);
}

const stale = results.filter((r) => r.managed && r.state === "STALE");
Expand All @@ -287,7 +305,7 @@ const publicSummary = () => {
return lines;
};
if (findingsFile) {
const lines = publicOutput ? publicSummary() : findings;
const lines = publicOutput || ciWrite ? publicSummary() : findings;
writeFileSync(findingsFile, lines.length === 0 ? "" : `${lines.join("\n")}\n`);
}

Expand All @@ -301,6 +319,9 @@ if (publicOutput) {
console.log(`unmanaged copies: ${countOf(results.filter((r) => !r.managed && r.state !== "MISSING"))}`);
const summary = publicSummary();
console.log(summary.length === 0 ? "\nfindings: none" : `\nfindings:\n${summary.map((line) => ` ${line}`).join("\n")}`);
} else if (ciWrite) {
// A leg exists only for a repository with a stale copy, so even a "behind" count would add nothing to say.
console.log(`refreshed ${plural(written, "copy", "copies")}`);
} else if (asJson) {
console.log(JSON.stringify({ results, mismatches }, null, 2));
} else {
Expand Down
23 changes: 23 additions & 0 deletions blueprint/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,29 @@ one. The repository is public and a name would tell an outsider where to aim. Ru
`node bin/template-sync.mjs` with `gh` access for the full comparison. Eleven
verbatim starters are compared the same way, see [Starters](#starters).

The log of `template-sync.yml` follows the same rule, and a test drives both scripts
through every path it can reach to hold it (`tests/sync-log-public.test.mjs`). In a
workflow run (`GITHUB_ACTIONS=true`):

- `template-sync.mjs --write` prints only `refreshed N copies`. Its error messages, in
the plan job too, name no repository, file, template or `gh` text.
- A copy held back because its refresh would rename a job is not mentioned in the log.
- `template-sync-pr.sh` prints how many files and bytes, never which files, versions,
branch, title or commit author. A refusal says how many changes it refused, and a
failed `gh` call says only that it failed, with its own message dropped.

Run by hand, both print the full detail and the full messages: that is the audit view.
What a public log still shows:

| What | Why |
| --- | --- |
| The repository being refreshed | The step environment, the token action's inputs and `actions/checkout` print it, not these scripts. The names are already public in `sync.json`. |
| That a leg ran for it | A leg exists only for a repository with a stale copy, so its existence says that one is behind. Not which file, how far, or why. |
| The URL of the pull request it opened | The script prints it, and it holds the repository name. The pull request is public in the other repository. |

A failure that is not one of those cases, such as an uncaught error from `jq`, can still
print what the tool prints. The script does not trap every exit.

The template is first **rendered** for the repository: `https://PROJECT.monte3l.com`
becomes its site, and a block between `# sync:if FLAG` and `# sync:end` stays
only in a repository that has that flag in `sync.json`. Then the two are
Expand Down
Loading