Skip to content

The agent that grows with you

feat(release): dispatch exact-commit builds and bind their stamps

ethernet11c65c4f3303
diff --git a/apps/desktop/scripts/commit-stamp-identity.test.mjs b/apps/desktop/scripts/commit-stamp-identity.test.mjs
new file mode 100644
index 00000000000..e26f3a5d6cf
--- /dev/null
+++ b/apps/desktop/scripts/commit-stamp-identity.test.mjs
@@ -0,0 +1,61 @@
+import assert from 'node:assert/strict'
+import { execFileSync, spawnSync } from 'node:child_process'
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+
+import { test } from 'vitest'
+
+const root = path.resolve(import.meta.dirname, '../../..')
+
+test('desktop stamp uses the admitted checkout rather than the dispatch SHA', () => {
+ const temp = fs.mkdtempSync(path.join(os.tmpdir(), 'stamp-identity-'))
+ const repo = path.join(temp, 'repo')
+ const scripts = path.join(repo, 'apps/desktop/scripts')
+ const git = (...args) => execFileSync('git', args, { cwd: repo, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim()
+ try {
+ fs.mkdirSync(scripts, { recursive: true })
+ for (const name of ['write-build-stamp.mjs', 'utils.mjs']) fs.copyFileSync(path.join(root, 'apps/desktop/scripts', name), path.join(scripts, name))
+ git('init', '-q', '-b', 'main')
+ git('config', 'user.name', 'Fixture')
+ git('config', 'user.email', '[email protected]')
+ git('add', '.')
+ git('commit', '-qm', 'main')
+ const main = git('rev-parse', 'HEAD')
+ git('checkout', '-qb', 'feature')
+ fs.writeFileSync(path.join(repo, 'feature'), 'feature\n')
+ git('add', 'feature')
+ git('commit', '-qm', 'feature')
+ const feature = git('rev-parse', 'HEAD')
+ const runtime = { repoDir: 'app', toolsDir: 'tools', storePython: 'tools/python/bin/python3', sitePackages: 'venv/site-packages', commands: { hermes: 'bin/hermes' } }
+ const build = path.join(repo, 'apps/desktop/build')
+ fs.mkdirSync(path.join(build, 'agent-payload'), { recursive: true })
+ fs.writeFileSync(path.join(build, 'agent-payload/manifest.json'), JSON.stringify({ runtime }))
+ const out = path.join(build, 'install-stamp.json')
+ const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith('GITHUB_') && !key.startsWith('HERMES_PAYLOAD_') && !key.startsWith('HERMES_BUILD_')))
+ Object.assign(env, { GITHUB_SHA: main, GITHUB_REF_NAME: 'main', HERMES_BUILD_COMMIT: feature, HERMES_DESKTOP_VARIANT: 'bundled' })
+ const run = override => spawnSync(process.execPath, [path.join(scripts, 'write-build-stamp.mjs')], { cwd: temp, env: { ...env, ...override }, encoding: 'utf8', timeout: 30000 })
+ const result = run({})
+ assert.equal(result.status, 0, result.stderr)
+ const stamp = JSON.parse(fs.readFileSync(out, 'utf8'))
+ assert.equal(stamp.commit, feature)
+ assert.equal(stamp.branch, null)
+ assert.equal(stamp.source, 'commit-build')
+ assert.equal(stamp.tag, null)
+ assert.equal(stamp.updateMechanism, 'external')
+ assert.deepEqual(stamp.runtime, runtime)
+ const before = fs.readFileSync(out)
+ git('checkout', '-q', 'main')
+ assert.notEqual(run({}).status, 0)
+ assert.deepEqual(fs.readFileSync(out), before)
+ git('checkout', '-q', 'feature')
+ for (const override of [{ HERMES_BUILD_COMMIT: feature.slice(0, 8) }, { HERMES_BUILD_COMMIT: ` ${feature}` }, { HERMES_PAYLOAD_TAG: 'v1.2.3' }]) {
+ assert.notEqual(run(override).status, 0)
+ assert.deepEqual(fs.readFileSync(out), before)
+ }
+ assert.equal(run({ HERMES_BUILD_COMMIT: '', HERMES_PAYLOAD_TAG: 'v1.2.3', GITHUB_SHA: feature }).status, 0)
+ assert.equal(JSON.parse(fs.readFileSync(out, 'utf8')).tag, 'v1.2.3')
+ } finally {
+ fs.rmSync(temp, { recursive: true, force: true })
+ }
+})
diff --git a/apps/desktop/scripts/write-build-stamp.mjs b/apps/desktop/scripts/write-build-stamp.mjs
index a642e3ebee0..f7b3d319535 100644
--- a/apps/desktop/scripts/write-build-stamp.mjs
+++ b/apps/desktop/scripts/write-build-stamp.mjs
@@ -8,7 +8,7 @@
import { mkdirSync, readFileSync, writeFileSync } from "fs"
import { resolve, join, relative } from "path"
-import { execSync } from "child_process"
+import { execFileSync } from "child_process"
import { isMain } from "./utils.mjs"
@@ -23,9 +23,9 @@ const REPO_ROOT = resolve(DESKTOP_ROOT, "..", "..")
const OUT_DIR = join(DESKTOP_ROOT, "build")
const OUT_FILE = join(OUT_DIR, "install-stamp.json")
-function tryExec(cmd, opts) {
+function tryExec(argv, opts) {
try {
- return execSync(cmd, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], ...opts }).trim()
+ return execFileSync(argv[0], argv.slice(1), { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 5000, ...opts }).trim()
} catch {
return null
}
@@ -44,16 +44,16 @@ export function fromCI(env = process.env) {
}
export function fromLocalGit(repoRoot = REPO_ROOT, execFn = tryExec) {
- const sha = execFn("git rev-parse HEAD", { cwd: repoRoot })
+ const sha = execFn(["git", "rev-parse", "HEAD"], { cwd: repoRoot })
if (!sha) return null
- const branch = execFn("git rev-parse --abbrev-ref HEAD", { cwd: repoRoot })
+ const branch = execFn(["git", "rev-parse", "--abbrev-ref", "HEAD"], { cwd: repoRoot })
// `git status --porcelain -uno` is empty iff tracked files match HEAD.
// We exclude untracked files (-uno) intentionally: a developer who's
// checked out an installer scratch dir alongside the repo shouldn't
// poison every local build with a [DIRTY] stamp. We DO care about
// tracked-but-modified files because those mean the .exe content
// differs from the commit being pinned.
- const status = execFn("git status --porcelain -uno", { cwd: repoRoot })
+ const status = execFn(["git", "status", "--porcelain", "-uno"], { cwd: repoRoot })
const dirty = status !== null && status.length > 0
return {
commit: sha,
@@ -87,6 +87,16 @@ export function resolveStamp({
execFn = tryExec,
fallbackBranch = FALLBACK_BRANCH
} = {}) {
+ if (env.HERMES_BUILD_COMMIT) {
+ if (!/^[a-f0-9]{40}$/.test(env.HERMES_BUILD_COMMIT) || env.HERMES_PAYLOAD_TAG) {
+ throw new Error('Commit builds require an exact full SHA without a release tag')
+ }
+ const local = fromLocalGit(repoRoot, execFn)
+ if (!local || local.commit !== env.HERMES_BUILD_COMMIT) {
+ throw new Error('Commit build identity does not match the checkout HEAD')
+ }
+ return { ...local, branch: null, source: 'commit-build' }
+ }
return fromCI(env) || fromLocalGit(repoRoot, execFn) || fromFallback(fallbackBranch)
}
@@ -152,13 +162,20 @@ function main() {
*/
export function buildStampPayload(stamp, env = process.env, platform = process.platform, payload = null) {
const variant = (env.HERMES_DESKTOP_VARIANT || "").trim()
+ const commitBuild = env.HERMES_BUILD_COMMIT || null
+ if (commitBuild && (!/^[a-f0-9]{40}$/.test(commitBuild) || commitBuild !== stamp.commit)) {
+ throw new Error('Commit build identity does not match the stamp commit')
+ }
+ if (commitBuild && env.HERMES_PAYLOAD_TAG) {
+ throw new Error('Commit builds cannot also set a release tag')
+ }
const base = {
schemaVersion: STAMP_SCHEMA_VERSION,
commit: stamp.commit,
- branch: stamp.branch,
+ branch: commitBuild ? null : stamp.branch,
builtAt: new Date().toISOString(),
dirty: stamp.dirty,
- source: stamp.source,
+ source: commitBuild ? 'commit-build' : stamp.source,
commitDate: stamp.commitDate ?? null,
baseVersion: stamp.baseVersion ?? null,
displayVersion: stamp.displayVersion ?? null,
@@ -181,7 +198,7 @@ export function buildStampPayload(stamp, env = process.env, platform = process.p
...base,
payload: variant === "store" ? "bundled" : variant || "bootstrap",
distribution: "desktop-app",
- updateMechanism,
+ updateMechanism: commitBuild ? 'external' : updateMechanism,
tag: env.HERMES_PAYLOAD_TAG || null,
...(bundled ? { runtime: payload.runtime } : {})
}
diff --git a/apps/desktop/scripts/write-build-stamp.test.mjs b/apps/desktop/scripts/write-build-stamp.test.mjs
index ffb7d9b9a91..c9b27724416 100644
--- a/apps/desktop/scripts/write-build-stamp.test.mjs
+++ b/apps/desktop/scripts/write-build-stamp.test.mjs
@@ -26,7 +26,8 @@ test('fromLocalGit returns null when git rev-parse fails', () => {
test('fromLocalGit reads HEAD + branch + dirty status', () => {
const calls = []
- const execFn = (cmd) => {
+ const execFn = (argv) => {
+ const cmd = argv.join(' ')
calls.push(cmd)
if (cmd === 'git rev-parse HEAD') return 'b'.repeat(40)
if (cmd === 'git rev-parse --abbrev-ref HEAD') return 'main'
@@ -63,7 +64,8 @@ test('resolveStamp prefers CI over local git over fallback', () => {
const local = resolveStamp({
env: {},
- execFn: (cmd) => {
+ execFn: (argv) => {
+ const cmd = argv.join(' ')
if (cmd === 'git rev-parse HEAD') return 'd'.repeat(40)
if (cmd === 'git rev-parse --abbrev-ref HEAD') return 'main'
if (cmd === 'git status --porcelain -uno') return ''
@@ -162,3 +164,17 @@ test('buildStampPayload keeps schemaVersion + provenance in the staged shape', (
assert.equal(payload.tag, null)
})
+test('commit builds retain exact provenance without entering an update channel', () => {
+ for (const platform of ['win32', 'darwin']) {
+ const env = { HERMES_DESKTOP_VARIANT: 'bundled', HERMES_BUILD_COMMIT: baseStamp.commit }
+ const payload = buildStampPayload(baseStamp, env, platform, { runtime })
+ assert.equal(payload.commit, baseStamp.commit)
+ assert.equal(payload.source, 'commit-build')
+ assert.equal(payload.branch, null)
+ assert.equal(payload.tag, null)
+ assert.equal(payload.updateMechanism, 'external')
+ assert.throws(() => buildStampPayload(baseStamp, { ...env, HERMES_BUILD_COMMIT: 'a'.repeat(40) }, platform, { runtime }), /commit/i)
+ assert.throws(() => buildStampPayload(baseStamp, { ...env, HERMES_PAYLOAD_TAG: 'v1.2.3' }, platform, { runtime }), /tag/i)
+ }
+})
+
diff --git a/scripts/release.py b/scripts/release.py
index 33015a20fc8..e33d769574d 100755
--- a/scripts/release.py
+++ b/scripts/release.py
@@ -2199,7 +2199,7 @@ def _default_branch(gh_repo: str | None) -> str | None:
"""The repo's default branch, resolved via gh. None on any failure."""
cmd = ["gh", "repo", "view", "--json", "defaultBranchRef", "--jq", ".defaultBranchRef.name"]
if gh_repo:
- cmd += ["--repo", gh_repo]
+ cmd += [gh_repo]
result = subprocess.run(
cmd, capture_output=True, text=True, encoding="utf-8",
errors="replace", cwd=str(REPO_ROOT),
@@ -2235,13 +2235,17 @@ def resolve_push_remote(requested: str | None) -> str:
def remote_github_repo(remote: str) -> str | None:
- """The 'owner/repo' behind a remote's push URL, for gh --repo.
- None when the URL is not a recognizable GitHub URL."""
+ """Read the GitHub repository that receives the remote's pushes."""
result = git_result("remote", "get-url", "--push", remote)
if result.returncode != 0:
return None
url = result.stdout.strip()
- match = re.search(r"github\.com[:/]([^/]+/[^/]+?)(?:\.git)?/?$", url)
+ match = re.fullmatch(
+ r"(?:https?://(?:[^/@\s]+@)?github\.com/|"
+ r"ssh://(?:[^/@\s]+@)?github\.com(?::\d+)?/|"
+ r"git://github\.com/|[^/@:\s]+@github\.com:)"
+ r"([A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+?)(?:\.git)?/?", url,
+ )
return match.group(1) if match else None
@@ -2889,6 +2893,9 @@ def main():
help="Tag + publish today's canary prerelease "
"(v<stable.minor+1>.0-canary.<YYYYMMDDHHMMSS>); no-op when "
"HEAD has no new commits since the last canary")
+ parser.add_argument("--build-commit", type=str, metavar="REV",
+ help="Preview an exact-commit build into releases/commit/<sha>/ on R2. "
+ "Add --publish to dispatch without a tag or release.")
parser.add_argument("--prune-canaries", action="store_true",
help="Delete canary releases+tags older than 14 days")
parser.add_argument("--publish", action="store_true",
@@ -2909,6 +2916,18 @@ def main():
if args.canary and args.bump:
parser.error("--canary and --bump are mutually exclusive")
+ if args.build_commit is not None:
+ conflicting = [name for name, supplied in (
+ ("--bump", args.bump), ("--canary", args.canary),
+ ("--prune-canaries", args.prune_canaries), ("--first-release", args.first_release),
+ ("--date", args.date), ("--output", args.output), ("--no-changelog", args.no_changelog),
+ ) if supplied]
+ if conflicting:
+ parser.error("--build-commit cannot be combined with " + ", ".join(conflicting))
+ from scripts.releases.commit_build import cmd_build_commit
+
+ cmd_build_commit(args)
+ return
if args.canary:
cmd_canary(args)
return
diff --git a/scripts/releases/commit_build.py b/scripts/releases/commit_build.py
new file mode 100644
index 00000000000..14148b18d0d
--- /dev/null
+++ b/scripts/releases/commit_build.py
@@ -0,0 +1,122 @@
+"""Admit and dispatch tagless builds without changing release channels."""
+from __future__ import annotations
+
+import json
+import os
+import re
+import shlex
+import subprocess
+import tomllib
+from pathlib import Path
+
+WORKFLOW = "desktop-bundled-release.yml"
+
+
+def require_commit(value: str) -> str:
+ if not isinstance(value, str) or not re.fullmatch(r"[a-f0-9]{40}", value):
+ raise ValueError("Commit builds require an exact full 40-character SHA")
+ return value
+
+
+def output(argv: list[str], repo: Path | None = None) -> str:
+ return subprocess.check_output(argv, cwd=repo, text=True, encoding="utf-8", timeout=60).strip()
+
+
+def require_pushed(commit: str, remote: str, repo: Path | None = None) -> None:
+ """Require ancestry from a branch or tag currently advertised by this remote."""
+ require_commit(commit)
+ advertised = {line.split()[0] for line in output(
+ ["git", "ls-remote", remote, "refs/heads/*", "refs/tags/*"], repo).splitlines()}
+ containing = set(output(["git", "for-each-ref", f"--contains={commit}", "--format=%(objectname)",
+ f"refs/remotes/{remote}/", "refs/tags/"], repo).splitlines())
+ if not advertised.intersection(containing):
+ raise ValueError(f"Commit {commit} is not reachable from a pushed branch or tag on {remote}")
+
+
+def version_at(repo: Path | None, commit: str) -> str:
+ require_commit(commit)
+ document = tomllib.loads(output(["git", "show", f"{commit}:pyproject.toml"], repo))
+ version = document["project"]["version"]
+ if not isinstance(version, str) or not re.fullmatch(r"(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)", version):
+ raise ValueError("Commit packaging requires project.version=X.Y.Z")
+ return version
+
+
+def admit(env: dict[str, str]) -> dict[str, str]:
+ commit = require_commit(env.get("BUILD_COMMIT", ""))
+ if env.get("TAG") or env.get("RELEASE_PHASE") or env.get("UPLOAD_RELEASE", "false") != "false":
+ raise ValueError("Commit builds cannot use tag, release-phase or upload_release")
+ if env.get("TERMUX_UPGRADE_FROM_TAG"):
+ raise ValueError("Commit builds do not run release-channel upgrade acceptance")
+ default = env.get("DEFAULT_BRANCH", "")
+ ref = f"refs/heads/{default}"
+ repository = env.get("GITHUB_REPOSITORY", "")
+ expected_workflow = f"{repository}/.github/workflows/{WORKFLOW}@{ref}"
+ if (not default or not repository or env.get("GITHUB_EVENT_NAME") != "workflow_dispatch"
+ or env.get("GITHUB_REF") != ref or env.get("GITHUB_WORKFLOW_REF") != expected_workflow):
+ raise ValueError("Commit builds require workflow_dispatch from the repository default-branch workflow")
+ actors = {env.get("GITHUB_ACTOR", ""), env.get("GITHUB_TRIGGERING_ACTOR") or env.get("GITHUB_ACTOR", "")}
+ for actor in actors:
+ if not actor:
+ raise ValueError("Commit builds require a repository maintainer")
+ permission = output(["gh", "api", f"repos/{repository}/collaborators/{actor}/permission", "--jq", ".permission"])
+ if permission not in {"write", "maintain", "admin"}:
+ raise ValueError("Commit builds require repository write, maintain or admin permission")
+ require_pushed(commit, "origin")
+ return {"sha": commit, "channel": "commit", "payload-version": version_at(None, commit)}
+
+
+def resolve_revision(rev: str, remote: str, repo: Path) -> str:
+ if not isinstance(rev, str) or not rev or rev.startswith("-"):
+ raise ValueError("Commit builds require a Git revision")
+ output(["git", "fetch", "--quiet", remote], repo)
+ commit = require_commit(output(["git", "rev-parse", "--verify", "--end-of-options", f"{rev}^{{commit}}"], repo))
+ require_pushed(commit, remote, repo)
+ return commit
+
+
+def dispatch_command(commit: str, repository: str, branch: str) -> list[str]:
+ require_commit(commit)
+ return ["gh", "workflow", "run", WORKFLOW, "--ref", branch, "--repo", repository,
+ "-f", f"build_commit={commit}", "-f", "tag=", "-f", "upload_release=false",
+ "-f", "termux_only=false", "-f", "termux_upgrade_from_tag="]
+
+
+def cmd_build_commit(args) -> None:
+ from scripts import release
+
+ try:
+ remote = release.resolve_push_remote(args.remote)
+ repository = release.remote_github_repo(remote)
+ if not repository:
+ raise ValueError("commit builds require an explicit GitHub remote")
+ commit = resolve_revision(args.build_commit, remote, release.REPO_ROOT)
+ branch = release._default_branch(repository)
+ if not branch:
+ raise ValueError("could not resolve the repository default branch")
+ command = dispatch_command(commit, repository, branch)
+ print(f"Commit: {commit}\nR2: releases/commit/{commit}/\nWorkflow: {repository}@{branch}")
+ print(shlex.join(command))
+ if not args.publish:
+ print("Dry run. Add --publish to dispatch. No tag, release or channel is changed.")
+ return
+ result = subprocess.run(command, cwd=release.REPO_ROOT, capture_output=True, text=True,
+ encoding="utf-8", errors="replace", check=True, timeout=60)
+ print((result.stdout or "").strip() or f"Dispatched commit build {commit}. No release was created.")
+ except (OSError, ValueError, subprocess.SubprocessError) as exc:
+ raise SystemExit(f"release: commit build refused: {exc}") from exc
+
+
+def main() -> None:
+ import sys
+
+ if sys.argv[1:] != ["admit"]:
+ raise SystemExit("usage: python -m scripts.releases.commit_build admit")
+ values = admit(dict(os.environ))
+ with Path(os.environ["GITHUB_OUTPUT"]).open("a", encoding="utf-8") as stream:
+ stream.write("".join(f"{key}={value}\n" for key, value in values.items()))
+ print(json.dumps(values, sort_keys=True))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/write_install_stamp.py b/scripts/write_install_stamp.py
index 6b0abf2f1b4..23f10b51d9a 100644
--- a/scripts/write_install_stamp.py
+++ b/scripts/write_install_stamp.py
@@ -149,7 +149,7 @@ def build_stamp(
) -> dict:
"""Build a stamp dict from explicit args, filling gaps from git/env.
- Args override detection — an explicit ``commit`` is used directly.
+ Args override detection except for commit-build checkout verification.
``source`` identifies where the stamp came from (``ci``, ``local``,
``docker``, ``nix``, ``fallback``). ``update_mechanism`` is required:
every stamp names who applies the next update (see UPDATE_MECHANISMS).
@@ -172,7 +172,18 @@ def build_stamp(
if base_version is None:
base_version = _base_version
- # Commit: explicit > CI env > git
+ commit_build = os.environ.get("HERMES_BUILD_COMMIT")
+ if commit_build:
+ from scripts.releases.commit_build import require_commit
+
+ require_commit(commit_build)
+ if os.environ.get("HERMES_PAYLOAD_TAG"):
+ raise ValueError("Commit builds cannot also select a release tag")
+ if _resolve_commit_from_git() != commit_build or commit not in (None, commit_build):
+ raise ValueError("Commit build identity does not match the checkout HEAD")
+ commit, source, update_mechanism = commit_build, "commit-build", "external"
+
+ # A dispatch SHA describes workflow code, not an admitted build checkout.
if commit is None:
commit = _resolve_commit_from_env()
source = "ci" if commit else source
@@ -184,9 +195,11 @@ def build_stamp(
source = "fallback"
# Branch: explicit > CI env > git
- if branch is None:
+ if commit_build:
+ branch = None
+ elif branch is None:
branch = _resolve_branch_from_env()
- if branch is None:
+ if branch is None and not commit_build:
branch = _resolve_branch_from_git()
# Dirty: explicit > git
@@ -221,8 +234,7 @@ def build_stamp(
# different MSIX packaging identity. Stamps as 'bundled'
# so the bundled shape logic (shared userData, steward-
# owned updates, no in-app updater) holds for it too.
- # bundled, light and store all pin a release tag: electron-updater keys on
- # it, so a tagless artifact of either kind cannot update itself.
+ # Release artifacts pin a tag. Commit builds never enter an update channel.
variant = os.environ.get("HERMES_DESKTOP_VARIANT", "").strip()
if variant not in ("", "bootstrap", "bundled", "light", "store"):
raise SystemExit(
@@ -231,13 +243,9 @@ def build_stamp(
)
payload = "bundled" if variant == "store" else (variant or "bootstrap")
tag = os.environ.get("HERMES_PAYLOAD_TAG") or None
- # Stable (vX.Y.Z) and canary (vX.Y.<any patch>-canary.<YYYYMMDDHHMMSS>,
- # or the legacy date-only shape) tags are both release-feed keys; anything
- # else cannot update itself and refuses. The canary shape is validated by
- # hermes_cli.update_channel — the single authority — so it accepts the
- # patch+1 form scripts/release.py's canary_tag_for_date produces.
+
_stable_tag = re.compile(r"^v(0|[1-9]\d{0,2})\.\d+\.\d+$")
- if payload != "bootstrap" and not (
+ if payload != "bootstrap" and not commit_build and not (
tag and (_stable_tag.match(tag) or update_channel.is_canary_tag(tag))
):
raise SystemExit(
diff --git a/tests/scripts/test_commit_stamp_identity.py b/tests/scripts/test_commit_stamp_identity.py
new file mode 100644
index 00000000000..cc6ea0823fd
--- /dev/null
+++ b/tests/scripts/test_commit_stamp_identity.py
@@ -0,0 +1,70 @@
+"""The Python stamp writer binds tagless identity to the built checkout."""
+import json
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import sys
+
+
+ROOT = Path(__file__).resolve().parents[2]
+
+
+def test_stamp_uses_built_commit_even_with_dispatch_sha_and_refuses_mismatch(tmp_path):
+ repo = tmp_path / 'repo'
+ repo.mkdir()
+ for relative in ('scripts/write_install_stamp.py', 'scripts/releases/commit_build.py',
+ 'hermes_cli/__init__.py', 'hermes_cli/update_channel.py',
+ 'hermes_cli/runtime_paths.py', 'hermes_cli/steward.py', 'hermes_constants.py'):
+ dest = repo / relative
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(ROOT / relative, dest)
+
+ def git(*args):
+ return subprocess.run(['git', *args], cwd=repo, check=True, capture_output=True,
+ text=True, encoding='utf-8', timeout=30).stdout.strip()
+
+ git('init', '-q', '-b', 'main')
+ git('config', 'user.name', 'Fixture')
+ git('config', 'user.email', '[email protected]')
+ git('add', '.')
+ git('commit', '-qm', 'main')
+ main = git('rev-parse', 'HEAD')
+ git('checkout', '-qb', 'feature')
+ (repo / 'feature').write_text('feature\n', encoding='utf-8')
+ git('add', 'feature')
+ git('commit', '-qm', 'feature')
+ feature = git('rev-parse', 'HEAD')
+ out = tmp_path / 'stamp.json'
+ env = {k: v for k, v in os.environ.items() if not k.startswith(('GITHUB_', 'HERMES_BUILD_', 'HERMES_PAYLOAD_'))}
+ env.update({'GITHUB_SHA': main, 'GITHUB_REF_NAME': 'main',
+ 'HERMES_BUILD_COMMIT': feature, 'HERMES_DESKTOP_VARIANT': 'bundled',
+ 'HERMES_HOME': str(tmp_path / 'home')})
+ command = [sys.executable, '-I', '-S', str(repo / 'scripts/write_install_stamp.py'),
+ '--output', str(out), '--update-mechanism', 'app-installer']
+
+ def run(*args, override=None):
+ return subprocess.run([*command, *args], cwd=tmp_path, env={**env, **(override or {})},
+ capture_output=True, text=True, encoding='utf-8', timeout=30)
+
+ result = run()
+ assert result.returncode == 0, result.stderr
+ data = json.loads(out.read_text(encoding='utf-8'))
+ assert data['commit'] == feature and data['source'] == 'commit-build'
+ assert data['branch'] is None and data['tag'] is None and data['updateMechanism'] == 'external'
+ result = run('--commit', feature)
+ assert result.returncode == 0, result.stderr
+ before = out.read_bytes()
+ git('checkout', '-q', 'main')
+ for args in ((), ('--commit', feature)):
+ result = run(*args)
+ assert result.returncode != 0 and 'checkout' in result.stderr.lower()
+ assert out.read_bytes() == before
+ git('checkout', '-q', 'feature')
+ for extra in ({'HERMES_BUILD_COMMIT': feature[:8]}, {'HERMES_PAYLOAD_TAG': 'v1.2.3'},
+ {'HERMES_BUILD_COMMIT': ' ' + feature}):
+ assert run(override=extra).returncode != 0
+ assert out.read_bytes() == before
+ result = run('--commit', feature, override={'HERMES_BUILD_COMMIT': '', 'HERMES_PAYLOAD_TAG': 'v1.2.3'})
+ assert result.returncode == 0, result.stderr
+ assert json.loads(out.read_text(encoding='utf-8'))['tag'] == 'v1.2.3'
diff --git a/tests/scripts/test_release_build_commit.py b/tests/scripts/test_release_build_commit.py
new file mode 100644
index 00000000000..57d79d93855
--- /dev/null
+++ b/tests/scripts/test_release_build_commit.py
@@ -0,0 +1,169 @@
+"""Commit-build entry points resolve real Git refs without publishing releases."""
+import json
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import sys
+
+from scripts.releases import commit_build
+
+ROOT = Path(__file__).resolve().parents[2]
+
+
+def git(repo, *args):
+ return subprocess.run(['git', *args], cwd=repo, check=True, capture_output=True,
+ text=True, encoding='utf-8', timeout=30).stdout.strip()
+
+
+def fixture_repo(tmp_path):
+ upstream = tmp_path / 'upstream.git'
+ subprocess.run(['git', 'init', '--bare', '-q', '-b', 'main', str(upstream)], check=True)
+ repo = tmp_path / 'repo'
+ subprocess.run(['git', 'clone', '-q', str(upstream), str(repo)], check=True)
+ git(repo, 'config', 'user.name', 'Fixture')
+ git(repo, 'config', 'user.email', '[email protected]')
+ (repo / 'pyproject.toml').write_text('[project]\nname="fixture"\nversion="1.2.3"\n', encoding='utf-8')
+ git(repo, 'add', 'pyproject.toml')
+ git(repo, 'commit', '-qm', 'fixture')
+ git(repo, 'push', '-q', 'origin', 'main')
+ git(repo, 'remote', 'set-url', 'origin', 'https://github.com/fixture-owner/fixture-repo.git')
+ for relative in ('scripts/release.py', 'scripts/releases/commit_build.py',
+ 'hermes_cli/__init__.py', 'hermes_cli/update_channel.py',
+ 'hermes_cli/runtime_paths.py', 'hermes_constants.py'):
+ dest = repo / relative
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(ROOT / relative, dest)
+ driver = tmp_path / 'drive.py'
+ driver.write_text('''import json, os, pathlib, runpy, subprocess, sys
+root = pathlib.Path(sys.argv[1])
+sys.path.insert(0, str(root))
+actual = subprocess.run
+calls = pathlib.Path(os.environ['PROBE_CALLS'])
+def run(argv, *args, **kwargs):
+ if argv and argv[0] == 'gh':
+ with calls.open('a', encoding='utf-8') as stream:
+ stream.write(json.dumps(argv) + '\\n')
+ if os.environ.get('PROBE_GH_MISSING'):
+ raise FileNotFoundError('fixture gh is absent')
+ if argv[1:3] == ['repo', 'view']:
+ assert '--repo' not in argv, 'gh repo view requires a positional repository'
+ assert 'fixture-owner/fixture-repo' in argv
+ value = 'main\\n'
+ elif argv[1:3] == ['workflow', 'run']:
+ value = 'fixture dispatch accepted\\n'
+ elif argv[1] == 'api':
+ value = os.environ.get('PROBE_PERMISSION', 'write') + '\\n'
+ else:
+ raise AssertionError(argv)
+ return subprocess.CompletedProcess(argv, 0, stdout=value, stderr='')
+ assert argv and argv[0] == 'git', f'unexpected external command: {argv}'
+ assert pathlib.Path(kwargs.get('cwd') or pathlib.Path.cwd()).resolve() == root.resolve()
+ if argv[1] in ('fetch', 'ls-remote'):
+ # Only the transport points at a local fixture. Identity reads stay real.
+ rewrite = 'url.' + os.environ['PROBE_REMOTE'] + '.insteadOf=https://github.com/fixture-owner/fixture-repo.git'
+ argv = ['git', '-c', rewrite, *argv[1:]]
+ return actual(argv, *args, **kwargs)
+subprocess.run = run
+if sys.argv[2] == 'admit':
+ sys.argv = ['commit_build.py', 'admit']
+ runpy.run_module('scripts.releases.commit_build', run_name='__main__')
+else:
+ sys.argv = ['release.py', *sys.argv[2:]]
+ runpy.run_path(str(root / 'scripts/release.py'), run_name='__main__')
+''', encoding='utf-8')
+ calls = tmp_path / 'gh.jsonl'
+ env = {k: v for k, v in os.environ.items() if not k.startswith(('GITHUB_', 'GH_'))}
+ env.update({'PROBE_CALLS': str(calls), 'PROBE_REMOTE': upstream.as_uri(), 'GIT_ALLOW_PROTOCOL': 'file',
+ 'GIT_TERMINAL_PROMPT': '0', 'HERMES_HOME': str(tmp_path / 'home')})
+
+ def invoke(*args, extra=None):
+ calls.unlink(missing_ok=True)
+ result = subprocess.run([sys.executable, '-I', '-S', str(driver), str(repo), *args],
+ cwd=repo, env={**env, **(extra or {})}, capture_output=True,
+ text=True, encoding='utf-8', timeout=45)
+ recorded = [json.loads(line) for line in calls.read_text(encoding='utf-8').splitlines()] if calls.exists() else []
+ return result, recorded
+
+ return repo, upstream, invoke
+
+
+def test_commit_build_cli_dispatches_only_the_resolved_remote_commit(tmp_path):
+ repo, upstream, invoke = fixture_repo(tmp_path)
+ tip = git(repo, 'rev-parse', 'HEAD')
+ before = git(repo, 'show-ref', '--heads', '--tags')
+ for revision in (tip[:8], 'main'):
+ result, calls = invoke('--build-commit', revision)
+ assert result.returncode == 0, result.stderr
+ assert f'Commit: {tip}' in result.stdout and f'releases/commit/{tip}/' in result.stdout
+ assert not any(call[1:3] == ['workflow', 'run'] for call in calls)
+ result, calls = invoke('--build-commit', tip, '--publish')
+ assert result.returncode == 0, result.stderr
+ dispatches = [call for call in calls if call[1:3] == ['workflow', 'run']]
+ assert dispatches == [commit_build.dispatch_command(tip, 'fixture-owner/fixture-repo', 'main')]
+ assert f'build_commit={tip}' in dispatches[0] and 'upload_release=false' in dispatches[0]
+ assert git(repo, 'show-ref', '--heads', '--tags') == before
+ assert git(upstream, 'rev-parse', 'refs/heads/main') == tip
+
+ git(repo, 'checkout', '-qb', 'feature')
+ (repo / 'feature').write_text('pushed feature', encoding='utf-8')
+ git(repo, 'add', 'feature')
+ git(repo, 'commit', '-qm', 'feature')
+ feature = git(repo, 'rev-parse', 'HEAD')
+ git(repo, 'tag', '-a', 'fixture-tag', '-m', 'fixture')
+ git(repo, 'push', '-q', str(upstream), 'feature', 'refs/tags/fixture-tag')
+ git(repo, 'checkout', '-q', 'main')
+ for revision in (feature[:8], 'origin/feature', 'fixture-tag'):
+ result, calls = invoke('--build-commit', revision)
+ assert result.returncode == 0, result.stderr
+ assert f'Commit: {feature}' in result.stdout
+ assert git(repo, 'rev-parse', 'HEAD') == tip
+ assert not any(call[1:3] == ['workflow', 'run'] for call in calls)
+
+ for flags in (['--bump', 'patch'], ['--canary'], ['--first-release'], ['--prune-canaries'],
+ ['--date', '2026.1.1'], ['--output', str(tmp_path / 'no-output')], ['--no-changelog']):
+ result, calls = invoke('--build-commit', tip, *flags)
+ assert result.returncode == 2 and not calls, result.stderr
+ assert not (tmp_path / 'no-output').exists()
+ for revision in ('', '--all', 'not-a-revision'):
+ result, calls = invoke('--build-commit=' + revision, '--publish')
+ assert result.returncode != 0 and not calls
+ assert 'Traceback' not in result.stderr
+ result, calls = invoke('--build-commit', tip, extra={'PROBE_GH_MISSING': '1'})
+ assert result.returncode != 0 and 'Traceback' not in result.stderr
+ (repo / 'local-only').write_text('not pushed', encoding='utf-8')
+ git(repo, 'add', 'local-only')
+ git(repo, 'commit', '-qm', 'local only')
+ result, calls = invoke('--build-commit', 'HEAD', '--publish')
+ assert result.returncode != 0 and 'not reachable' in result.stderr and not calls
+ for url in (str(tmp_path / 'github.com/owner/repo'), 'https://notgithub.com/owner/repo',
+ 'https://github.com/owner/repo/extra'):
+ git(repo, 'remote', 'set-url', 'origin', url)
+ result, calls = invoke('--build-commit', tip)
+ assert result.returncode != 0 and 'GitHub remote' in result.stderr and not calls
+
+
+def test_workflow_admission_checks_trust_before_publishing_outputs(tmp_path):
+ repo, _, invoke = fixture_repo(tmp_path)
+ tip = git(repo, 'rev-parse', 'HEAD')
+ output = tmp_path / 'output'
+ env = {'BUILD_COMMIT': tip, 'DEFAULT_BRANCH': 'main',
+ 'GITHUB_REPOSITORY': 'fixture-owner/fixture-repo', 'GITHUB_EVENT_NAME': 'workflow_dispatch',
+ 'GITHUB_REF': 'refs/heads/main',
+ 'GITHUB_WORKFLOW_REF': 'fixture-owner/fixture-repo/.github/workflows/desktop-bundled-release.yml@refs/heads/main',
+ 'GITHUB_ACTOR': 'maintainer', 'GITHUB_TRIGGERING_ACTOR': 'maintainer',
+ 'GITHUB_OUTPUT': str(output), 'UPLOAD_RELEASE': 'false'}
+ result, calls = invoke('admit', extra=env)
+ assert result.returncode == 0, result.stderr
+ assert dict(line.split('=', 1) for line in output.read_text(encoding='utf-8').splitlines()) == {
+ 'sha': tip, 'channel': 'commit', 'payload-version': '1.2.3'}
+ assert calls and all(call[1] == 'api' for call in calls)
+ original = output.read_bytes()
+ for key, value in [('BUILD_COMMIT', tip[:8]), ('TAG', 'v1.2.3'), ('UPLOAD_RELEASE', 'true'),
+ ('RELEASE_PHASE', 'candidate'), ('TERMUX_UPGRADE_FROM_TAG', 'v1.0.0'),
+ ('GITHUB_EVENT_NAME', 'workflow_call'), ('GITHUB_REF', 'refs/heads/other'),
+ ('GITHUB_WORKFLOW_REF', 'fixture-owner/fixture-repo/.github/workflows/other.yml@refs/heads/main'),
+ ('PROBE_PERMISSION', 'read')]:
+ result, _ = invoke('admit', extra={**env, key: value})
+ assert result.returncode != 0
+ assert output.read_bytes() == original
diff --git a/tests/scripts/test_release_tags.py b/tests/scripts/test_release_tags.py
index c5da4e29138..08ddabccb06 100644
--- a/tests/scripts/test_release_tags.py
+++ b/tests/scripts/test_release_tags.py
@@ -2,6 +2,7 @@
import importlib.util
from pathlib import Path
+import subprocess
import pytest
@@ -79,18 +80,23 @@ def test_no_remotes_is_rejected(monkeypatch):
release.resolve_push_remote(None)
-def test_github_repo_parsed_from_ssh_and_https_urls(monkeypatch):
+def test_github_repo_parsed_from_ssh_and_https_urls(tmp_path, monkeypatch):
+ subprocess.run(['git', 'init', '-q', str(tmp_path)], check=True)
+ monkeypatch.setattr(release, 'REPO_ROOT', tmp_path)
urls = {
"fork": "[email protected]:ethernet8023/hermes-agent.git",
"origin": "https://github.com/NousResearch/hermes-agent",
"gitlab": "[email protected]:someone/elsewhere.git",
}
- monkeypatch.setattr(
- release,
- "git_result",
- lambda *args, **_kw: _FakeResult(urls[args[-1]]),
- )
+ for name, url in urls.items():
+ subprocess.run(['git', 'config', f'remote.{name}.url', url], cwd=tmp_path, check=True)
assert release.remote_github_repo("fork") == "ethernet8023/hermes-agent"
assert release.remote_github_repo("origin") == "NousResearch/hermes-agent"
assert release.remote_github_repo("gitlab") is None
+ subprocess.run(['git', 'config', 'url.https://github.com/fork/.pushInsteadOf',
+ 'https://github.com/NousResearch/'], cwd=tmp_path, check=True)
+ assert release.remote_github_repo('origin') == 'fork/hermes-agent'
+ subprocess.run(['git', 'config', 'remote.origin.pushurl', 'ssh://[email protected]:22/other/repo.git'],
+ cwd=tmp_path, check=True)
+ assert release.remote_github_repo('origin') == 'other/repo'