From e8edc37aaf794c8090a0edd908b83feaf0c5bf07 Mon Sep 17 00:00:00 2001 From: Offending Commit Date: Mon, 21 Sep 2026 15:37:52 -0500 Subject: [PATCH 1/5] docs(openspec): author the contract-gate change Proposal, design, and tasks for hardening the Hermes contract gates. No spec delta: this alters CI wiring and local task definitions and changes no capability-level requirement, so .openspec.yaml carries skip_specs rather than inventing a requirement to satisfy validation. The design records why each defect looks like success today -- a drift job that cannot fire on drift, a continue-on-error flag that renders green, a local lane that can only reach upstream main, and a Python 3.11 exit status that cannot distinguish a passing suite from a vanished one. --- .../harden-hermes-contract-gates/design.md | 92 +++++++++++++++++++ .../harden-hermes-contract-gates/proposal.md | 61 ++++++++++++ .../harden-hermes-contract-gates/tasks.md | 64 +++++++++++++ 3 files changed, 217 insertions(+) create mode 100644 openspec/changes/harden-hermes-contract-gates/design.md create mode 100644 openspec/changes/harden-hermes-contract-gates/proposal.md create mode 100644 openspec/changes/harden-hermes-contract-gates/tasks.md diff --git a/openspec/changes/harden-hermes-contract-gates/design.md b/openspec/changes/harden-hermes-contract-gates/design.md new file mode 100644 index 0000000..a298957 --- /dev/null +++ b/openspec/changes/harden-hermes-contract-gates/design.md @@ -0,0 +1,92 @@ +## Context + +Four defects sit in the current wiring, and three of them look like success. + +`.github/workflows/test.yml` triggers only on `push` and `pull_request`. The +drift job therefore runs on this repository's activity and never on Hermes'. +Job-level `continue-on-error: true` additionally makes it render green in the +checks list, so even when it does run and fail, the signal reads as a pass. + +`justfile`'s `prepare-hermes-agent` clones the default branch with no ref +support, so the pinned revision is unreachable outside CI — `just test-contract` +can only ever test upstream main. Both contract recipes resolve to the same +directory, and the recipe swallows the pull error a detached checkout leaves +behind, so an upstream run after a pinned one silently re-exercises the pin. + +And the pinned gate covers `tests.test_context_engine_contract` only. The full +suite is green at `f80f453` — verified by running it there — so widening the job +adds coverage rather than risk on the day it lands. + +## Goals / Non-Goals + +**Goals:** + +- A blocking gate whose green means the whole contract holds at the pin. +- A drift lane that fires when Hermes moves, is honestly red, and distinguishes + a new break from the known one. +- A local lane that can target the pin and never reports success for a run that + checked nothing. + +**Non-Goals:** + +- Fixing the #99220 relay-egress break. It is the motivating evidence; making it + visible is this change's job, and repairing it is a separate objective. +- Promoting the deployed pin past `f80f453`. +- A tracking-issue lifecycle for the drift lane. The requirement asks for a + visible record, which a job summary plus an honestly-red workflow provides; an + issue manager is stateful, needs a permission the workflow lacks, and is + deferred until the lane has proven it fires. + +## Decisions + +**A separate scheduled workflow, not a repaired flag.** Fixing +`continue-on-error` would leave the lane triggering on the wrong event. A +workflow on `schedule` plus `workflow_dispatch`, outside required checks and +carrying no `continue-on-error`, fires on the right event and cannot mislead the +PR checks list — while still being non-blocking, since a workflow that is not a +required check cannot block a merge. Daily, so the worst-case detection lag is a +stated 24 hours rather than an unspecified hope. + +**The workflow keeps a pin literal; a test enforces agreement.** The workflow +cannot read the harness constant: `actions/checkout` consumes the `ref:` before +`setup-uv` installs Python, so a dynamic read would mean reordering the job to +install a toolchain ahead of the host checkout. Test-enforced agreement gets the +same single-source-of-truth property through the route the release-contract +tests already own. + +**Assert the executed-test count, not the exit status.** On Python 3.11 — +pinned in CI — `unittest` exits 0 both when every test skips and when zero tests +are collected; exit 5 arrives only in 3.12. So "the gate passed" and "the gate +ran" are indistinguishable from the status alone. + +**The guard needs an intent signal.** A test outside `skipUnless` cannot tell an +intended contract run from an ordinary one. Without a signal it either reddens +the blocking job on every push — that job checks out no Hermes revision and +`just test` discovers both contract modules — or never fires. The contract +recipes set the signal; a bare `just test` stays green and claims no contract +coverage. + +**Baseline on failure fingerprints, not test names.** A baselined test whose +assertion or error has changed is a new break wearing a known name. Matching on +names alone would file it as expected. + +## Risks / Trade-offs + +- A scheduled workflow on a public repository is auto-disabled after 60 days of + inactivity, so the alarm can switch itself off in exactly the quiet period it + guards. An activity trigger alongside the schedule mitigates it; it does not + eliminate it, and that residue is accepted rather than solved here. +- The drift lane launches knowingly red, because #99220 stays out of scope. The + baseline is what keeps that from training people to ignore it. +- Widening the blocking gate means any contract the job previously ignored can + now fail the build. That is the point, and the suite is green at the pin + today, but it does remove a hiding place. + +## Migration + +None. CI wiring and local recipes only; no consumer-visible API changes. + +## Open Questions + +- Whether the drift lane should eventually block once #99220 is resolved and the + baseline is empty. Not decided here; the settled position is non-blocking. diff --git a/openspec/changes/harden-hermes-contract-gates/proposal.md b/openspec/changes/harden-hermes-contract-gates/proposal.md new file mode 100644 index 0000000..4928b56 --- /dev/null +++ b/openspec/changes/harden-hermes-contract-gates/proposal.md @@ -0,0 +1,61 @@ +## Why + +The gate that blocks covers a tenth of the contract, and the lane that would +warn about upstream drift cannot fire on drift at all. + +The blocking job runs only `tests.test_context_engine_contract` — 110 lines of +an 853-line suite — against the deployed pin, even though the full suite is +green there. The upstream-drift job triggers on `push` and `pull_request`, so it +runs when this repository changes and never when Hermes moves, which is the only +event it exists to detect. Job-level `continue-on-error: true` compounds that by +rendering it green in the checks list rather than visibly amber. + +Locally the picture is worse. `just test` auto-discovers `~/hermes-agent`, so it +silently exercises whatever branch a developer happens to have checked out, +while CI has no checkout and skips the module entirely — the same command +meaning two different things. And on Python 3.11, the version CI pins, +`unittest` exits 0 both when every test skips and when zero tests are collected, +so a contract lane that vanished is indistinguishable from one that passed. + +Hermes #99220 is the live proof: it broke the kit's media contract against +upstream on 2026-09-21 and nothing reported it. + +## What Changes + +- The blocking pinned job runs the full contract suite instead of the + context-engine module alone. +- The pin becomes one literal, test-enforced against the constant the harness + ships, instead of two copies that agree with nothing. +- The upstream-drift lane moves to its own scheduled workflow: daily, outside + required checks, no `continue-on-error`, so red is honestly red. +- Drift reporting names the revision and the failing tests, and separates + failures already known from genuinely new ones. +- The local lane can target the pin, reports the revision and executed-test + count, and refuses rather than reporting success when it checked nothing. +- Both contract modules resolve a host by one policy instead of two. + +## Capabilities + +### New Capabilities + + + +### Modified Capabilities + + + +## Impact + +- `.github/workflows/test.yml` — blocking job widened, drift job removed. +- `.github/workflows/hermes-drift.yml` — new scheduled lane. +- `tests/fixtures/known-hermes-drift.txt` — the baseline that keeps the known + #99220 failure from drowning a new one. +- `justfile` — pin-aware and upstream contract recipes, separate checkout + directories, an intent signal so a bare `just test` stays honest. +- `tests/test_hermes_contract.py`, `tests/test_context_engine_contract.py` — + one discovery policy, plus a guard outside `skipUnless`. +- `tests/test_release_contract.py` — asserts the new workflow shape. +- No change to `deliver_media`. The #99220 break stays out of scope; this + change makes it visible, not fixed. diff --git a/openspec/changes/harden-hermes-contract-gates/tasks.md b/openspec/changes/harden-hermes-contract-gates/tasks.md new file mode 100644 index 0000000..a4beb39 --- /dev/null +++ b/openspec/changes/harden-hermes-contract-gates/tasks.md @@ -0,0 +1,64 @@ +## 1. Pin-aware local lane with one discovery policy (U5) + +- [ ] 1.1 Teach the checkout preparation step to check out a requested ref. + Verify: the pinned revision is reachable locally, where today only the + default branch is. +- [ ] 1.2 Give the pin recipe and the upstream recipe separate checkout + directories. Verify: running upstream after pinned exercises upstream, not + the pin left behind by the previous run. +- [ ] 1.3 Consolidate both contract modules onto one discovery policy — an + explicit path is authoritative and re-raises, absence is explicit. Verify: + the same bad path produces the same refusal from each module. +- [ ] 1.4 For any pin-targeted run, compare the resolved checkout's HEAD against + the pin and refuse on mismatch. Verify: a stale path naming a different + revision is refused with expected and actual, rather than receipting the + wrong host. +- [ ] 1.5 Emit a receipt naming the revision exercised and the executed-test + count, capturing the exit status directly rather than through a pipe. + Verify: the receipt names both, and a filtered pipeline cannot supply the + pass/fail signal. +- [ ] 1.6 Add a guard outside each module's `skipUnless`, firing only when the + contract recipes set an intent signal. Verify: a bare `just test` with no + host stays green, while an invoked contract lane that cannot resolve a + host fails. +- [ ] 1.7 Make the context-engine recipe require an explicit checkout path. + Verify: with the variable unset the recipe refuses instead of skipping. +- [ ] 1.8 Prove the all-skipped and zero-collected cases fail. Verify: both are + reported as failures, which is the pair Python 3.11 exits 0 on. + +## 2. Blocking gate and scheduled drift lane (U6) + +- [ ] 2.1 Point the blocking pinned job at the full contract suite. Verify: it + passes at the pin and the suite it runs is the whole module, not the + context-engine one. +- [ ] 2.2 Collapse the two pin literals to one. Verify: the workflow names the + pin exactly once. +- [ ] 2.3 Move the drift lane into its own workflow on a daily schedule plus + manual dispatch, outside required checks, with no `continue-on-error`. + Verify: a manual dispatch runs, and a failure is visibly red without + affecting any required check. +- [ ] 2.4 Report the upstream revision and failing tests to the run summary, on + a step that runs even after the contract step fails. Verify: a failing + dispatch still produces the summary, rather than skipping the step that + reports the failure. +- [ ] 2.5 Add the known-drift baseline and classify failures against it by + fingerprint. Verify: the #99220 media failure is labelled known, and an + unrecognized failure appears under its own heading. +- [ ] 2.6 Add an activity trigger alongside the schedule. Verify: the workflow + has a trigger other than the clock, so 60 days of quiet cannot silently + disable the alarm. + +## 3. Workflow shape held by the release contract (U7) + +- [ ] 3.1 Assert the blocking job selects the full contract suite. Verify: + reducing it back to the context-engine module fails the test. +- [ ] 3.2 Assert the workflow pin equals the harness constant. Verify: editing + either one alone fails the test. +- [ ] 3.3 Assert the drift workflow keeps its schedule trigger, its + report-on-failure condition, and its baseline file. Verify: removing any + of the three fails the test. +- [ ] 3.4 Assert the built wheel contains the harness module. Verify: dropping + it from the packaging manifest fails this test where `twine check` passes. +- [ ] 3.5 Confirm the existing SHA-pinning, just-only, and + `pull_request_target` assertions still hold for the new workflow. Verify: + the release-contract suite passes with both workflows present. From 2be53d6777d0cd6a913be7911af2bba35a1a5040 Mon Sep 17 00:00:00 2001 From: Offending Commit Date: Mon, 21 Sep 2026 15:45:41 -0500 Subject: [PATCH 2/5] feat(ci): one discovery policy and an honest local contract lane Three ways a contract run could report success without checking anything, all closed. Discovery consolidates into tests/_hermes_host.py. Nothing is auto-discovered any more: the old ~/hermes-agent fallback is what made a bare `just test` exercise whatever branch a developer had checked out while CI, which checks out nothing, skipped the module entirely. A named path stays authoritative and still raises on a bad one. Absence is only tolerated when nobody asked for a contract run. The recipes set HERMES_CONTRACT_REQUIRED, and a guard outside skipUnless fails when that signal is present and no host resolved. Without the signal the guard could only redden every push -- the blocking job checks out no Hermes revision and discovers both contract modules -- or never fire at all. Pin-targeted runs compare HEAD against the revision they claim, so a stale HERMES_AGENT_PATH is refused rather than receipting the wrong host. The suite runner asserts the executed-test count, because on Python 3.11 the exit status cannot distinguish a passing run from a vanished one. Verified against all three shapes: zero-collected refused, all-skipped refused, a genuine 16-test run accepted. Pinned and upstream lanes get separate checkout directories. Sharing one left a detached HEAD behind and the old `pull --ff-only || true` swallowed the error, so an upstream run silently re-tested the pin. Receipts observed: pinned f80f453 executed=16; upstream a6bab19 fails on the known #99220 media contract, naming the revision. --- justfile | 94 ++++++++++--- .../harden-hermes-contract-gates/tasks.md | 16 +-- tests/_hermes_host.py | 126 ++++++++++++++++++ tests/test_context_engine_contract.py | 17 ++- tests/test_hermes_contract.py | 49 +++---- 5 files changed, 241 insertions(+), 61 deletions(-) create mode 100644 tests/_hermes_host.py diff --git a/justfile b/justfile index 6076f06..93cab96 100644 --- a/justfile +++ b/justfile @@ -4,7 +4,8 @@ uv := env_var_or_default("UV", "uv") openspec := env_var_or_default("OPENSPEC", "openspec") openspec_min := "1.13.1" hermes_agent_repo := env_var_or_default("HERMES_AGENT_REPO", "https://github.com/NousResearch/hermes-agent.git") -hermes_agent_dir := env_var_or_default("HERMES_AGENT_DIR", ".hermes-agent") +hermes_pinned_dir := env_var_or_default("HERMES_PINNED_DIR", ".hermes-agent-pinned") +hermes_upstream_dir := env_var_or_default("HERMES_UPSTREAM_DIR", ".hermes-agent-upstream") # Show available recipes. default: @@ -37,32 +38,91 @@ release-attach-trigger: test "$(git branch --show-current)" = "main" test "$(git rev-parse HEAD)" = "$EXPECTED_SHA" -# Prepare a local Hermes checkout unless the caller supplied one. +# Check out hermes-agent at a given ref, in a directory of its own. +# +# Each ref gets its own directory. Sharing one meant a pinned checkout left a +# detached HEAD behind, and the next upstream run's `pull --ff-only || true` +# swallowed the resulting error -- so it silently re-tested the pin while +# reporting upstream. [private] -prepare-hermes-agent: +prepare-hermes-ref ref dir: #!/usr/bin/env bash set -euo pipefail - if [[ -n "${HERMES_AGENT_PATH:-}" ]]; then - exit 0 - elif [[ -d "{{ hermes_agent_dir }}/.git" ]]; then - echo "Updating {{ hermes_agent_dir }}" - git -C "{{ hermes_agent_dir }}" pull --ff-only -q || true + if [[ -d "{{ dir }}/.git" ]]; then + git -C "{{ dir }}" fetch -q --depth 1 origin "{{ ref }}" else - echo "Cloning hermes-agent into {{ hermes_agent_dir }}" - git clone --depth 1 "{{ hermes_agent_repo }}" "{{ hermes_agent_dir }}" + echo "Cloning hermes-agent into {{ dir }}" + git init -q "{{ dir }}" + git -C "{{ dir }}" remote add origin "{{ hermes_agent_repo }}" + git -C "{{ dir }}" fetch -q --depth 1 origin "{{ ref }}" fi + git -C "{{ dir }}" checkout -q FETCH_HEAD + echo "hermes-agent at $(git -C "{{ dir }}" rev-parse HEAD)" -# Run contract tests against an existing or locally managed Hermes checkout. -test-contract: prepare-hermes-agent +# Run the full contract suite against the deployed pin. +# +# HERMES_EXPECTED_REVISION makes the lane refuse a checkout at any other +# revision, so a stale HERMES_AGENT_PATH cannot receipt the wrong host. +test-contract-pinned: #!/usr/bin/env bash set -euo pipefail - hermes_path="${HERMES_AGENT_PATH:-{{ hermes_agent_dir }}}" - HERMES_AGENT_PATH="$(cd "$hermes_path" && pwd)" \ - {{ uv }} run python -m unittest tests.test_hermes_contract -v + pin="$({{ uv }} run python -c 'from hermes_plugin_kit.testing import DEPLOYED_HERMES_REVISION as r; print(r)')" + dir="${HERMES_AGENT_PATH:-{{ hermes_pinned_dir }}}" + if [[ -z "${HERMES_AGENT_PATH:-}" ]]; then + just prepare-hermes-ref "$pin" "{{ hermes_pinned_dir }}" + fi + HERMES_CONTRACT_REQUIRED=1 HERMES_EXPECTED_REVISION="$pin" \ + HERMES_AGENT_PATH="$(cd "$dir" && pwd)" \ + just _run-contract-suite "pinned $pin" -# Run the context-engine contract against HERMES_AGENT_PATH. +# Run the full contract suite against upstream main -- the drift lane. +test-contract-upstream: + #!/usr/bin/env bash + set -euo pipefail + dir="${HERMES_AGENT_PATH:-{{ hermes_upstream_dir }}}" + if [[ -z "${HERMES_AGENT_PATH:-}" ]]; then + just prepare-hermes-ref main "{{ hermes_upstream_dir }}" + fi + rev="$(git -C "$dir" rev-parse HEAD)" + HERMES_CONTRACT_REQUIRED=1 HERMES_AGENT_PATH="$(cd "$dir" && pwd)" \ + just _run-contract-suite "upstream $rev" + +# Backwards-compatible alias for the upstream lane. +test-contract: test-contract-upstream + +# Run both contract modules and prove the run actually executed checks. +# +# The exit status alone cannot say whether anything ran: on Python 3.11 -- +# the version CI pins -- unittest exits 0 both when every test skips and when +# zero tests are collected. So the executed count is the evidence. +[private] +_run-contract-suite label: + #!/usr/bin/env bash + set -euo pipefail + log="$(mktemp)" + trap 'rm -f "$log"' EXIT + set +e + {{ uv }} run python -m unittest tests.test_hermes_contract tests.test_context_engine_contract -v \ + > "$log" 2>&1 + echo "EXIT=$?" >> "$log" + set -e + tail -25 "$log" + grep -qE '^EXIT=0' "$log" || { echo "contract suite failed ({{ label }})" >&2; exit 1; } + ran="$(grep -oE '^Ran [0-9]+' "$log" | grep -oE '[0-9]+' | head -n1)" + test -n "$ran" && [ "$ran" -gt 0 ] \ + || { echo "no contract tests ran ({{ label }}); a lane that checked nothing is not a lane that passed" >&2; exit 1; } + if grep -qE 'OK \(skipped=' "$log"; then + echo "contract suite skipped tests ({{ label }}); expected a host for every case" >&2 + exit 1 + fi + echo "contract receipt: {{ label }}; executed=$ran" + +# Run the context-engine contract. Requires an explicit checkout. test-context-engine-contract: - {{ uv }} run python -m unittest tests.test_context_engine_contract -v + #!/usr/bin/env bash + set -euo pipefail + : "${HERMES_AGENT_PATH:?set it to a hermes-agent checkout; this lane does not guess}" + HERMES_CONTRACT_REQUIRED=1 {{ uv }} run python -m unittest tests.test_context_engine_contract -v # Refuse to run when the installed OpenSpec predates the archive-correctness fixes. [private] diff --git a/openspec/changes/harden-hermes-contract-gates/tasks.md b/openspec/changes/harden-hermes-contract-gates/tasks.md index a4beb39..0a16c6e 100644 --- a/openspec/changes/harden-hermes-contract-gates/tasks.md +++ b/openspec/changes/harden-hermes-contract-gates/tasks.md @@ -1,29 +1,29 @@ ## 1. Pin-aware local lane with one discovery policy (U5) -- [ ] 1.1 Teach the checkout preparation step to check out a requested ref. +- [x] 1.1 Teach the checkout preparation step to check out a requested ref. Verify: the pinned revision is reachable locally, where today only the default branch is. -- [ ] 1.2 Give the pin recipe and the upstream recipe separate checkout +- [x] 1.2 Give the pin recipe and the upstream recipe separate checkout directories. Verify: running upstream after pinned exercises upstream, not the pin left behind by the previous run. -- [ ] 1.3 Consolidate both contract modules onto one discovery policy — an +- [x] 1.3 Consolidate both contract modules onto one discovery policy — an explicit path is authoritative and re-raises, absence is explicit. Verify: the same bad path produces the same refusal from each module. -- [ ] 1.4 For any pin-targeted run, compare the resolved checkout's HEAD against +- [x] 1.4 For any pin-targeted run, compare the resolved checkout's HEAD against the pin and refuse on mismatch. Verify: a stale path naming a different revision is refused with expected and actual, rather than receipting the wrong host. -- [ ] 1.5 Emit a receipt naming the revision exercised and the executed-test +- [x] 1.5 Emit a receipt naming the revision exercised and the executed-test count, capturing the exit status directly rather than through a pipe. Verify: the receipt names both, and a filtered pipeline cannot supply the pass/fail signal. -- [ ] 1.6 Add a guard outside each module's `skipUnless`, firing only when the +- [x] 1.6 Add a guard outside each module's `skipUnless`, firing only when the contract recipes set an intent signal. Verify: a bare `just test` with no host stays green, while an invoked contract lane that cannot resolve a host fails. -- [ ] 1.7 Make the context-engine recipe require an explicit checkout path. +- [x] 1.7 Make the context-engine recipe require an explicit checkout path. Verify: with the variable unset the recipe refuses instead of skipping. -- [ ] 1.8 Prove the all-skipped and zero-collected cases fail. Verify: both are +- [x] 1.8 Prove the all-skipped and zero-collected cases fail. Verify: both are reported as failures, which is the pair Python 3.11 exits 0 on. ## 2. Blocking gate and scheduled drift lane (U6) diff --git a/tests/_hermes_host.py b/tests/_hermes_host.py new file mode 100644 index 0000000..83a670c --- /dev/null +++ b/tests/_hermes_host.py @@ -0,0 +1,126 @@ +"""One discovery policy for every contract lane. + +The two contract modules used to resolve a Hermes checkout differently, and +both ways could report success without checking anything. + +`test_hermes_contract` auto-discovered `~/hermes-agent`, so a bare `just test` +silently exercised whatever branch a developer happened to have checked out, +while CI — which checks out nothing — skipped the module entirely. The same +command meant two different things. `test_context_engine_contract` was env-only +and returned `None` into a silent skip. + +Both are replaced by one policy: + +- ``HERMES_AGENT_PATH`` is authoritative. A path that is not a checkout raises + rather than falling back, because an operator who set it meant it. +- Nothing is auto-discovered. A checkout the caller did not name is never used. +- Absence is only *tolerated* when nobody asked for a contract run. When + ``HERMES_CONTRACT_REQUIRED`` is set, absence is a failure. + +That last rule is what lets the guard exist at all. A test outside +``skipUnless`` cannot otherwise tell an intended contract run from an ordinary +``just test``: without the signal it would either redden every push — the +blocking job checks out no Hermes revision and discovers both contract modules +— or never fire, leaving the honest-receipt requirement unenforced. +""" + +from __future__ import annotations + +import os +import subprocess +import unittest +from pathlib import Path + +#: Set by the contract recipes to say "a contract run was actually asked for". +CONTRACT_REQUIRED_ENV = "HERMES_CONTRACT_REQUIRED" + +#: Set by the pin-targeted recipe to the revision the run claims to exercise. +EXPECTED_REVISION_ENV = "HERMES_EXPECTED_REVISION" + +HOST_PATH_ENV = "HERMES_AGENT_PATH" + + +def contract_required() -> bool: + return bool((os.environ.get(CONTRACT_REQUIRED_ENV) or "").strip()) + + +def host_root() -> Path | None: + """The checkout to test against, or ``None`` when none was named. + + Raises when a path was named and is not a Hermes checkout: turning that + into a skip is how a misconfigured lane becomes a misleading green. + """ + raw = (os.environ.get(HOST_PATH_ENV) or "").strip() + if not raw: + return None + root = Path(raw) + if not (root / "hermes_cli" / "plugins.py").exists(): + raise FileNotFoundError( + f"{HOST_PATH_ENV} has no hermes_cli/plugins.py: {root}" + ) + return root + + +def head_revision(root: Path) -> str | None: + try: + return subprocess.run( + ["git", "-C", str(root), "rev-parse", "HEAD"], + capture_output=True, text=True, check=True, timeout=30, + ).stdout.strip() + except Exception: + return None + + +def revision_mismatch(root: Path) -> str | None: + """Describe a pin-targeted run pointed at the wrong revision, if it is. + + A stale ``HERMES_AGENT_PATH`` otherwise sails through the pin lane and + produces a receipt naming a revision the run did not actually use — and CI + inheriting that variable would go green against an incompatible host. + """ + expected = (os.environ.get(EXPECTED_REVISION_ENV) or "").strip() + if not expected: + return None + actual = head_revision(root) + if actual == expected: + return None + return ( + f"{HOST_PATH_ENV} is at {actual or 'an unreadable revision'} but this lane " + f"claims {expected}; refusing to report a revision the run did not use." + ) + + +def build_guard(module_resolved_host: object, module_name: str) -> type[unittest.TestCase]: + """A test case that stays *outside* the module's ``skipUnless``. + + Every other test in a contract module is skipped when no host resolves, + which on Python 3.11 exits 0 — indistinguishable from passing. This one + cannot be skipped along with them, so an intended-but-unconfigured lane + fails instead of vanishing. + """ + + class ContractLaneGuard(unittest.TestCase): + def test_an_intended_contract_run_actually_resolved_a_host(self) -> None: + if not contract_required(): + self.skipTest( + "no contract run was requested; " + f"set {CONTRACT_REQUIRED_ENV} to require one" + ) + self.assertIsNotNone( + module_resolved_host, + f"{module_name}: a contract run was requested but no Hermes host " + f"resolved. Set {HOST_PATH_ENV} to a checkout, or stop setting " + f"{CONTRACT_REQUIRED_ENV}.", + ) + + def test_a_pin_targeted_run_is_at_the_revision_it_claims(self) -> None: + if not contract_required(): + self.skipTest("no contract run was requested") + root = host_root() + if root is None: + self.skipTest("covered by the host-resolution guard above") + mismatch = revision_mismatch(root) + self.assertIsNone(mismatch, mismatch) + + ContractLaneGuard.__qualname__ = f"{module_name}ContractLaneGuard" + return ContractLaneGuard diff --git a/tests/test_context_engine_contract.py b/tests/test_context_engine_contract.py index 2008c1d..2694f5d 100644 --- a/tests/test_context_engine_contract.py +++ b/tests/test_context_engine_contract.py @@ -8,20 +8,21 @@ import subprocess import sys import unittest + +try: # `unittest discover -s tests` puts tests/ on sys.path; `-m tests.x` does not. + from tests import _hermes_host +except ImportError: # pragma: no cover - depends on how the suite was invoked + import _hermes_host from pathlib import Path import hermes_plugin_kit as hpk def _import_deployed_host(): - root_value = os.environ.get("HERMES_AGENT_PATH") - if not root_value: + """Resolve the deployed host through the shared policy (see _hermes_host).""" + root = _hermes_host.host_root() + if root is None: return None - root = Path(root_value) - if not (root / "hermes_cli" / "plugins.py").exists(): - raise FileNotFoundError( - f"HERMES_AGENT_PATH has no hermes_cli/plugins.py: {root}" - ) sys.path.insert(0, str(root)) from agent.context_engine import ContextEngine # type: ignore from hermes_cli.plugins import ( # type: ignore @@ -35,6 +36,8 @@ def _import_deployed_host(): _HOST = _import_deployed_host() +ContractLaneGuard = _hermes_host.build_guard(_HOST, "test_context_engine_contract") + @unittest.skipUnless(_HOST is not None, "exact Hermes host source not configured") class DeployedContextEngineContractTests(unittest.TestCase): diff --git a/tests/test_hermes_contract.py b/tests/test_hermes_contract.py index 973f1f3..bb42bd6 100644 --- a/tests/test_hermes_contract.py +++ b/tests/test_hermes_contract.py @@ -32,21 +32,24 @@ from unittest.mock import AsyncMock, Mock, patch import hermes_plugin_kit as hpk +try: # `unittest discover -s tests` puts tests/ on sys.path; `-m tests.x` does not. + from tests import _hermes_host +except ImportError: # pragma: no cover - depends on how the suite was invoked + import _hermes_host def _import_real_hermes(): - """Return real plugin runtime APIs, failing when an explicit checkout is invalid.""" - candidates: list[Path] = [] - env_path = os.environ.get("HERMES_AGENT_PATH") - if env_path: - explicit_root = Path(env_path) - if not (explicit_root / "hermes_cli" / "plugins.py").exists(): - raise FileNotFoundError( - f"HERMES_AGENT_PATH has no hermes_cli/plugins.py: {explicit_root}" - ) - sys.path.insert(0, str(explicit_root)) - candidates.append(Path.home() / "hermes-agent") - candidates.append(Path.home() / ".hermes" / "hermes-agent") + """Return real plugin runtime APIs from the checkout the caller named. + + Discovery lives in `tests/_hermes_host.py` so both contract modules share + one policy. Nothing is auto-discovered: a `~/hermes-agent` fallback is what + made a bare `just test` exercise whatever branch a developer had, while CI + skipped the module entirely. + """ + root = _hermes_host.host_root() + if root is None: + return None + sys.path.insert(0, str(root)) def _try(): from hermes_cli.plugins import ( # type: ignore @@ -107,27 +110,15 @@ def _try(): ContextEngine=ContextEngine, ) - try: - return _try() - except Exception: - if env_path: - # An explicit contract checkout is authoritative in CI. Do not turn - # import or layout drift into a misleading skipped-green build. - raise - - for root in candidates: - if not (root / "hermes_cli" / "plugins.py").exists(): - continue - sys.path.insert(0, str(root)) - try: - return _try() - except Exception: - continue - return None + # A named checkout is authoritative: import or layout drift must fail loudly + # rather than becoming a misleading skipped-green build. + return _try() _REAL = _import_real_hermes() +ContractLaneGuard = _hermes_host.build_guard(_REAL, "test_hermes_contract") + def _write_legacy_state_db(db_path: Path) -> None: """Create a tiny pre-v16 database without borrowing a user's state.""" From d4f42966ad63d9e50429b29439b860dc4c178294 Mon Sep 17 00:00:00 2001 From: Offending Commit Date: Mon, 21 Sep 2026 15:48:41 -0500 Subject: [PATCH 3/5] feat(ci): widen the blocking gate, move drift to its own schedule The blocking job now runs the full contract suite at the pin instead of the context-engine module alone -- 110 lines of an 853-line suite. The suite is green at f80f453, verified by running it there, so this adds coverage rather than risk. The two pin literals collapse to one, which U7 will hold against the harness constant. The drift lane moves out of test.yml into its own scheduled workflow. A job there could never fire on drift: test.yml triggers on push and pull_request, so it ran when this repo changed and never when Hermes moved. Job-level continue-on-error compounded it by rendering a failed job green in the checks list. The new workflow is daily, carries no continue-on-error, and is not a required check -- non-blocking without a flag that hides the result. Failures are classified against a committed baseline by fingerprint rather than test name. The lane launches knowingly red, because #99220 stays out of scope, and an unclassified report would name the same failure every run until nobody read it. Verified both directions: the known break classifies as known and exits 0; the same test with a changed cause classifies as new drift. The reporting step runs on always(), or the failure it reports would skip it. A push trigger sits alongside the schedule because scheduled workflows are disabled after 60 days of inactivity on a public repo -- the exact quiet period the alarm guards. That mitigates rather than removes the risk, and the design says so. --- .github/workflows/hermes-drift.yml | 75 ++++++++++++ .github/workflows/test.yml | 41 ++----- .../harden-hermes-contract-gates/tasks.md | 12 +- scripts/classify_drift.py | 108 ++++++++++++++++++ tests/fixtures/known-hermes-drift.txt | 17 +++ 5 files changed, 218 insertions(+), 35 deletions(-) create mode 100644 .github/workflows/hermes-drift.yml create mode 100644 scripts/classify_drift.py create mode 100644 tests/fixtures/known-hermes-drift.txt diff --git a/.github/workflows/hermes-drift.yml b/.github/workflows/hermes-drift.yml new file mode 100644 index 0000000..262b0ae --- /dev/null +++ b/.github/workflows/hermes-drift.yml @@ -0,0 +1,75 @@ +--- +# yamllint disable rule:line-length rule:truthy +# +# Early warning that upstream hermes-agent has broken this kit's contract. +# +# This lives in its own workflow rather than as a job in test.yml for two +# reasons. test.yml triggers on push and pull_request, so a job there runs when +# *this* repository changes and never when Hermes moves -- the only event the +# lane exists to detect. And job-level `continue-on-error` renders a failed job +# green in the checks list, so even a run that fired and failed read as a pass. +# +# Nothing here is a required check, so a red run cannot block a merge. That +# keeps the non-blocking property without needing a flag that hides the result. +name: hermes-drift + +on: + schedule: + # Daily. The requirement states a 24-hour worst-case detection lag, so the + # cadence is part of the contract rather than an implementation detail. + - cron: "17 6 * * *" + # Scheduled workflows are disabled after 60 days without repository activity + # on a public repo -- exactly the quiet period this alarm guards. A push + # trigger keeps it alive. It does not fully remove the risk. + push: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: hermes-drift + cancel-in-progress: true + +jobs: + upstream-contract: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + repository: NousResearch/hermes-agent + path: .hermes-agent-upstream + - uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # v8.2.0 + with: + python-version: "3.11" + enable-cache: true + - uses: extractions/setup-just@53165ef7e734c5c07cb06b3c8e7b647c5aa16db3 # v4 + with: + just-version: "1.58.0" + - name: Record the upstream revision under test + id: upstream + run: | + rev="$(git -C .hermes-agent-upstream rev-parse HEAD)" + echo "revision=$rev" >> "$GITHUB_OUTPUT" + - name: Run the contract suite against upstream + id: contract + env: + HERMES_AGENT_PATH: ${{ github.workspace }}/.hermes-agent-upstream + run: | + just test-contract-upstream > contract.log 2>&1 + echo "EXIT=$?" >> contract.log + continue-on-error: true + # `outcome` is the result before continue-on-error is applied; + # `conclusion` is after. Keying on outcome is what makes this step see a + # failure at all. Without a run-after-failure condition the reporting + # step would be skipped by the very failure it exists to report. + - name: Classify and report drift + if: always() + run: | + python3 scripts/classify_drift.py contract.log "${{ steps.upstream.outputs.revision }}" \ + | tee -a "$GITHUB_STEP_SUMMARY" + new_drift=${PIPESTATUS[0]} + tail -40 contract.log >> "$GITHUB_STEP_SUMMARY" || true + exit "$new_drift" diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 13ad7e3..3cb189b 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -47,8 +47,14 @@ jobs: # Amber admission gates on the exact deployed Hermes fork contract. Keep the # immutable revision aligned with infra's candidate image/source receipt. - hermes-deployed-context-engine-contract: + # Amber admission gates on the exact deployed Hermes fork contract. The pin + # below is test-enforced against hermes_plugin_kit.testing's constant; the + # workflow cannot read that constant, because actions/checkout consumes the + # ref before setup-uv installs Python. + hermes-deployed-contract: runs-on: ubuntu-latest + env: + DEPLOYED_HERMES_REVISION: f80f453ae0679347e38abc917c7f94f717bf96c5 steps: - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 @@ -63,35 +69,12 @@ jobs: - uses: extractions/setup-just@53165ef7e734c5c07cb06b3c8e7b647c5aa16db3 # v4 with: just-version: "1.58.0" - - name: Run context-engine contract against deployed Hermes revision + # The full suite, not the context-engine module alone. It is green at + # this pin, so widening adds coverage rather than risk. + - name: Run the full contract suite against the deployed Hermes revision env: HERMES_AGENT_PATH: ${{ github.workspace }}/.hermes-agent-deployed run: | test "$(git -C "$HERMES_AGENT_PATH" rev-parse HEAD)" = \ - "f80f453ae0679347e38abc917c7f94f717bf96c5" - just test-context-engine-contract - - # Track forward drift against upstream main without making Amber depend on - # APIs that are newer than its exact deployed host. - hermes-contract: - runs-on: ubuntu-latest - continue-on-error: true - steps: - - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 - - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 - with: - repository: NousResearch/hermes-agent - path: .hermes-agent - - uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # v8.2.0 - with: - python-version: "3.11" - enable-cache: true - - uses: extractions/setup-just@53165ef7e734c5c07cb06b3c8e7b647c5aa16db3 # v4 - with: - just-version: "1.58.0" - - name: Run hermes contract tests against upstream main - env: - HERMES_AGENT_PATH: ${{ github.workspace }}/.hermes-agent - run: | - git -C "$HERMES_AGENT_PATH" rev-parse HEAD - just test-contract + "$DEPLOYED_HERMES_REVISION" + just test-contract-pinned diff --git a/openspec/changes/harden-hermes-contract-gates/tasks.md b/openspec/changes/harden-hermes-contract-gates/tasks.md index 0a16c6e..78277f2 100644 --- a/openspec/changes/harden-hermes-contract-gates/tasks.md +++ b/openspec/changes/harden-hermes-contract-gates/tasks.md @@ -28,23 +28,23 @@ ## 2. Blocking gate and scheduled drift lane (U6) -- [ ] 2.1 Point the blocking pinned job at the full contract suite. Verify: it +- [x] 2.1 Point the blocking pinned job at the full contract suite. Verify: it passes at the pin and the suite it runs is the whole module, not the context-engine one. -- [ ] 2.2 Collapse the two pin literals to one. Verify: the workflow names the +- [x] 2.2 Collapse the two pin literals to one. Verify: the workflow names the pin exactly once. -- [ ] 2.3 Move the drift lane into its own workflow on a daily schedule plus +- [x] 2.3 Move the drift lane into its own workflow on a daily schedule plus manual dispatch, outside required checks, with no `continue-on-error`. Verify: a manual dispatch runs, and a failure is visibly red without affecting any required check. -- [ ] 2.4 Report the upstream revision and failing tests to the run summary, on +- [x] 2.4 Report the upstream revision and failing tests to the run summary, on a step that runs even after the contract step fails. Verify: a failing dispatch still produces the summary, rather than skipping the step that reports the failure. -- [ ] 2.5 Add the known-drift baseline and classify failures against it by +- [x] 2.5 Add the known-drift baseline and classify failures against it by fingerprint. Verify: the #99220 media failure is labelled known, and an unrecognized failure appears under its own heading. -- [ ] 2.6 Add an activity trigger alongside the schedule. Verify: the workflow +- [x] 2.6 Add an activity trigger alongside the schedule. Verify: the workflow has a trigger other than the clock, so 60 days of quiet cannot silently disable the alarm. diff --git a/scripts/classify_drift.py b/scripts/classify_drift.py new file mode 100644 index 0000000..176f9f6 --- /dev/null +++ b/scripts/classify_drift.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python3 +"""Sort contract failures into already-known and genuinely new. + +The drift lane launches knowingly red: the #99220 relay-egress break is out of +scope and stays failing. An unclassified report would therefore name the same +failure every run, and a channel that is always red trains people to stop +reading it -- so the next real break arrives invisible. + +Matching is on a fingerprint of the failure text, not the test id alone. A +baselined test whose assertion or error has changed is a new break wearing a +known name. + +Reads a unittest log on stdin or as a path; writes a GitHub-flavoured summary +to stdout. Exit status is 0 when nothing unrecognized appeared, 1 otherwise, so +a caller can branch on "is there new drift" rather than "did anything fail". +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +BASELINE = Path(__file__).resolve().parents[1] / "tests" / "fixtures" / "known-hermes-drift.txt" + +# unittest prints: "FAIL: ()", optionally a docstring +# line, then a dashed rule, then the body. The parenthesised value is already +# the full id, so it is taken verbatim rather than rebuilt from parts. +_BLOCK = re.compile( + r"^(?:FAIL|ERROR): \S+ \((?P[^)]+)\)\n" + # [^\n] not . -- re.S is on for the body, and a dotall `.*` here + # would run straight past the separator it is meant to stop at. + r"(?:(?!-{10,})[^\n]*\n)*?" + r"-{10,}\n" + r"(?P.*?)(?=\n={10,}|\n-{10,}\n|\Z)", + re.M | re.S, +) + + +def load_baseline(path: Path = BASELINE) -> dict[str, str]: + entries: dict[str, str] = {} + if not path.exists(): + return entries + for line in path.read_text().splitlines(): + line = line.strip() + if not line or line.startswith("#"): + continue + test_id, _, fingerprint = line.partition(" ") + entries[test_id.strip()] = fingerprint.strip() + return entries + + +def fingerprint(body: str) -> str: + """A short stable digest of what actually went wrong. + + Uses the assertion or error text rather than the whole traceback, so a line + number shifting does not read as a new break, while a changed message does. + """ + for line in reversed(body.strip().splitlines()): + line = line.strip() + if not line or line.startswith(("File \"", "Traceback", "~", "^")): + continue + slug = re.sub(r"[^a-z0-9]+", "-", line.lower()).strip("-") + return slug[:80] or "unknown" + return "unknown" + + +def classify(log: str, baseline: dict[str, str]) -> tuple[list[str], list[str]]: + known: list[str] = [] + new: list[str] = [] + for match in _BLOCK.finditer(log): + test_id = match.group("test_id") + print_id = test_id + fp = fingerprint(match.group("body")) + expected = baseline.get(test_id) + if expected and expected in fp: + known.append(f"{print_id} ({fp})") + else: + reason = "not in the baseline" if expected is None else ( + f"baselined as {expected!r} but failed as {fp!r}" + ) + new.append(f"{print_id} — {reason}") + return known, new + + +def main() -> int: + log = Path(sys.argv[1]).read_text() if len(sys.argv) > 1 else sys.stdin.read() + revision = (sys.argv[2] if len(sys.argv) > 2 else "unknown").strip() + known, new = classify(log, load_baseline()) + + out = [f"## Hermes upstream drift\n", f"Exercised hermes-agent `{revision}`.\n"] + if new: + out.append(f"### New drift ({len(new)})\n") + out.append("These are not in the known-drift baseline, or their failure changed.\n") + out += [f"- `{n}`" for n in new] + out.append("") + if known: + out.append(f"### Already known ({len(known)})\n") + out += [f"- `{k}`" for k in known] + out.append("") + if not known and not new: + out.append("No contract failures against upstream.\n") + print("\n".join(out)) + return 1 if new else 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/fixtures/known-hermes-drift.txt b/tests/fixtures/known-hermes-drift.txt new file mode 100644 index 0000000..73d8ebb --- /dev/null +++ b/tests/fixtures/known-hermes-drift.txt @@ -0,0 +1,17 @@ +# Contract failures against upstream Hermes that are known and accepted. +# +# Without this the drift lane names the same failure on every run, and within a +# week nobody reads it -- at which point the next genuinely new break arrives as +# one more line in a channel that has been failing since day one. +# +# Format: one entry per line, ` `. +# +# The fingerprint is a short, stable digest of the failure's own text, not just +# the test id. A baselined test whose assertion or error has *changed* is a new +# break wearing a known name, and matching on the name alone would file it as +# expected. Change the failure, and it stops matching. +# +# Remove an entry when the underlying break is fixed. An entry that no longer +# matches any failure is reported, so this file cannot rot quietly. + +tests.test_hermes_contract.HermesContractTests.test_host_tool_invocation_reaches_real_telegram_media_contract refusing-to-send-to-telegram-relay-routing From e8bcad6d2f31fa9a2dc797ff32d8bd45b80416c5 Mon Sep 17 00:00:00 2001 From: Offending Commit Date: Mon, 21 Sep 2026 15:50:09 -0500 Subject: [PATCH 4/5] test(release): hold the contract-gate shape against regression Extends the existing workflow-as-contract tests rather than adding a parallel mechanism, since that module already parses the workflows and asserts SHA pinning, just-only steps, and permissions. Seven properties, each one a way the gates could regress while still reporting green: the blocking job runs the full suite rather than the context-engine module; test.yml names exactly one Hermes pin and it equals the harness constant; the drift workflow keeps its schedule, its manual dispatch, and the push trigger that stops a 60-day quiet period disabling it; no job-level continue-on-error, which would render a failed run green in the checks list; the reporting step keeps always(), or the failure it reports skips it; the baseline exists and parses, since an empty one files every known failure as new; and the built wheel actually contains the harness module. Every one was mutation-tested rather than assumed. Narrowing the blocking job, disagreeing the pin, removing the schedule, dropping always(), adding continue-on-error, emptying the baseline, and dropping the module from the wheel each fail their guard, and the suite is green once restored. The drift workflow also joins the existing SHA-pinning, just-only, and permissions sweeps. --- .../harden-hermes-contract-gates/tasks.md | 10 +- tests/test_release_contract.py | 102 ++++++++++++++++++ 2 files changed, 107 insertions(+), 5 deletions(-) diff --git a/openspec/changes/harden-hermes-contract-gates/tasks.md b/openspec/changes/harden-hermes-contract-gates/tasks.md index 78277f2..6481631 100644 --- a/openspec/changes/harden-hermes-contract-gates/tasks.md +++ b/openspec/changes/harden-hermes-contract-gates/tasks.md @@ -50,15 +50,15 @@ ## 3. Workflow shape held by the release contract (U7) -- [ ] 3.1 Assert the blocking job selects the full contract suite. Verify: +- [x] 3.1 Assert the blocking job selects the full contract suite. Verify: reducing it back to the context-engine module fails the test. -- [ ] 3.2 Assert the workflow pin equals the harness constant. Verify: editing +- [x] 3.2 Assert the workflow pin equals the harness constant. Verify: editing either one alone fails the test. -- [ ] 3.3 Assert the drift workflow keeps its schedule trigger, its +- [x] 3.3 Assert the drift workflow keeps its schedule trigger, its report-on-failure condition, and its baseline file. Verify: removing any of the three fails the test. -- [ ] 3.4 Assert the built wheel contains the harness module. Verify: dropping +- [x] 3.4 Assert the built wheel contains the harness module. Verify: dropping it from the packaging manifest fails this test where `twine check` passes. -- [ ] 3.5 Confirm the existing SHA-pinning, just-only, and +- [x] 3.5 Confirm the existing SHA-pinning, just-only, and `pull_request_target` assertions still hold for the new workflow. Verify: the release-contract suite passes with both workflows present. diff --git a/tests/test_release_contract.py b/tests/test_release_contract.py index 11607f3..f93c70a 100644 --- a/tests/test_release_contract.py +++ b/tests/test_release_contract.py @@ -5,6 +5,7 @@ import subprocess import tarfile import tempfile +import re import unittest import zipfile from pathlib import Path @@ -436,6 +437,9 @@ def setUpClass(cls) -> None: cls.workflow = (ROOT / ".github/workflows/release.yml").read_text( encoding="utf-8" ) + cls.drift_workflow = (ROOT / ".github/workflows/hermes-drift.yml").read_text( + encoding="utf-8" + ) cls.test_workflow = (ROOT / ".github/workflows/test.yml").read_text( encoding="utf-8" ) @@ -653,6 +657,7 @@ def test_workflows_install_and_use_only_just(self) -> None: workflows = { "release": self.workflow, "test": self.test_workflow, + "hermes-drift": self.drift_workflow, } for workflow_name, workflow in workflows.items(): config = yaml.load(workflow, Loader=yaml.BaseLoader) @@ -695,3 +700,100 @@ def test_unsafe_pull_request_target_is_not_used(self) -> None: if __name__ == "__main__": unittest.main() + + +class ContractGateShapeTests(unittest.TestCase): + """Hold the gate shape that makes a green run mean something. + + Each of these guards a property that, if it regressed, would leave the + workflow passing while checking less than it claims. + """ + + @classmethod + def setUpClass(cls) -> None: + cls.test_workflow = (ROOT / ".github/workflows/test.yml").read_text(encoding="utf-8") + cls.drift_workflow = ( + ROOT / ".github/workflows/hermes-drift.yml" + ).read_text(encoding="utf-8") + cls.test_config = yaml.load(cls.test_workflow, Loader=yaml.BaseLoader) + cls.drift_config = yaml.load(cls.drift_workflow, Loader=yaml.BaseLoader) + + def _steps(self, config, job): + return config["jobs"][job].get("steps", []) + + def test_blocking_job_runs_the_full_contract_suite(self) -> None: + run = "\n".join( + step.get("run", "") for step in self._steps(self.test_config, "hermes-deployed-contract") + ) + self.assertIn("just test-contract-pinned", run) + self.assertNotIn( + "just test-context-engine-contract", run, + "the blocking gate must run the whole contract, not the context-engine module alone", + ) + + def test_workflow_pin_agrees_with_the_harness_constant(self) -> None: + # The workflow cannot read the constant -- actions/checkout consumes the + # ref before Python exists -- so the two are kept honest by this test. + from hermes_plugin_kit.testing import DEPLOYED_HERMES_REVISION + + pins = set(re.findall(r"\b[0-9a-f]{40}\b", self.test_workflow)) - set( + re.findall(r"uses: [^@]+@([0-9a-f]{40})", self.test_workflow) + ) + self.assertEqual( + {DEPLOYED_HERMES_REVISION}, pins, + "test.yml must name exactly one Hermes pin, equal to the harness constant", + ) + + def test_drift_workflow_is_scheduled_and_manually_dispatchable(self) -> None: + triggers = self.drift_config[True] if True in self.drift_config else self.drift_config["on"] + self.assertIn("schedule", triggers) + self.assertIn("workflow_dispatch", triggers) + self.assertIn( + "push", triggers, + "a schedule-only workflow is disabled after 60 days of inactivity on a " + "public repo; an activity trigger keeps the alarm alive", + ) + + def test_drift_job_is_not_silenced_at_the_job_level(self) -> None: + for name, job in self.drift_config["jobs"].items(): + with self.subTest(job=name): + self.assertNotIn( + "continue-on-error", job, + "job-level continue-on-error renders a failed job green in the " + "checks list; this lane stays non-blocking by not being required", + ) + + def test_drift_reporting_survives_a_failing_contract_step(self) -> None: + steps = self._steps(self.drift_config, "upstream-contract") + reporting = [s for s in steps if "classify_drift.py" in s.get("run", "")] + self.assertTrue(reporting, "the drift lane must classify and report its failures") + for step in reporting: + with self.subTest(step=step.get("name")): + self.assertEqual( + "always()", step.get("if"), + "without this the reporting step is skipped by the very failure " + "it exists to report", + ) + + def test_known_drift_baseline_exists_and_is_parseable(self) -> None: + baseline = ROOT / "tests/fixtures/known-hermes-drift.txt" + self.assertTrue(baseline.exists(), "the baseline is what keeps known red from hiding new red") + entries = [ + line for line in baseline.read_text().splitlines() + if line.strip() and not line.startswith("#") + ] + self.assertTrue(entries, "an empty baseline classifies every known failure as new") + for entry in entries: + with self.subTest(entry=entry): + test_id, _, fingerprint = entry.partition(" ") + self.assertTrue(test_id.strip() and fingerprint.strip()) + + def test_built_wheel_contains_the_harness_module(self) -> None: + # `twine check` reads metadata and never opens the archive, so it passes + # on a wheel missing a module entirely. Proven by probe during U4. + wheels = sorted((ROOT / "dist").glob("*.whl")) if (ROOT / "dist").exists() else [] + if not wheels: + self.skipTest("no built wheel in dist/; `just build` first") + with zipfile.ZipFile(wheels[-1]) as archive: + names = archive.namelist() + self.assertIn("hermes_plugin_kit/testing.py", names) From 157bd0a78e912c795d6aab2115d4e518a506cc7d Mon Sep 17 00:00:00 2001 From: Offending Commit Date: Mon, 21 Sep 2026 15:54:47 -0500 Subject: [PATCH 5/5] fix: make the harness and drift lane environment agnostic Four assumptions that would have failed off this machine. The drift fingerprint absorbed machine-specific text. A baseline committed from a laptop carried home directories, temp paths, ports and PIDs into the digest, so it matched where it was written and nowhere else -- every known failure would have classified as new in CI, which is exactly the noise the baseline exists to prevent. Absolute paths (POSIX, Windows, UNC), hex addresses, sha-like runs and multi-digit numbers now normalize before slugging. Small numbers are deliberately kept: "expected 3, got 5" is a different break from "expected 3, got 7", so flattening every digit would trade machine noise for lost signal. The cache location assumed a POSIX home. HERMES_PLUGIN_KIT_CACHE now overrides outright, then XDG_CACHE_HOME, then LOCALAPPDATA, then a writable home, then a temp directory. A container with no home or a read-only image no longer fails for a reason the caller cannot act on. The new checkout directories were not gitignored, so any contract run dirtied the tree. The drift workflow called python3 directly. It now goes through uv, matching the repo's own convention and avoiding an interpreter that resolves differently per platform. Tests cover each: identical fingerprints across POSIX, macOS and Windows paths, across temp directories, and across ports and PIDs; a resolvable cache location on any platform; and a missing git, an offline network, and a slow fetch each yielding the same unchecked report rather than a traceback or a hang. --- .github/workflows/hermes-drift.yml | 2 +- .gitignore | 2 + hermes_plugin_kit/testing.py | 34 ++++++- scripts/classify_drift.py | 33 ++++++- tests/test_drift_classification.py | 138 +++++++++++++++++++++++++++++ tests/test_testing_harness.py | 72 +++++++++++++++ 6 files changed, 274 insertions(+), 7 deletions(-) create mode 100644 tests/test_drift_classification.py diff --git a/.github/workflows/hermes-drift.yml b/.github/workflows/hermes-drift.yml index 262b0ae..16fef16 100644 --- a/.github/workflows/hermes-drift.yml +++ b/.github/workflows/hermes-drift.yml @@ -68,7 +68,7 @@ jobs: - name: Classify and report drift if: always() run: | - python3 scripts/classify_drift.py contract.log "${{ steps.upstream.outputs.revision }}" \ + uv run python scripts/classify_drift.py contract.log "${{ steps.upstream.outputs.revision }}" \ | tee -a "$GITHUB_STEP_SUMMARY" new_drift=${PIPESTATUS[0]} tail -40 contract.log >> "$GITHUB_STEP_SUMMARY" || true diff --git a/.gitignore b/.gitignore index b69cf75..4007cc1 100644 --- a/.gitignore +++ b/.gitignore @@ -6,4 +6,6 @@ dist/ .venv/ .eggs/ .hermes-agent/ +.hermes-agent-pinned/ +.hermes-agent-upstream/ .DS_Store diff --git a/hermes_plugin_kit/testing.py b/hermes_plugin_kit/testing.py index 0a4e764..da198f3 100644 --- a/hermes_plugin_kit/testing.py +++ b/hermes_plugin_kit/testing.py @@ -31,6 +31,7 @@ import inspect import os import subprocess +import tempfile import sys from pathlib import Path from dataclasses import dataclass, field @@ -38,6 +39,7 @@ from typing import Any, Callable, Iterable, Mapping, Sequence __all__ = [ + "CACHE_DIR_ENV", "DEPLOYED_HERMES_REVISION", "RECEIPT_FIELD_ORDER", "CheckResult", @@ -688,6 +690,34 @@ def resolve_hermes_checkout( return ResolvedHost(cache, head, f"fetched {revision}") +#: Overrides where a fetched checkout is cached. Set this in any environment +#: where the defaults below are wrong or unwritable -- a container with no home +#: directory, a read-only image, a CI runner with its own cache mount. +CACHE_DIR_ENV = "HERMES_PLUGIN_KIT_CACHE" + + def _default_cache_dir() -> Path: - base = os.environ.get("XDG_CACHE_HOME") or (Path.home() / ".cache") - return Path(base) / "hermes-plugin-kit" / "hermes-agent" + """Where to cache a fetched checkout, without assuming an OS or a layout. + + An explicit override wins, then each platform's own convention, then a + temp directory. The last step matters: a home directory is not guaranteed + to exist or be writable in a container, and a library that assumed one + would fail there for a reason the caller cannot act on. + """ + override = (os.environ.get(CACHE_DIR_ENV) or "").strip() + if override: + return Path(override) + + for variable in ("XDG_CACHE_HOME", "LOCALAPPDATA"): + base = (os.environ.get(variable) or "").strip() + if base: + return Path(base) / "hermes-plugin-kit" / "hermes-agent" + + try: + home = Path.home() + except (RuntimeError, OSError): # no resolvable home, e.g. a bare container + home = None + if home is not None and os.access(home, os.W_OK): + return home / ".cache" / "hermes-plugin-kit" / "hermes-agent" + + return Path(tempfile.gettempdir()) / "hermes-plugin-kit" / "hermes-agent" diff --git a/scripts/classify_drift.py b/scripts/classify_drift.py index 176f9f6..73315f1 100644 --- a/scripts/classify_drift.py +++ b/scripts/classify_drift.py @@ -50,17 +50,42 @@ def load_baseline(path: Path = BASELINE) -> dict[str, str]: return entries +#: Text that differs between machines and runs, and so must never reach a +#: fingerprint. A baseline is committed once and matched everywhere; if it +#: absorbed a home directory, a temp path, a port, or a PID, it would match on +#: the machine that produced it and nowhere else. +_VOLATILE = ( + # Windows and POSIX absolute paths, including UNC. + (re.compile(r"[A-Za-z]:[\\/][^\s'\"]*"), " path "), + (re.compile(r"(? str: + """Strip everything that varies by machine or run.""" + for pattern, replacement in _VOLATILE: + text = pattern.sub(replacement, text) + return text + + def fingerprint(body: str) -> str: - """A short stable digest of what actually went wrong. + """A short digest of what went wrong, stable across machines. - Uses the assertion or error text rather than the whole traceback, so a line - number shifting does not read as a new break, while a changed message does. + Uses the assertion or error text rather than the whole traceback, so a + shifting line number does not read as a new break while a changed message + does -- and normalizes the parts that differ per machine, so a baseline + committed from a laptop still matches in CI. """ for line in reversed(body.strip().splitlines()): line = line.strip() if not line or line.startswith(("File \"", "Traceback", "~", "^")): continue - slug = re.sub(r"[^a-z0-9]+", "-", line.lower()).strip("-") + slug = re.sub(r"[^a-z0-9]+", "-", normalize(line).lower()).strip("-") return slug[:80] or "unknown" return "unknown" diff --git a/tests/test_drift_classification.py b/tests/test_drift_classification.py new file mode 100644 index 0000000..d3187ad --- /dev/null +++ b/tests/test_drift_classification.py @@ -0,0 +1,138 @@ +"""The drift baseline is committed once and matched everywhere. + +A fingerprint that absorbed a home directory, a temp path, a port, or a PID +would match on the machine that produced it and nowhere else -- the baseline +would look correct locally and classify every known failure as new in CI. These +tests hold the normalization that prevents that. +""" + +from __future__ import annotations + +import importlib.util +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] + +_spec = importlib.util.spec_from_file_location( + "classify_drift", ROOT / "scripts" / "classify_drift.py" +) +classify_drift = importlib.util.module_from_spec(_spec) +assert _spec.loader is not None +_spec.loader.exec_module(classify_drift) + + +class FingerprintStabilityTests(unittest.TestCase): + """Same failure, different machine, same fingerprint.""" + + def test_posix_and_windows_paths_normalize_alike(self) -> None: + posix = classify_drift.fingerprint( + "FileNotFoundError: No such file: /home/runner/work/hermes-agent/x.py" + ) + mac = classify_drift.fingerprint( + "FileNotFoundError: No such file: /Users/someone/hermes-agent/x.py" + ) + windows = classify_drift.fingerprint( + r"FileNotFoundError: No such file: C:\Users\someone\hermes-agent\x.py" + ) + + self.assertEqual(posix, mac) + self.assertEqual(posix, windows) + self.assertNotIn("runner", posix) + self.assertNotIn("someone", posix) + + def test_temp_directories_do_not_reach_the_fingerprint(self) -> None: + first = classify_drift.fingerprint( + "AssertionError: /var/folders/v9/T/tmpab12cd/references != expected" + ) + second = classify_drift.fingerprint( + "AssertionError: /tmp/tmp99zzzz/references != expected" + ) + + self.assertEqual(first, second) + self.assertNotIn("tmpab12cd", first) + + def test_ports_and_pids_do_not_reach_the_fingerprint(self) -> None: + first = classify_drift.fingerprint( + "ConnectionError: could not connect to 127.0.0.1:54321 (pid 88213)" + ) + second = classify_drift.fingerprint( + "ConnectionError: could not connect to 127.0.0.1:61000 (pid 9182)" + ) + + self.assertEqual(first, second) + + def test_small_numbers_survive_because_they_usually_carry_meaning(self) -> None: + """Normalization stops at two digits on purpose. + + Ports, PIDs and byte counts are multi-digit and volatile. A small + number in an assertion is usually part of the failure's identity -- + "expected 3, got 5" is a different break from "expected 3, got 7" -- + so flattening every digit would trade machine-noise for lost signal. + """ + three = classify_drift.fingerprint("AssertionError: expected 3 items, got 5") + seven = classify_drift.fingerprint("AssertionError: expected 3 items, got 7") + + self.assertNotEqual(three, seven) + + def test_a_genuinely_different_cause_still_differs(self) -> None: + """Normalization must not flatten real differences into one bucket.""" + relay = classify_drift.fingerprint( + "AssertionError: Refusing to send to 'telegram': relay routing unknown" + ) + other = classify_drift.fingerprint( + "AssertionError: schema parameters must be object-shaped" + ) + + self.assertNotEqual(relay, other) + + def test_a_line_number_shift_is_not_new_drift(self) -> None: + body_a = 'File "x.py", line 807, in test\n assert False\nAssertionError: boom' + body_b = 'File "x.py", line 912, in test\n assert False\nAssertionError: boom' + + self.assertEqual( + classify_drift.fingerprint(body_a), classify_drift.fingerprint(body_b) + ) + + +class BaselineTests(unittest.TestCase): + def test_the_committed_baseline_parses(self) -> None: + entries = classify_drift.load_baseline() + + self.assertTrue(entries, "an empty baseline files every known failure as new") + for test_id, fingerprint in entries.items(): + with self.subTest(test_id=test_id): + self.assertTrue(fingerprint) + self.assertNotIn("/", fingerprint, "a path in a baseline is machine-specific") + + def test_a_known_failure_classifies_as_known(self) -> None: + test_id, fingerprint = next(iter(classify_drift.load_baseline().items())) + log = ( + f"FAIL: t ({test_id})\n" + + "-" * 70 + + "\nTraceback (most recent call last):\n" + + f"AssertionError: ... {fingerprint.replace('-', ' ')} ...\n" + ) + + known, new = classify_drift.classify(log, classify_drift.load_baseline()) + + self.assertEqual(1, len(known), f"known={known} new={new}") + self.assertEqual([], new) + + def test_the_same_test_failing_differently_is_new(self) -> None: + test_id = next(iter(classify_drift.load_baseline())) + log = ( + f"FAIL: t ({test_id})\n" + + "-" * 70 + + "\nTraceback (most recent call last):\n" + + "AssertionError: an entirely unrelated cause\n" + ) + + known, new = classify_drift.classify(log, classify_drift.load_baseline()) + + self.assertEqual([], known) + self.assertEqual(1, len(new), "a baselined test failing differently is a new break") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_testing_harness.py b/tests/test_testing_harness.py index a80fd8a..0d7ee49 100644 --- a/tests/test_testing_harness.py +++ b/tests/test_testing_harness.py @@ -616,3 +616,75 @@ def test_import_pulls_in_neither_hermes_nor_a_test_framework(self) -> None: if __name__ == "__main__": unittest.main() + + +class EnvironmentAgnosticTests(unittest.TestCase): + """The harness runs on machines this repository will never see. + + A consumer's CI may have no home directory, no git, no network, or a + Windows path layout. None of those may turn into a hang or an opaque + traceback from inside a test-support library. + """ + + def setUp(self) -> None: + self._tmp = tempfile.TemporaryDirectory() + self.addCleanup(self._tmp.cleanup) + self.root = Path(self._tmp.name) + + def test_an_explicit_cache_override_wins_over_every_convention(self) -> None: + import os + + previous = os.environ.get(hpk_testing.CACHE_DIR_ENV) + os.environ[hpk_testing.CACHE_DIR_ENV] = str(self.root / "explicit") + self.addCleanup( + lambda: os.environ.__setitem__(hpk_testing.CACHE_DIR_ENV, previous) + if previous is not None + else os.environ.pop(hpk_testing.CACHE_DIR_ENV, None) + ) + + self.assertEqual(self.root / "explicit", hpk_testing._default_cache_dir()) + + def test_the_cache_location_is_always_resolvable(self) -> None: + # Never raises, whatever the platform conventions happen to be. + self.assertIsInstance(hpk_testing._default_cache_dir(), Path) + + def test_a_missing_git_is_an_unavailable_result_not_a_traceback(self) -> None: + resolved = hpk_testing.resolve_hermes_checkout( + cache_dir=self.root / "cache", env={}, + fetcher=lambda *a, **k: (_ for _ in ()).throw(FileNotFoundError("git")), + ) + + self.assertFalse(resolved.available) + self.assertIn(hpk_testing.DEPLOYED_HERMES_REVISION, resolved.detail) + self.assertIsNone(resolved.plugin_context_class()) + + def test_a_slow_fetch_is_abandoned_rather_than_hanging(self) -> None: + resolved = hpk_testing.resolve_hermes_checkout( + cache_dir=self.root / "cache", env={}, timeout=1, + fetcher=lambda *a, **k: (_ for _ in ()).throw( + subprocess.TimeoutExpired("git", 1) + ), + ) + + self.assertFalse(resolved.available) + self.assertIn("1s", resolved.detail) + + def test_every_unavailable_path_yields_an_unchecked_report(self) -> None: + """Whatever went wrong, the caller gets the same honest shape.""" + ctx = hpk_testing.RecordingPluginContext(name="probe-plugin") + _register_a_tool(ctx) + + for label, fetcher in { + "no git": lambda *a, **k: (_ for _ in ()).throw(FileNotFoundError("git")), + "offline": lambda *a, **k: (_ for _ in ()).throw(OSError("unreachable")), + "timeout": lambda *a, **k: (_ for _ in ()).throw( + subprocess.TimeoutExpired("git", 1) + ), + }.items(): + with self.subTest(case=label): + resolved = hpk_testing.resolve_hermes_checkout( + cache_dir=self.root / label.replace(" ", "-"), env={}, fetcher=fetcher + ) + report = ctx.check_against_host(resolved.plugin_context_class()) + self.assertFalse(report.checked) + self.assertFalse(report.clean)