diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 0efe5a5..13ad7e3 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -39,6 +39,11 @@ jobs: run: | just build just check-dist + # `twine check` reads metadata and never opens the archive, so it passes + # on a wheel that is missing a module entirely. Installing and importing + # is the only thing that catches that. + - name: Prove the public surface imports from the installed wheel + run: just check-install # Amber admission gates on the exact deployed Hermes fork contract. Keep the # immutable revision aligned with infra's candidate image/source receipt. diff --git a/.gitignore b/.gitignore index 036c367..b69cf75 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,4 @@ dist/ .venv/ .eggs/ .hermes-agent/ +.DS_Store diff --git a/docs/plans/2026-09-21-1406-feat-plugin-contract-testing-harness-plan.md b/docs/plans/2026-09-21-1406-feat-plugin-contract-testing-harness-plan.md new file mode 100644 index 0000000..c20d8cd --- /dev/null +++ b/docs/plans/2026-09-21-1406-feat-plugin-contract-testing-harness-plan.md @@ -0,0 +1,474 @@ +--- +title: Plugin Contract Testing Harness - Plan +type: feat +date: 2026-09-21 +artifact_contract: ce-unified-plan/v1 +product_contract_source: ce-plan-bootstrap +execution: code +--- + +# Plugin Contract Testing Harness - Plan + +## Goal Capsule + +- Objective: a Hermes plugin author — human or coding agent — finds out that the host's registration contract has drifted underneath their plugin, at the Hermes revision the kit names as deployed, before that drift reaches production. Proving the *full* runtime contract stays this repository's own contract gate, which is the only thing that runs Hermes' real dispatchers; the harness is blind to how the host invokes a registered hook. +- Means: export a record-and-replay test harness from the installed package and split the contract lanes into a blocking pinned gate and a scheduled drift gate (KTD1, KTD4, KTD10). +- Authority: requirements govern behavior; KTDs govern mechanism. Where a unit disagrees with a cited R or KTD, the cited entry wins. +- Execution profile: three OpenSpec changes delivered in dependency order; each is independently reviewable, and shippable in that order. +- Stop conditions: stop and ask if `openspec validate` cannot accept a change shape this plan assumes, or if exporting the harness would require a runtime dependency the kit does not already carry. +- Finishes the work: `ce-work`, or the author who picks up a phase. + +--- + +## Product Contract + +### Summary + +Ship a public `hermes_plugin_kit.testing` surface so plugin authors stop hand-rolling fake plugin contexts, make the blocking CI gate run the full contract suite at the deployed Hermes pin, give the upstream-drift lane a voice, and make the local contract lane pin-aware instead of silently green. Delivered as three OpenSpec changes. + +### Problem Frame + +Fifteen repositories on this machine independently define a fake Hermes plugin context — fourteen consumer plugins plus the kit itself. Across the fourteen consumers, eight use a strict positional `register_skill(self, name, path, description="")`, three use a permissive `**kwargs` form, and three define no skill registrar at all; the kit's own fake is a fourth permissive one. Every one of them is an author who needed a harness, could not find one, and wrote a weaker substitute. The kit's own `FakePluginCtx` and its real-Hermes import seam live in `tests/`, which never reaches a consumer: consumers install via `git+…@sha`, and the wheel carries only `hermes_plugin_kit/__init__.py` and `hermes_plugin_kit/observability.py`. + +The repository already teaches the principle it cannot deliver. `skills/hermes-plugins/references/plugin-kit.md:98-99` states that "a fake context alone can hide signature drift," and `skills/hermes-plugins/SKILL.md` instructs an agent to "run contract tests against the real pinned Hermes Agent checkout" — an instruction no consumer can carry out, because the fake, the import seam, and the pin all live outside anything they install. + +The gap is not hypothetical. Hermes commit `866332bf` (#99220) added `gateway/relay/egress.py`, which refuses `send_message` to relay targets whose routing is not attested. The kit's media host-tool contract passes against the pinned Hermes revision `f80f453` (2026-08-14) and fails against upstream main `a6bab19` (2026-09-21). Nobody was paged: the job that would have caught it carries `continue-on-error: true` and emits no summary, and the blocking job runs only `tests.test_context_engine_contract` — 110 lines of an 853-line contract suite that is fully green at that same pin. + +### Key Decisions + +- Resolving the #99220 relay-egress break in `deliver_media` is out of scope (session-settled: user-directed — chosen over bundling it with the harness work: the drift is the motivating evidence for building the gate, and fixing it is a separate objective with its own proof boundary). Governs R14. +- Work is delivered as three OpenSpec changes cut on dependency lines rather than one combined change or five per-item changes (session-settled: user-approved — chosen over one-change and five-change cuts: the CI gate work ships today, the consumer lane cannot start until the harness exists). Governs R15. +- The consumer contract lane stops at the kit shipping a harness and a documented recipe; it does not convert any consumer repository's hand-rolled fake (session-settled: user-approved — chosen over migrating consumers in the same change: adoption cost belongs to each consumer's own release cadence). Governs R16. +- The harness fetches a Hermes checkout at the pin whenever none resolves, rather than only reporting what to provision (session-settled: user-directed — chosen over validate-and-instruct and an opt-in fetch: a step that merely instructs leaves every consumer on the record-only path, which is the gap the harness exists to close). Governs R17. + +### Requirements + +**Harness surface** + +- R1. `hermes_plugin_kit.testing` is importable from an installed wheel, with no new runtime dependency and no test-framework import at module import time. +- R2. The fake records the registration calls a plugin makes, and those recorded calls are replayed against the real Hermes `PluginContext` signatures wherever a Hermes checkout is importable, so a host adding or renaming a required parameter fails rather than passing. +- R3. The fake is usable with no Hermes checkout present, and a run that could not perform the replay says so rather than presenting itself as drift-checked. When no checkout is available, the harness names the exact revision a consumer must provision to enable the replay. +- R4. A drift failure names the registrar and the parameter that drifted, rather than only raising. +- R5. Registration assertions cover the receipt's stable log field order, duplicate detection, deterministic ordering, and the schema-under-`function.parameters` convention, so a consumer asserts them without copying literals. +- R6. The harness ships the deployed Hermes revision as a machine-readable constant, and the CI workflow's pin literal is test-enforced to agree with it. + +**Contract lanes** + +- R7. The blocking CI gate runs the full Hermes contract suite at the deployed pin, not only the context-engine module. +- R8. The upstream-drift lane runs at least daily rather than only when the kit changes, so the worst-case lag between an upstream break landing and this repository seeing it is 24 hours. It stays outside required checks and emits a visible record naming the failing tests, the Hermes revision exercised, and which failures are new versus already known. +- R9. A contract run states which Hermes revision it exercised and how many tests actually executed, or refuses; a run in which everything skipped or nothing was collected must not report success. +- R10. The local lane can target the deployed pin, not only whatever the default branch currently is. +- R11. Hermes checkout discovery follows one policy across both contract modules. + +**Discoverability** + +- R12. Every public name the kit documents — the harness surface and existing exports such as `plugin_reference_tool` — is reachable through the package's public import path and is covered by a guard that fails when it is not. +- R13. `skills/hermes-plugins/SKILL.md` and `skills/hermes-plugins/references/plugin-kit.md` route an author to the harness by import path, and their reference-file links are covered by a test. + +**Delivery** + +- R14. The plan changes no behavior in `deliver_media` or `invoke_host_tool`. +- R15. Each OpenSpec change validates under `openspec validate` and is reviewable on its own. +- R16. No consumer repository's hand-rolled fake context is converted; the consumer lane ends at the kit shipping the harness and a documented recipe. +- R17. The harness ships a Python-invocable step that resolves a Hermes checkout at the pin, fetching one when none is present, so the drift replay runs on a consumer's machine rather than only inside this repository. + +### Success Criteria + +- **Core outcome.** A fresh consumer repository with no Hermes checkout on the machine can follow the skill's Validation section and complete a replay against a named Hermes revision with a non-zero executed-check count. A refusal does not satisfy this one; the point is that the check actually ran somewhere other than this repository. +- **Refusal safety.** When the replay genuinely cannot run, the result is an explicit receipt naming what is missing — never a green run with the check silently absent. This is the honest-failure guarantee, kept separate so it cannot stand in for the outcome above. +- Re-running the #99220 scenario against upstream main produces a named, readable CI record instead of silence, and a *new* failure is distinguishable from that known one. +- The kit's own fake migrates onto the harness and deletes more lines than it adds. This measures the kit, not a consumer: R16 keeps consumer repositories out of scope, so the consumer-side benefit stays a projection from the kit's own migration rather than something this plan evidences. + +### Scope Boundaries + +- Converting any consumer repository's fake, per R16. +- Changing media delivery or relay attestation behavior, per R14. +- Bumping the deployed Hermes pin past `f80f453`. Promotion is infra's snapshot objective; this plan only makes the pin readable and the gate honest. +- Guaranteeing the named pin equals what production runs. The gate proves conformance at the revision the kit names, which is a weaker claim than conformance at whatever is deployed right now, and during a promotion the two diverge — the contingency below deliberately holds the old pin when a promoted revision is red. Keeping them equal is the promotion process's job, and making it the kit's would reintroduce the cross-repo dependency the kit-owned-pin decision rejected. + +#### Deferred to Follow-Up Work + +- Version-coupling the skill to the pinned kit revision. The skill is consumed as a symlink to a moving checkout (`README.md:689`) while `AGENTS.md` requires consumers to pin the kit immutably, so the skill an author reads and the kit revision they install can drift apart. Out of scope here; worth its own change. +- Exposing the harness to the Hermes runtime agent loop via `plugin_reference_tool` or a registered tool. The harness is dev-time, invoked from a consumer's test runner. Recorded so it does not drift into scope. +- A tracking-issue lifecycle for the drift lane — one issue kept in sync, closed when the lane goes green, with repeat reports suppressed until the upstream revision changes. R8 asks for a visible record, which the job summary and an honestly-red workflow already give; an issue manager is a stateful subsystem needing a permission the workflow does not currently grant. Worth doing once the lane has proven it fires, not before. + +--- + +## Planning Contract + +### Key Technical Decisions + +- KTD1. Record the plugin's registration calls in a permissive fake, then replay those recorded arguments through the real `PluginContext` signatures wherever the host is importable. Probing five candidate techniques settled this. A permissive `**kwargs` fake and a hand-written positional fake mirroring today's host both pass unchanged when the host gains a required parameter — the positional fake is a frozen snapshot, not a stricter contract. Comparing the fake's own signature to the real one also catches nothing, because `**kwargs` is compatible with every signature by construction. `create_autospec` does catch it, but only where the real class is importable, which a consumer's machine generally is not — so it cannot be the mechanism in the shipped fake. Replaying recorded arguments through the real signature catches the drift shapes and needs the host only at check time: an added required parameter reports `missing a required argument`, and a renamed keyword reports `got an unexpected keyword argument`. A renamed *positional* parameter is the one case binding alone misses, because Python binds those by position and the call still fits — so the replay also compares parameter names for the registrars the kit calls positionally. An independent cross-model review found that gap after the first implementation; a probe confirmed it and the fix landed. Strictness is not the axis, and neither is derivation — separating *recording* (always available) from *checking* (available when the host is) is. Governs R2, R3, R4. +- KTD2. Ship a flat `hermes_plugin_kit/testing.py`, not a `hermes_plugin_kit/testing/` subpackage. `pyproject.toml:34` declares `packages = ["hermes_plugin_kit"]` as an explicit list, so a subpackage is silently omitted from the wheel and the existing `package` CI job would not notice; the built wheel today contains exactly the two flat modules. This mirrors the `observability.py` precedent. Governs R1. +- KTD3. Assert the receipt's **log** field order, not the dataclass field order. They genuinely differ — `RegistrationSummary` declares `tools, hooks, skills, …` while `log_registration_summary` emits `commands, cli_commands, tools, …`. The log string is the external contract `AGENTS.md` pins. Governs R5. +- KTD4. The pin lives in `hermes_plugin_kit/testing.py`, the workflow keeps a literal, and a release-contract test asserts the two agree (session-settled: user-approved — chosen over reading infra's deployed-snapshot receipt: a constant that ships in the wheel is the only form a consumer can read offline, and it keeps R6 free of a cross-repo dependency). The workflow cannot read the 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 KTD5 already chose. Today the pin is two unlinked literals at `.github/workflows/test.yml:52` and `:66`, readable only inside CI and agreeing with nothing. Governs R6, R7. +- KTD5. Extend the existing workflow-as-contract tests in `tests/test_release_contract.py` rather than adding a parallel mechanism. That module already parses `test.yml` and asserts SHA-pinned actions (`:638`), `just`-only steps (`:649`), justfile-as-sole-runner (`:687`), and absence of `pull_request_target` (`:691`). Job *names* are asserted nowhere, so jobs may be added or renamed freely. Governs R7, R8. +- KTD6. Keep the upstream-drift lane non-blocking and give it a reporting step (session-settled: user-approved — chosen over making it blocking: it tracks a moving target, so blocking would put Hermes' merge queue in this repo's critical path). Governs R8. +- KTD7. Expose the harness as composable pieces — fake context, pin constant, conformance check, assertion helpers — rather than one opaque "run the lane" entry point, so an author can take just registration parity. The lane entry point is Python-invocable because consumer repositories predominantly use `make`, not `just`; a recipe documented only as `just test-contract` is unusable in the repositories that need it. Governs R5, R12. +- KTD8. Consolidate Hermes discovery on the stricter of the two existing policies: an explicit `HERMES_AGENT_PATH` is authoritative and re-raises on a bad path, and absence produces an explicit outcome rather than a silent skip. `tests/test_hermes_contract.py:37-126` already does the former with staleness guards; `tests/test_context_engine_contract.py:16-36` is env-only and returns `None` into a silent skip. Governs R9, R11. + +- KTD9. Prove a contract run happened by asserting the executed-test count, not by trusting the exit code. On Python 3.11 — the version CI pins — `unittest` exits 0 both when every test skips and when zero tests are collected; the `NO TESTS RAN` exit-5 behavior only arrives in 3.12. Verified on both versions. So "the contract gate passed" and "the contract gate ran" are today indistinguishable from the exit status alone. Each contract module also gets a guard test outside the `skipUnless` decorator, so an intended-but-unconfigured run fails instead of vanishing. Governs R9. +- KTD10. Move the upstream-drift lane to its own scheduled workflow instead of repairing the flag on the existing job. The current job cannot warn about drift at all: `test.yml` triggers only on `push` and `pull_request`, so it runs when the kit changes and never when Hermes moves — which is the only event it exists to detect. Job-level `continue-on-error: true` compounds it by rendering the job green in the checks list rather than visibly amber. A separate `schedule` + `workflow_dispatch` workflow, outside required checks and carrying no `continue-on-error`, fires on the right event and is honestly red when it fails. This keeps KTD6's settled non-blocking property — a workflow that is not a required check cannot block a merge — while giving the lane a trigger it currently lacks. Governs R8. +- KTD11. Gate each change on `openspec show --diff` in addition to `openspec validate`. A `MODIFIED` header that matches nothing in the main spec passes `validate --strict` at exit 0 and is then refused at archive time, so validation green does not predict a successful archive. Separately, `archive -y` does not block on unchecked tasks; `openspec validate --archived` is the only check that catches them. Governs R15. + +- KTD12. Migrate the kit's own `FakePluginCtx` and the bespoke host-shape classes around it onto the harness, not the fake alone (session-settled: user-approved — chosen over a fake-only swap and over deferring: only the host-shape classes exercise the `references_dir` switch and the missing-registrar mode the way a consumer would, and the fuller migration is what gives the line-delta success criterion a real number). Governs R5. + +A Bake-off was considered for KTD1 and did not qualify: the four candidate mechanisms were already concrete enough to compare directly, and a single probe settled them, so the decision needed judgment rather than development. + +### High-Level Technical Design + +Three OpenSpec changes, cut so each is independently shippable and the dependency runs one way: + +```mermaid +flowchart TB + U1["U1 · openspec init + scaffold 3 changes"] + subgraph A["Change A · add-plugin-test-harness"] + U2["U2 · testing.py: recording fake + replay + pin"] + U9["U9 · shipped checkout resolver"] + U3["U3 · registration & schema assertions"] + U4["U4 · public-surface reachability guard"] + end + subgraph B["Change B · harden-hermes-contract-gates"] + U5["U5 · pin-aware local lane, one discovery policy"] + U6["U6 · blocking gate runs full suite; drift lane moves to own schedule"] + U7["U7 · release-contract assertions for the workflow"] + end + subgraph C["Change C · route-authors-to-the-harness"] + U8["U8 · SKILL.md + plugin-kit.md routing; link test"] + end + U1 --> A + U1 --> B + U2 --> U9 + U2 --> U5 + U2 --> U8 + A --> C +``` + +Change B cannot precede Change A. Its discovery-policy consolidation and full-suite selection are conceptually independent, but all three of its units consume the pin constant U2 places in the harness module: U5 runs the suite at that pin, U6 sources the workflow's pin from it, and U7 asserts the two agree. If the harness slips, Change B waits. The contract lane resolves a host in one policy: + +```mermaid +flowchart TB + S["contract lane starts"] --> E{"HERMES_AGENT_PATH set?"} + E -->|yes| V{"valid checkout?"} + V -->|no| X["refuse: name the bad path"] + V -->|yes| R["run; receipt names the revision"] + E -->|no| P{"pin checkout available?"} + P -->|yes| R + P -->|no| K["exit non-zero, naming the missing input"] +``` + +### Assumptions + +- `openspec validate` accepts a change whose `.openspec.yaml` sets `skip_specs: true` for tooling-only work; the template states this and the validator's error message names it as the remedy. +- The deployed pin `f80f453` remains the revision infra deploys for the life of this work. If infra promotes mid-flight, R6's constant changes value, not shape. + +### Sequencing + +U1 first and outside any change (a change cannot scaffold itself). Then Change A (U2 → U3, U4), then Change B (U5 → U6 → U7), then Change C (U8). Within Change B, U7 lands with or after U6 so the assertion and the workflow move together. + +OpenSpec has no cross-change dependency mechanism — there is no `depends_on`, and nothing in its status, validate, or doctor output models one. Ordering is therefore a convention this plan asserts, enforced only indirectly: a later change's `MODIFIED` delta must be written against the post-archive main spec or validation rejects it. Because the three changes here touch disjoint capabilities, that indirect enforcement does not apply, so the sequence above is the only thing keeping them in order. Archive them in that order. + +--- + +## Implementation Units + +### U1. Initialize OpenSpec and scaffold the three changes + +- Goal: OpenSpec exists in the repo and the three change directories are created, so subsequent units author into them. +- Requirements: R15 +- Dependencies: none +- Files: `openspec/config.yaml`, `openspec/changes/add-plugin-test-harness/.openspec.yaml`, `openspec/changes/harden-hermes-contract-gates/.openspec.yaml`, `openspec/changes/route-authors-to-the-harness/.openspec.yaml`, `justfile`, `.gitignore` +- Approach: + 1. OpenSpec is already at 1.13.1 — upgraded from 1.13.0 during planning, because those two releases together fix four defects where archive exited 0 having applied less than the delta specified, and a silent partial archive is the worst failure mode for a spec store meant to be authoritative. Confirm the version before initializing rather than assuming; a machine that missed the upgrade reintroduces those defects. + 2. Initialize with agent-instruction files suppressed, per the confirmed scope — the repo's `AGENTS.md` already owns agent guidance and a second instruction surface would compete with it. Verified that this writes nothing outside the project and leaves `AGENTS.md` untouched. + 3. Create the three changes named above. + 4. Set `skip_specs: true` on the two changes that alter no capability requirements (gates, routing). The harness change introduces a new capability and carries a real spec delta, so it does not get the marker. The shipped template is explicit that a requirement must not be invented to satisfy validation. + 5. Populate `openspec/config.yaml`'s `context:` with the repo's stack and conventions so artifact authoring is grounded. + 6. Add a `justfile` recipe that refuses to run when the installed OpenSpec is below the floor, and route `validate`, `show --diff`, and `archive` through it. Every other tool this repository depends on carries an enforced version — `just` is pinned in CI, actions are SHA-pinned — while the archive-correctness property this plan rests on would otherwise live only on whichever machine happened to upgrade. +- Patterns to follow: `openspec init --tools none` produces only `config.yaml`, `changes/archive/.gitkeep`, and `specs/.gitkeep` — verified by probe in a scratch repository. A new capability's delta needs a real `## Purpose`; omitting it passes validation and then bakes a placeholder into the archived spec permanently. +- Test expectation: none — scaffolding. Validation is U1's verification, below. +- Verification: `openspec list` shows three changes; `openspec validate` passes for each; `openspec show --diff` resolves cleanly per KTD11; `openspec status --change ` reports the `proposal → (specs, design) → tasks` progression. + +### U2. Ship `hermes_plugin_kit/testing.py` with a host-derived fake and the pin constant + +- Goal: a consumer installing the wheel can import a fake plugin context that fails when the real host's registrar signatures drift, plus the deployed pin as data. +- Requirements: R1, R2, R3, R4, R6; mechanism per KTD1, KTD2, KTD4, KTD7 +- Dependencies: U1 +- Files: `hermes_plugin_kit/testing.py`, `hermes_plugin_kit/__init__.py`, `tests/test_testing_harness.py` +- Approach: + 1. Add the flat module per KTD2 and re-export from `__init__.py` following the `observability.py` precedent. + 2. Build the fake as a permissive recorder that captures each registration call's arguments, and give it a strict mode that replays a call through the real signature at call time when a host is available. Putting the replay in the fake — not only in the kit's contract lane — is what makes a consumer's own direct calls drift-checked; a lane-only check leaves them invisible. + 3. Carry `name` and `config` as first-class constructor arguments — `load_plugin_config` reads `ctx.manifest.config` and `register_plugin` resolves receipt identity from `ctx.manifest.name`, and every existing fake bolts this on ad hoc. + 4. Provide a switch for whether the host's `register_skill` accepts `references_dir`, so both branches of the kit's capability probe are exercisable. + 5. Provide a "host lacks registrar X" mode for the runtime-gated registration paths. + 6. Expose the pin as a module constant per KTD4. + 7. Keep Hermes imports lazy so no test-framework or host import happens at module import time, per R1. +- Execution note: write the drift test first — a fake that does not fail against a host with an added required parameter is the defect this unit exists to prevent. +- Test scenarios: + - Replay against a host whose registrar gained a required parameter: fails, naming that parameter. + - Replay against a host that renamed a parameter: fails, naming the unexpected keyword. + - Replay against a host that removed a registrar entirely: fails, naming the missing method. + - Replay against the unchanged real host: clean, and the receipt matches. + - No Hermes checkout resolvable: the fake still records and the result reports that no replay was performed — not that it passed. + - Constructed with `name` and `config`: `load_plugin_config` returns the supplied config, and the receipt carries the supplied plugin name. + - `references_dir`-unsupported mode: the kit's capability probe takes the retry branch and the skill still registers. + - "Host lacks registrar" mode: `register_plugin` raises the unsupported-context error rather than silently skipping the surface. + - Module import performs no Hermes import and no test-framework import. +- Verification: the drift scenario fails against a mutated host signature and passes against the real one; importing the module in a clean interpreter pulls in neither Hermes nor a test framework. + +### U3. Registration, receipt, and schema assertion helpers + +- Goal: a consumer asserts the kit's registration contracts without copying literals out of the kit's own tests. +- Requirements: R4, R5; mechanism per KTD1, KTD3, KTD7, KTD12 +- Dependencies: U2 +- Files: `hermes_plugin_kit/testing.py`, `tests/test_testing_harness.py`, `tests/test_kit.py` +- Approach: + 1. A receipt assertion pinned to the **log** field order per KTD3, tolerant of which surfaces are populated and rendering empties the way the kit does. + 2. A duplicate-detection assertion covering the distinct registrar messages, including that the same name on a slash command and a CLI command is permitted. + 3. A deterministic-ordering assertion — every registrar loop in the kit sorts, and a consumer should be able to prove its own registration inherits that. + 4. A schema-convention assertion mirroring the kit's own: arguments under `function.parameters`, no top-level `properties`, object-typed parameters, and the `_required`/`_example` folding. + 5. A signature-conformance report per R4 that names the drifted registrar and the parameter delta, shaped like the kit's existing structured receipts rather than a bare raise. +- Test scenarios: + - Receipt assertion passes for a plugin registering every surface, and fails with a readable diff when one surface is missing. + - Receipt assertion fails if field order is permuted — proving it pins log order, not dataclass order. + - Duplicate tool name is rejected; identical name across slash and CLI is accepted. + - Registration submitted out of alphabetical order still yields sorted receipt output. + - A schema with flattened top-level arguments is rejected; a conforming one passes. + - Conformance report against a host with an added required parameter names that parameter; against an unchanged host it reports clean. +- Verification: the kit's own registration assertions are expressed through these helpers with no loss of coverage, and the migration removes more lines than it adds. + +### U4. Public-surface reachability guard + +- Goal: a documented name cannot be unreachable from an installed wheel. +- Requirements: R12 +- Dependencies: U2, U3 +- Files: `hermes_plugin_kit/__init__.py`, `tests/test_testing_harness.py`, `justfile`, `.github/workflows/test.yml` +- Approach: + 0. Give the installed-artifact check somewhere to run: a `justfile` recipe that builds, installs into a throwaway environment, and imports through the public path, invoked by a CI job. The Verification Contract names this gate, and without a recipe it either goes unrun or collapses into a unit test executing in the source tree — which is the one place the failure cannot appear. + 1. Add the harness names to `__all__`. + 2. Add `plugin_reference_tool`, which is documented in `README.md` and `skills/hermes-plugins/references/plugin-kit.md` and tested in `tests/test_kit.py`, but is absent from `__all__` today — the drift this unit prevents has already happened once on the newest agent-facing feature. + 3. Take the guard's input set from the `Kit API` column of the Surface Map table in `skills/hermes-plugins/references/plugin-kit.md` — the one place the kit enumerates its own public names. Scraping the README instead would sweep up host-side names like `ctx.register_tool` and fail falsely, and the README has no API-surface section to key off. Assert every name in that column is in `__all__` and importable from the package root. + 4. Have the recipe from step 0 import every `__all__` name from the installed wheel, and run it in the existing packaging job after the metadata check. A module present in an archive is not the same as a module importable after installation, which is what this gate claims to prove. +- Test scenarios: + - Every name in `__all__` is importable from the package root. + - A name listed in the Surface Map's `Kit API` column but missing from `__all__` fails the guard — verified by temporarily removing one. + - The built wheel contains `hermes_plugin_kit/testing.py`; importing it from a clean install succeeds. +- Verification: `plugin_reference_tool` and the harness names appear in `__all__`, and the wheel check fails if the module is dropped from the packaging manifest. + +### U9. Shipped checkout resolver + +- Goal: a consumer with no Hermes checkout reaches the replay instead of the record-only path. +- Requirements: R17; mechanism per KTD7, under the fetch-when-missing Key Decision +- Dependencies: U2 +- Files: `hermes_plugin_kit/testing.py`, `tests/test_testing_harness.py` +- Approach: + 1. Export a resolver from the harness that returns a usable checkout at the pin. This belongs in Change A, not the contract-lane change: it is a harness capability a consumer imports, and leaving it in the lane would have left the only concrete implementation inside a `just` recipe consumers do not install — which is what made R17 unreachable in the first place. + 2. Honor an explicit `HERMES_AGENT_PATH` first and always; it wins over any fetch. + 3. Fetch at the pin when nothing resolves, into a cache reused across runs so it happens at most once per machine. + 4. Bound the fetch with a timeout and never retry silently. A failure — offline, sandboxed, no network — surfaces as R3's ordinary unchecked result naming the revision and the reason, not a hang and not a raw subprocess error. +- Execution note: write the offline case first. A resolver that hangs or raises opaquely in a sandboxed CI run is worse than the record-only path it replaces. +- Test scenarios: + - Explicit `HERMES_AGENT_PATH` present: used as-is, no fetch attempted. + - Nothing resolvable and fetch succeeds: returns a checkout whose HEAD is the pin, and the replay then runs. + - Second call after a successful fetch: reuses the cache rather than fetching again. + - Fetch fails or the network is unavailable: returns the unchecked result naming the revision and the reason, within the timeout, without raising a subprocess error. + - Cache present but at the wrong revision: refused or re-resolved, never used as if it were the pin. +- Verification: in a container with no Hermes checkout and no network, a consumer-shaped run finishes promptly with an explicit unchecked receipt; with network, the same run completes a replay against the pin. + +### U5. Pin-aware local contract lane with one discovery policy + +- Goal: a local contract run targets the deployed pin and states which Hermes revision it exercised, or refuses. +- Requirements: R9, R10, R11; mechanism per KTD7, KTD8 +- Dependencies: U2 +- Files: `justfile`, `tests/test_hermes_contract.py`, `tests/test_context_engine_contract.py`, `tests/test_testing_harness.py` +- Approach: + 1. Teach `prepare-hermes-agent` to check out a requested ref; today it clones the default branch only, so the pinned revision is unreachable outside CI and `just test-contract` can only ever test upstream main. + 2. Add a recipe that runs the contract suite at the pin from U2's constant, and keep a separate recipe for upstream main. + 3. Consolidate both contract modules onto the single discovery policy in KTD8, replacing the env-only silent-skip variant. + 4. Emit a receipt naming the Hermes revision exercised. + 5. Resolve the local/CI asymmetry: a bare `just test` must not quietly run the contract suite against whatever branch a developer's `~/hermes-agent` happens to sit on, nor report green when it skipped everything. + 6. Per KTD9, assert the executed-test count rather than reading the exit status alone, and add a guard test outside each contract module's `skipUnless` so a configured-but-broken lane fails instead of vanishing. Capture the exit status directly rather than through a pipe, which would report the filter's status instead. + 7. Give the guard an explicit intent signal — an environment variable the contract recipes set — and have it fail only when that signal is present. Without one the guard cannot distinguish an intended contract run from an ordinary `just test`, so 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 at all, leaving R9 unenforced. + 8. For any pin-targeted run, compare the resolved checkout's actual HEAD against the pin and refuse on mismatch, naming expected and actual. `HERMES_AGENT_PATH` stays authoritative for *where* the checkout is, but a stale path currently sails through the pin lane and produces a receipt for the wrong revision — and CI inheriting that variable would go green against an incompatible host. + 9. Give the pin recipe and the upstream recipe separate checkout directories. They resolve to the same directory today, and `prepare-hermes-agent` swallows the pull error a detached checkout produces, so an upstream run after a pinned one would silently re-exercise the pin while reporting upstream. + 10. Make `just test-context-engine-contract` require `HERMES_AGENT_PATH` explicitly; it currently sets no variable and has no checkout dependency, so a missing variable produces a silent all-skip. +- Execution note: reproduce today's misleading-green locally first — a checkout on an unrelated branch, and no checkout at all — so the fix is measured against the actual failure. +- Test scenarios: + - `HERMES_AGENT_PATH` pointing at a non-checkout: refuses and names the bad path; does not skip. + - No checkout resolvable: the run exits non-zero, naming the missing input. It may describe itself as a skip, but per R9 it must not report success. + - Pin recipe against the pinned revision: full contract suite passes and the receipt names `f80f453`. + - Upstream recipe against a revision with the #99220 egress change: the media contract fails and the receipt names that revision. + - Both contract modules resolve a host by the same policy, verified by pointing the same bad path at each. + - A run in which every contract test skips is reported as a failure, not a pass — the case Python 3.11 exits 0 on. + - A run that collects zero tests is reported as a failure — likewise exit 0 on 3.11. + - `HERMES_AGENT_PATH` unset for the context-engine recipe: the recipe refuses rather than skipping. + - A bare `just test` with no Hermes checkout and no intent signal stays green, while a contract recipe that cannot resolve a host fails. + - Running the upstream recipe after the pin recipe exercises upstream, not the pinned revision left behind by the previous run. +- Verification: a run's receipt names the revision tested and the executed-test count; the pinned recipe reproduces the green result at `f80f453` and the upstream recipe reproduces the media failure at current main; deliberately emptying the lane produces a failure rather than a green run. + +### U6. Blocking gate runs the full suite; drift lane moves to its own schedule + +- Goal: the gate that blocks covers the whole contract at the pin, and the lane that warns actually runs when Hermes moves. +- Requirements: R7, R8; mechanism per KTD4, KTD6, KTD10 +- Dependencies: U5 +- Files: `.github/workflows/test.yml`, `.github/workflows/hermes-drift.yml`, `tests/fixtures/known-hermes-drift.txt` +- Approach: + 1. Point the blocking pinned job at the full contract suite instead of the context-engine module alone. The full suite is already green at that pin — verified by running it there, so widening the job adds coverage rather than risk on the day it lands. + 2. Collapse the two pin literals to one and make it test-enforced against U2's constant per KTD4, rather than leaving two copies that agree with nothing. + 3. Move the upstream-drift job out of `test.yml` into a scheduled workflow per KTD10, dropping `continue-on-error` and leaving it outside required checks. + 4. Have it write the upstream revision and the failing test names to the run's job summary, on a step that runs even after the contract step fails. A reporting step without that condition is skipped by the failure it exists to report, so it would fire only when there is no drift. + 5. Compare failures against a committed baseline and surface anything unrecognized under its own heading. Match on a stable fingerprint of the failure, not the test name alone: a baselined test whose assertion or error has changed is a new break wearing a known name, and a name-only baseline would file it as expected. The #99220 media failure is red against upstream today and stays red by design, so an unbaselined report names the same failure every run and is ignored within a week — the lane would pass its acceptance criterion on landing and stop informing anyone immediately after. Baselining is what makes the next genuinely new break visible. + 6. Schedule it daily, so R8's 24-hour lag bound is a property of the workflow rather than a hope. Add an activity trigger alongside the schedule: scheduled workflows are disabled after 60 days of repository inactivity on public repositories, and this repository is public — a drift alarm that silently switches itself off is worse than none. +- Patterns to follow: actions stay 40-hex SHA-pinned with a trailing version comment, `just` steps stay behind `extractions/setup-just` at the asserted version, `test.yml`'s top-level permissions stay `{contents: read}` — all enforced by `tests/test_release_contract.py`. +- Test scenarios: covered by U7's workflow assertions; this unit's own proof is a scheduled run and a manual dispatch. +- Verification: the blocking job runs the full contract suite and passes at the pin; a manual dispatch of the drift workflow against current upstream reproduces the media failure, shows the revision and failing tests on the run summary with that failure recognized as baselined rather than new, and does not affect any required check. + +### U7. Release-contract assertions for the new workflow shape + +- Goal: the workflow guarantees this plan introduces cannot silently regress. +- Requirements: R1, R7, R8; mechanism per KTD5 +- Dependencies: U6 +- Files: `tests/test_release_contract.py` +- Approach: extend the existing workflow-parsing tests — do not add a parallel mechanism. Assert that the blocking contract job selects the full suite, that the workflow's pin equals the harness constant, that the drift workflow carries a schedule trigger and stays out of required checks, and that the built wheel actually contains the harness module. That last assertion matters because the existing packaging gate runs `twine check`, which validates metadata and never inspects archive contents. +- Test scenarios: + - Blocking job reduced back to the context-engine module only: assertion fails. + - Workflow pin edited to disagree with the harness constant: assertion fails. + - Drift workflow's schedule trigger removed: assertion fails. + - Drift workflow's reporting step loses its run-after-failure condition: assertion fails, since the step would then be skipped by the very failure it reports. + - Known-drift baseline file missing: assertion fails. + - A fixture run with one baselined failure and one unrecognized failure labels them known and new respectively — file existence alone would let the classification regress while every test stayed green. + - Harness module dropped from the packaging manifest: the wheel-membership assertion fails, where `twine check` would still pass. + - Existing SHA-pinning, `just`-only, and `pull_request_target` assertions still pass, and the new drift workflow satisfies them too. +- Verification: each regression above is caught by a failing test, confirmed by making the edit and observing the failure. + +### U8. Route authors to the harness + +- Goal: the skill's existing instruction to run contract tests becomes an instruction an author can actually follow. +- Requirements: R13; mechanism per KTD7 +- Dependencies: U2, U3 +- Files: `skills/hermes-plugins/SKILL.md`, `skills/hermes-plugins/references/plugin-kit.md`, `tests/test_skills.py` +- Approach: + 1. Rewrite the Validation section's contract-test instruction to name the harness by **import path** and the pin by constant. It cannot route via kit-repo paths: the skill is consumed as a symlink from a kit checkout, and `tests/` never reaches a consumer install. + 2. Add the harness row to the API routing table in `plugin-kit.md`. + 3. Give the lane a Python-invocable form in the documentation, since consumer repositories predominantly use `make`; `just test-contract` is unusable there. + 4. Document the resolver from U9 as part of the lane, so an author reaches it without reading this plan. Documentation alone is not enough — without the shipped step, provisioning lives only in the kit's `prepare-hermes-agent` recipe, which no consumer installs, and every consumer gets the record-only path while the drift check the harness exists for never runs for them. + 5. Extend `tests/test_skills.py` to validate relative links in `references/*.md`. It currently checks links in `SKILL.md` bodies only, so reference-file links rot unnoticed — the existing `../../../` links resolve inside a kit checkout but nothing tests them either way. + 6. State the minimum kit revision that provides the harness everywhere the skill names an import path. The skill is read from a moving symlinked checkout while consumers pin the kit immutably, so without it an author on an older pin follows the instruction and gets an import error from a module their kit predates. + 7. `AGENTS.md` already binds `plugin-kit.md` to public-API changes; cite that rule rather than inventing a new gate. +- Test scenarios: + - A broken relative link in `references/plugin-kit.md` fails the extended skills test — verified by introducing one. + - Existing `SKILL.md` link validation still passes. + - Every import path named in the skill and the reference resolves against the installed package. + - Every harness import path the skill names is accompanied by the minimum kit revision that provides it. + - Following the documented provisioning step in a repository with no Hermes checkout results in a run where the replay actually engages, not a record-only run. +- Verification: following the skill's Validation section verbatim in a consumer repository with no Hermes checkout yields an explicit receipt or refusal, not a green run with the contract suite absent. + +--- + +## System-Wide Impact + +- Fourteen consumer plugin repositories are affected but none are changed, per R16. Their existing fakes keep passing — including the eight positional ones that KTD1 shows are frozen snapshots rather than strict contracts. The harness protects only repositories that adopt it, so the census in the Problem Frame is a measure of remaining exposure, not of work completed. +- CI gating semantics get stricter at the same pin. The blocking job goes from 110 lines of contract coverage to the full suite, which is already green at `f80f453` — so this is added coverage, not added risk, on the day it lands. From then on, any kit change that breaks a contract the gate previously ignored will fail the build. +- The public API grows. Additive exports plus `plugin_reference_tool` make this a minor release; see the contingency patch below for keeping that to a single bump. +- The pin becomes an explicit coupling point between this repository and infra's deployed snapshot. Today the coupling exists but is invisible, encoded in two workflow literals. Making it a constant does not create the dependency — it makes it readable, and it makes a snapshot promotion a change this repository must respond to. +- The skill becomes load-bearing infrastructure rather than documentation. After U8 it is the only channel through which an author or coding agent learns the harness exists, which is why `AGENTS.md`'s existing rule binding `plugin-kit.md` to public-API changes has to be honored rather than treated as a formality. + +--- + +## Risks and Contingency Patches + +Each risk names the signal that it has fired and the smallest patch that recovers. + +- The harness fetches a checkout in an environment that cannot reach the network — a sandboxed or offline CI runner, or an air-gapped machine. This is the accepted cost of the settled fetch-when-missing decision, not a reason to revisit it. **Signal:** a consumer's suite hangs or fails inside the harness rather than in their own code. **Patch:** an explicit `HERMES_AGENT_PATH` is checked first and always wins, the fetch is cached so it happens at most once per machine, and a failed fetch surfaces as the same explicit unchecked result R3 already defines — naming the revision and the reason — rather than hanging or raising an opaque subprocess error. Bound the fetch with a timeout and never retry silently. +- A registrar is attached dynamically rather than declared on `PluginContext`, so there is no signature to replay against. **Signal:** the U2 drift scenario passes when it should fail for that registrar. **Patch:** treat an unresolvable registrar as a drift report of its own — "could not check this surface" — rather than silently clean. The one registrar known to take trailing `**kwargs` after its required parameters still binds its required portion, so partial coverage is the realistic outcome, not zero. +- Hermes is importable but too stale for the replay to mean anything. **Signal:** the existing staleness guards raise on a checkout users actually have. **Patch:** treat a stale host like an absent one — R3's no-replay-performed path already covers it; widen the guard rather than adding a third mode. +- Record-and-bind proves nothing about host→plugin **callback** drift. If Hermes changes how it *invokes* a registered hook or middleware, replaying the kit's outbound registration calls is silent on it. **Signal:** a hook breaks in production against a host the harness called clean. **Patch:** none available in the harness — this is the residual that makes the contract lane mandatory rather than optional, because only the real dispatchers exercise it. R7's full-suite gate is what covers this; do not let the harness's existence become an argument for weakening that gate. +- Infra promotes the Hermes snapshot mid-flight, so `f80f453` stops being the deployed revision. **Signal:** the contract suite fails at the new pin — most likely the #99220 media contract, which is the known break. **Patch:** the pin is a constant by then (R6), so the value changes in one place. If the new pin fails the full suite, land U6 with the blocking job still at the old pin and open the promotion as its own change; do not weaken the gate to make a red suite green. +- `openspec validate` rejects a change shape this plan assumes. **Signal:** U1's verification fails. **Patch:** this is a Goal Capsule stop condition — stop and ask rather than reshaping the work to fit the tool. The fallback is to merge Changes B and C, which are the two carrying `skip_specs: true`. +- A change validates but refuses to archive, because a `MODIFIED` header matches nothing in the main spec. **Signal:** `openspec validate --strict` is green and `archive` reports a spec-update failure. **Patch:** the refusal is atomic — no files change — so re-derive the delta from the current main spec and retry. KTD11's `--diff` gate is what catches this before archive rather than at it. +- The scheduled drift workflow is auto-disabled after 60 days of repository inactivity. **Signal:** no drift runs appear despite the schedule. **Patch:** U6's activity trigger is the prevention; if it still trips, a manual dispatch re-enables it, and the tracking issue's absence is the tell that nobody should read silence as "no drift." +- The harness lands but consumers do not adopt it, leaving fifteen fakes and one more surface to maintain. **Signal:** no consumer imports it within a release cycle. **Patch:** out of scope per R16, but the cheapest recovery is converting one consumer as a worked example; `hermes-plugin-memory-sync` is the best candidate since its fake already carries `manifest.config` and is closest to the harness shape. +- Adding names to `__all__` changes the public surface and therefore the semver story. **Signal:** the release workflow computes a different bump than expected. **Patch:** additive exports are a minor bump; keep U4's `plugin_reference_tool` addition in the same change as the harness so one minor release covers both, rather than shipping a bare export bump. + +--- + +## Verification Contract + +| Gate | Command | Applies to | Proves | +|---|---|---|---| +| Unit suite | `just test` | U2-U9 | Kit and harness behavior. This is a source-tree unit run and makes no contract-coverage claim — with no host and no intent signal it stays green by design, per U5. The contract gates below are the only ones that must refuse or report a revision | +| Contract at pin | pin-targeted recipe from U5 | U5, U6 | Full contract suite green at the deployed Hermes revision, with a non-zero executed-test count | +| Contract vs upstream | upstream recipe from U5 | U5 | Reproduces the #99220 media failure with a named revision | +| Release contract | `just test-release` | U6, U7 | Workflow shape, SHA pinning, pin/constant agreement, drift-workflow schedule, wheel membership | +| Packaging | `just build` then `just check-dist` | U2, U4 | Metadata valid. Not sufficient alone — `twine check` never inspects archive contents, so U7's wheel-membership assertion is the real gate | +| Installed reachability | U4's build-install-import recipe, run by its own CI job | U4 | Public names reachable from the wheel, not just the source tree | +| Change validity | `openspec validate` and `openspec show --diff` per change, behind U1's version-floor recipe | U1-U9 | Each change is well-formed, independently reviewable, and will actually archive — on a toolchain new enough to archive it completely | +| Archived integrity | `openspec validate --archived` after each archive | U1 | Tasks were actually checked before archiving. `archive -y` does not block on unchecked tasks, so nothing else catches it | + +Record which Hermes revision each contract run exercised and how many tests ran. A contract gate that skipped is not a contract gate that passed — and on the pinned Python version it exits 0 either way, so the count is the evidence, not the exit status. + +--- + +## Definition of Done + +Global: + +- All three OpenSpec changes validate, and each is reviewable without the other two. +- Every gate in the Verification Contract has run, with the contract gates reporting the revision they exercised rather than an unqualified pass. +- No abandoned experimental code remains — in particular, no second fake implementation left behind if KTD1's contingency patch was taken. +- `deliver_media` and `invoke_host_tool` behavior is unchanged, per R14. +- No consumer repository was modified, per R16. The diff touches this repository only. + +Per unit: + +| Unit | Done when | +|---|---| +| U1 | The version floor is enforced by a recipe, not a local upgrade; three changes exist, validate, and resolve under `--diff`; `skip_specs` set only on the two tooling changes | +| U2 | Replay fails against added, renamed, and removed registrar parameters, naming the registrar and parameter in each case; module imports without Hermes or a test framework | +| U3 | Receipt assertion pins log order; the kit's own fake is migrated onto the harness with no loss of coverage | +| U4 | `plugin_reference_tool` and harness names in `__all__`; the build-install-import recipe runs in CI and succeeds | +| U9 | Offline run returns an explicit unchecked receipt promptly; online run completes a replay at the pin; cache reused, never used at the wrong revision | +| U5 | Run names the revision and executed-test count or refuses; pin recipe green at `f80f453`, upstream recipe red on media; an emptied lane fails | +| U6 | Blocking job runs the full suite at the pin; drift workflow runs on its own schedule, outside required checks, and surfaces the revision and failing tests on the run summary | +| U7 | Each named regression is caught by a failing test, including the wheel-membership case | +| U8 | Skill routes by import path, names the minimum kit revision, and documents provisioning; a broken reference link fails the extended test | + +Archive each change in the sequence the Planning Contract states, and confirm its tasks are checked before archiving — `archive -y` does not block on unchecked tasks, and `openspec validate --archived` is the only thing that catches them afterwards. + +--- + +## Open Questions + +- Is `unittest` the right surface for a consumer-facing harness, given consumers may use `pytest`? The kit is stdlib-`unittest` throughout, and KTD7's composable pieces are framework-neutral, but the assertion helpers will have a framework flavor. Default if unanswered: keep helpers framework-neutral by returning structured results and letting the consumer assert. + +--- + +## Sources and Research + +Repository evidence: + +- `pyproject.toml:34` — explicit `packages` list; the built wheel contains only `hermes_plugin_kit/__init__.py` and `observability.py`. Grounds KTD2. +- `hermes_plugin_kit/__init__.py` — `RegistrationSummary` dataclass order differs from the `log_registration_summary` emission order. Grounds KTD3. +- `.github/workflows/test.yml:52,66` — the deployed pin as two unlinked literals; `:67` selects only the context-engine module; `:73` carries `continue-on-error: true`. Grounds R6, R7, R8. +- `tests/test_hermes_contract.py:37-126,233` — authoritative-env discovery with staleness guards, and the `skipUnless` gate that turns an absent host into a silent green. Grounds KTD8, R9. +- `tests/test_context_engine_contract.py:16-36` — the competing env-only discovery policy. Grounds R11. +- `tests/test_release_contract.py:638,649,687,691` — existing workflow-as-contract assertions; job names are asserted nowhere. Grounds KTD5. +- `tests/test_skills.py` — validates links in `SKILL.md` bodies only. Grounds R13. +- `skills/hermes-plugins/SKILL.md` Validation section and `references/plugin-kit.md:98-99` — the instruction and the doctrine the repo cannot currently deliver. Grounds the Problem Frame. +- `justfile:40-51` — `prepare-hermes-agent` clones the default branch with no ref support. Grounds R10. +- `README.md:689` — the skill is consumed as a symlink from a kit checkout. Grounds the deferred version-coupling item. +- Consumer census across fifteen local repositories that define a fake plugin context — fourteen consumers plus the kit. Among the fourteen consumers: eight strict-positional `register_skill` fakes, three permissive `**kwargs`, three defining no skill registrar. The kit's own fake is the fourth permissive one. Grounds the Problem Frame and R2. + +External and empirical: + +- Hermes `866332bf` (#99220) added `gateway/relay/egress.py`, absent at `f80f453`. The kit's media contract passes at `f80f453` and fails at `a6bab19`. Grounds the Problem Frame and R14's scope exclusion. +- OpenSpec, observed via CLI in scratch repositories on both 1.13.0 and 1.13.1: `spec-driven` is the only schema; artifacts form `proposal → (specs, design) → tasks`; spec deltas use `## ADDED/MODIFIED/REMOVED/RENAMED Requirements` with a required `#### Scenario:` block per requirement; `openspec validate` rejects a zero-delta change unless `.openspec.yaml` sets `skip_specs: true`, and the shipped template warns against inventing a requirement to satisfy it; `init --tools none` writes only `config.yaml` and two `.gitkeep` files. Re-verified unchanged after the 1.13.1 upgrade. Grounds U1 and R15. +- `openspec archive` folds a completed change's deltas into `openspec/specs/` and carries its own `--skip-specs` flag for "infrastructure, tooling, or doc-only changes" — an archive-time flag distinct from the `.openspec.yaml` marker, and the two tooling changes will need it at archive time as well as at validation time. Grounds U1's marker decision and the Definition of Done. +- Drift-mechanism probe, run twice independently with matching results: a permissive `**kwargs` fake and a hand-written positional fake mirroring the current host both pass when the host gains a required parameter; comparing the fake's own signature to the real one also catches nothing; `create_autospec` catches it but needs the real class importable; replaying recorded call arguments through the real signature catches an added required parameter, a renamed parameter, and a removed registrar. Grounds KTD1. +- Python 3.11 — the version CI pins — exits 0 from `unittest` both when every test skips and when zero tests are collected; 3.12 exits 5 with `NO TESTS RAN`. Verified on both. Grounds KTD9 and R9. +- `.github/workflows/test.yml` triggers only on `push` and `pull_request`, so the upstream-drift job cannot fire on the event it exists to detect. Job-level `continue-on-error` additionally renders the job green in the checks list rather than amber. Grounds KTD10. +- OpenSpec: `archive` is the only merge path into `openspec/specs/` and rewrites each capability spec as `# Specification` / `## Purpose` / `## Requirements` / `### Requirement:` / `#### Scenario:`; failures are atomic. A `MODIFIED` header matching nothing passes `validate --strict` at exit 0 but is refused at archive; `archive -y` does not block on unchecked tasks. No cross-change dependency mechanism exists. Latest is 1.13.1, not the installed 1.13.0, and the two releases fix four silent partial-archive defects. Grounds KTD11, U1, and the Sequencing note. +- Test-support distribution precedents for an in-package `pkg.testing` surface: `django.test`, `starlette.testclient` (heavy dependency behind an extra with a guarded import), `httpx.MockTransport` in-package versus `respx` separate, and Celery keeping light fixtures in-package while splitting the heavy variant into its own distribution. A `pytest11` entry point is avoided because it auto-loads into every pytest run in the environment. The decisive local constraint is `AGENTS.md`'s same-revision pinning rule: a second distribution would create a second pin that can skew. Grounds KTD2 and KTD7. +- `twine check` validates metadata only and never inspects archive contents, so the existing packaging gate cannot catch a module missing from the wheel. Grounds U7's wheel-membership assertion. + +Research gaps, recorded honestly: `failure()`'s outcome-versus-conclusion semantics in GitHub Actions were not verified, so U6 should key its reporting on a step's `outcome` explicitly rather than relying on that function. Not probed: OpenSpec custom schemas, stores, and `openspec view`. Separately, this repository's pinned `actions/checkout` and `astral-sh/setup-uv` majors are behind current releases; that is pre-existing and outside this plan's scope, but it is worth its own change. diff --git a/hermes_plugin_kit/__init__.py b/hermes_plugin_kit/__init__.py index 8da2893..c8e80c9 100644 --- a/hermes_plugin_kit/__init__.py +++ b/hermes_plugin_kit/__init__.py @@ -67,6 +67,7 @@ def register(ctx): from pathlib import Path from typing import Any, Callable, Iterable, Iterator, Mapping, Protocol +from . import testing from .observability import ( ObservabilityEvent, credential_identity_hash, @@ -119,6 +120,13 @@ def register(ctx): "credential_identity_hash", "log_observability_event", "new_correlation_id", + # Documented in README.md and the Surface Map, and tested, but absent from + # this list until now -- the exact drift the reachability guard prevents. + "plugin_reference_tool", + # Consumer-facing test support. The submodule is the public name rather than + # its individual classes, so test doubles stay out of the runtime namespace + # (the shape django.test and starlette.testclient take). + "testing", ] _SPEC_ATTR = "_hpk_tool_spec" diff --git a/hermes_plugin_kit/testing.py b/hermes_plugin_kit/testing.py new file mode 100644 index 0000000..0a4e764 --- /dev/null +++ b/hermes_plugin_kit/testing.py @@ -0,0 +1,693 @@ +"""Consumer-facing test support for Hermes plugins. + +A plugin author needs two things a hand-rolled fake cannot give them: a plugin +context that works with no Hermes checkout present, and a way to find out that +the host's registrar signatures changed underneath them. Those pull in opposite +directions, so this module separates them. + +:class:`RecordingPluginContext` records the registration calls a plugin makes +and needs no host at all. :meth:`RecordingPluginContext.check_against_host` +replays those recorded arguments through the real ``PluginContext`` signatures +wherever a host *is* importable, and reports what drifted. + +That split is deliberate. A permissive fake accepts every future signature, and +a hand-written fake mirroring today's host is a frozen snapshot of one revision +-- both pass unchanged when the host gains a required parameter. Comparing a +fake's own signature to the real one catches nothing either, because ``**kwargs`` +is compatible with every signature by construction. Binding the *recorded +arguments* is what catches it, along with removed registrars. + +Renames need one extra step. Binding surfaces a renamed *keyword* on its own, as +an unexpected-keyword error, but it cannot see a renamed *positional* parameter +-- Python binds those by position, so the call still fits. For the registrars +the kit calls positionally, the replay therefore compares parameter names as +well, against the baseline in ``_POSITIONAL_PARAMS``. + +Nothing here imports hermes-agent or a test framework at module import time. +""" + +from __future__ import annotations + +import inspect +import os +import subprocess +import sys +from pathlib import Path +from dataclasses import dataclass, field +from types import SimpleNamespace +from typing import Any, Callable, Iterable, Mapping, Sequence + +__all__ = [ + "DEPLOYED_HERMES_REVISION", + "RECEIPT_FIELD_ORDER", + "CheckResult", + "ResolvedHost", + "Drift", + "DriftReport", + "RecordingPluginContext", + "check_registration", + "receipt_fields", + "resolve_hermes_checkout", +] + +#: Receipt fields in the order ``log_registration_summary`` emits them. +#: +#: This is deliberately not ``RegistrationSummary``'s dataclass field order -- +#: the two genuinely differ, and the logged string is the contract AGENTS.md +#: pins. Asserting the dataclass order instead would pass while the external +#: contract drifted. +RECEIPT_FIELD_ORDER: tuple[str, ...] = ( + "commands", + "cli_commands", + "tools", + "middlewares", + "hooks", + "skills", + "skipped_optional_skills", + "memory_providers", + "image_gen_providers", + "video_gen_providers", + "capabilities", + "context_engine", + "context_engine_registration", +) + +#: The hermes-agent revision this kit's contract lanes are pinned to. +#: +#: The CI workflow keeps its own literal -- ``actions/checkout`` consumes the +#: ``ref:`` before a Python toolchain exists, so the workflow cannot read this +#: value -- and a release-contract test asserts the two agree. +DEPLOYED_HERMES_REVISION = "f80f453ae0679347e38abc917c7f94f717bf96c5" + +#: Parameter names the kit's registrars pass positionally, in order. +#: +#: These are the names a rename would change. A keyword call surfaces a rename +#: on its own as an unexpected-keyword error; a positional one does not, because +#: Python binds by position, so the replay needs a name baseline for these. +#: Registrars the kit calls entirely by keyword are absent and need no baseline. +_POSITIONAL_PARAMS: dict[str, tuple[str, ...]] = { + "register_middleware": ("kind", "callback"), + "register_hook": ("hook_name", "callback"), + "register_memory_provider": ("provider",), + "register_image_gen_provider": ("provider",), + "register_video_gen_provider": ("provider",), + "register_context_engine": ("engine",), +} + +_ALL_REGISTRARS = ( + "register_tool", + "register_command", + "register_cli_command", + "register_middleware", + "register_hook", + "register_skill", + "register_memory_provider", + "register_image_gen_provider", + "register_video_gen_provider", + "register_context_engine", +) + + +@dataclass(frozen=True) +class Drift: + """One registrar whose recorded call no longer fits the host's signature.""" + + registrar: str + detail: str + + def __str__(self) -> str: # pragma: no cover - trivial + return f"{self.registrar}: {self.detail}" + + +@dataclass(frozen=True) +class DriftReport: + """The outcome of replaying recorded calls against a host. + + ``checked`` is the field that matters most: a report that could not run is + not a report that found nothing. ``clean`` is never ``True`` unless the + replay actually happened. + """ + + checked: bool + drifts: tuple[Drift, ...] = () + detail: str = "" + + @property + def clean(self) -> bool: + return self.checked and not self.drifts + + def __bool__(self) -> bool: # pragma: no cover - trivial + return self.clean + + def __str__(self) -> str: + if not self.checked: + return f"unchecked: {self.detail}" + if not self.drifts: + return "clean" + return "; ".join(str(d) for d in self.drifts) + + +def _positional_names(target: Callable[..., Any]) -> list[str] | None: + """Parameter names a call can reach positionally, excluding ``self``.""" + try: + params = list(inspect.signature(target).parameters.values()) + except (ValueError, KeyError, TypeError): + return None + kinds = (inspect.Parameter.POSITIONAL_ONLY, inspect.Parameter.POSITIONAL_OR_KEYWORD) + return [p.name for p in params[1:] if p.kind in kinds] + + +def _bind( + target: Callable[..., Any], + args: Sequence[Any], + kwargs: dict[str, Any], + expected_positional: Sequence[str] = (), +) -> str | None: + """Return a drift description, or ``None`` when the call still fits. + + ``target`` is looked up on the class, so its first parameter is ``self``; + ``None`` stands in for the instance. Binding raises before any function body + runs, so this never invokes host code. + + Binding alone cannot see a renamed *positional* parameter: Python binds by + position, so ``register_hook(event_name, callback)`` accepts a call written + for ``register_hook(hook_name, callback)`` and reports clean. Keyword calls + do surface a rename, as an unexpected-keyword error. So for the positional + slots a call actually used, compare names as well as arity -- + ``expected_positional`` carries the names the kit's own registrar declares + for those slots, which is the shape the plugin was written against. + """ + try: + inspect.signature(target).bind(None, *args, **kwargs) + except TypeError as exc: + return str(exc) + except (ValueError, KeyError) as exc: # unintrospectable builtin or C callable + return f"signature could not be read ({exc}); this surface was not checked" + + if args and expected_positional: + host_names = _positional_names(target) + if host_names is None: + return None + renamed = [ + f"{was!r} is now {now!r} at position {i + 1}" + for i, (was, now) in enumerate(zip(expected_positional, host_names)) + if was != now + ] + if renamed: + return "positional parameter renamed: " + ", ".join(renamed) + return None + + +class RecordingPluginContext: + """A plugin context that records what a plugin registers. + + Usable with no Hermes checkout present. Pass ``strict_against`` to bind each + call against a host as it is made, or call :meth:`check_against_host` + afterwards to replay everything at once. + + The shape knobs exist so every branch of the kit's own capability probe is + reachable from a test: + + - ``supports_references_dir`` -- whether ``register_skill`` advertises that + keyword at all. + - ``references_dir_probe_lies`` -- a permissive signature that satisfies the + probe and then rejects the keyword at call time. This is the shape that + fools a signature check, and the only way to reach the documented retry. + - ``register_skill_error`` -- raise this from ``register_skill``. Used to + prove the retry stays narrow and does not swallow an unrelated error. + - ``missing_registrars`` -- omit a registrar entirely, which is how a host + predating a surface behaves. + """ + + def __init__( + self, + *, + name: str = "test-plugin", + config: dict[str, Any] | None = None, + supports_references_dir: bool = True, + references_dir_probe_lies: bool = False, + register_skill_error: BaseException | None = None, + missing_registrars: Iterable[str] = (), + strict_against: type | None = None, + context_engine_result: bool = True, + ) -> None: + unknown = sorted(set(missing_registrars) - set(_ALL_REGISTRARS)) + if unknown: + raise ValueError( + f"unknown registrar(s) in missing_registrars: {', '.join(unknown)}; " + f"expected any of {', '.join(_ALL_REGISTRARS)}" + ) + + self.manifest = SimpleNamespace(name=name, config=dict(config or {})) + self.calls: list[tuple[str, tuple[Any, ...], dict[str, Any]]] = [] + + self.tools: list[dict[str, Any]] = [] + self.commands: list[dict[str, Any]] = [] + self.cli_commands: list[dict[str, Any]] = [] + self.middlewares: list[tuple[Any, Any]] = [] + self.hooks: list[tuple[str, Any]] = [] + self.skills: list[dict[str, Any]] = [] + self.memory_providers: list[Any] = [] + self.image_gen_providers: list[Any] = [] + self.video_gen_providers: list[Any] = [] + self.context_engines: list[Any] = [] + + self.context_engine_result = context_engine_result + self.subagent_lifecycle = SimpleNamespace( + launch=lambda request: request, + status=lambda handle: handle, + wait=lambda handle, **kwargs: handle, + cancel=lambda handle, **kwargs: handle, + result=lambda handle: handle, + reconnect=lambda handle: handle, + ) + + self._strict_against = strict_against + self._install_registrars( + supports_references_dir=supports_references_dir, + references_dir_probe_lies=references_dir_probe_lies, + register_skill_error=register_skill_error, + missing=set(missing_registrars), + ) + + # -- recording ----------------------------------------------------------- + + def _record(self, registrar: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> None: + """Capture one call, and bind it now when running strict.""" + self.calls.append((registrar, args, kwargs)) + if self._strict_against is None: + return + target = getattr(self._strict_against, registrar, None) + if target is None: + raise AttributeError( + f"host {self._strict_against.__name__} does not expose {registrar}()" + ) + detail = _bind(target, args, kwargs, _POSITIONAL_PARAMS.get(registrar, ())) + if detail is not None: + raise TypeError(f"{registrar}: {detail}") + + def _install_registrars( + self, + *, + supports_references_dir: bool, + references_dir_probe_lies: bool, + register_skill_error: BaseException | None, + missing: set[str], + ) -> None: + """Bind registrars per instance, so an omitted one is genuinely absent. + + `register_plugin` detects host support with ``callable(getattr(ctx, name, None))``, + so leaving the attribute unset is what makes a missing surface look missing. + """ + + def register_tool( + name, toolset, schema, handler, requires_env=None, description="", emoji="" + ) -> None: + kwargs = dict( + name=name, toolset=toolset, schema=schema, handler=handler, + requires_env=requires_env, description=description, emoji=emoji, + ) + self._record("register_tool", (), kwargs) + self.tools.append(kwargs) + + def register_command(**kwargs) -> None: + self._record("register_command", (), kwargs) + self.commands.append(kwargs) + + def register_cli_command(**kwargs) -> None: + self._record("register_cli_command", (), kwargs) + self.cli_commands.append(kwargs) + + def register_middleware(kind, callback) -> None: + self._record("register_middleware", (kind, callback), {}) + self.middlewares.append((kind, callback)) + + def register_hook(hook_name, callback) -> None: + self._record("register_hook", (hook_name, callback), {}) + self.hooks.append((hook_name, callback)) + + def register_skill_with_references(name, path, description="", references_dir=None) -> None: + kwargs = dict(name=name, path=path, description=description) + if references_dir is not None: + kwargs["references_dir"] = references_dir + self._record("register_skill", (), kwargs) + self.skills.append(kwargs) + + def register_skill_only(name, path, description="") -> None: + kwargs = dict(name=name, path=path, description=description) + self._record("register_skill", (), kwargs) + self.skills.append(kwargs) + + def register_skill_lying_probe(**kwargs) -> None: + # A permissive signature satisfies the kit's keyword probe, so the + # probe reports support this host does not have. Rejecting at call + # time is what drives the documented retry. + if "references_dir" in kwargs: + raise TypeError( + "register_skill() got an unexpected keyword argument 'references_dir'" + ) + self._record("register_skill", (), kwargs) + self.skills.append(kwargs) + + def register_skill_raising(**kwargs) -> None: + raise register_skill_error + + def register_memory_provider(provider) -> None: + self._record("register_memory_provider", (provider,), {}) + self.memory_providers.append(provider) + + def register_image_gen_provider(provider) -> None: + self._record("register_image_gen_provider", (provider,), {}) + self.image_gen_providers.append(provider) + + def register_video_gen_provider(provider) -> None: + self._record("register_video_gen_provider", (provider,), {}) + self.video_gen_providers.append(provider) + + def register_context_engine(engine): + self._record("register_context_engine", (engine,), {}) + self.context_engines.append(engine) + return self.context_engine_result + + def _pick_skill_registrar() -> Callable[..., Any]: + # Order matters: a raising host outranks the probe shapes, since a + # test asking for an error wants it regardless of the keyword. + if register_skill_error is not None: + return register_skill_raising + if references_dir_probe_lies: + return register_skill_lying_probe + if supports_references_dir: + return register_skill_with_references + return register_skill_only + + implementations: dict[str, Callable[..., Any]] = { + "register_tool": register_tool, + "register_command": register_command, + "register_cli_command": register_cli_command, + "register_middleware": register_middleware, + "register_hook": register_hook, + "register_skill": _pick_skill_registrar(), + "register_memory_provider": register_memory_provider, + "register_image_gen_provider": register_image_gen_provider, + "register_video_gen_provider": register_video_gen_provider, + "register_context_engine": register_context_engine, + } + + for registrar, impl in implementations.items(): + if registrar not in missing: + setattr(self, registrar, impl) + + # -- checking ------------------------------------------------------------ + + def check_against_host(self, host: type | None) -> DriftReport: + """Replay every recorded call through ``host``'s signatures. + + Pass the real ``PluginContext`` class. ``None`` means no host was + available, which produces an explicitly unchecked report rather than a + clean one -- not having looked is not the same as having found nothing. + """ + if host is None: + return DriftReport( + checked=False, + detail=( + "no hermes-agent checkout was available, so no drift check ran. " + f"Provision hermes-agent at {DEPLOYED_HERMES_REVISION} and point " + "HERMES_AGENT_PATH at it to enable the check." + ), + ) + + drifts: list[Drift] = [] + for registrar, args, kwargs in self.calls: + target = getattr(host, registrar, None) + if target is None: + drifts.append( + Drift(registrar, f"host {host.__name__} does not expose {registrar}()") + ) + continue + detail = _bind(target, args, kwargs, _POSITIONAL_PARAMS.get(registrar, ())) + if detail is not None: + drifts.append(Drift(registrar, detail)) + + return DriftReport(checked=True, drifts=tuple(drifts)) + + +@dataclass(frozen=True) +class CheckResult: + """A framework-neutral verdict: the consumer decides how to assert it. + + The kit is stdlib ``unittest``, but consumers may not be, so these helpers + return a result rather than raising -- ``assert result.ok, result`` works + under any runner, and ``problems`` says what to fix. + """ + + problems: tuple[str, ...] = () + + @property + def ok(self) -> bool: + return not self.problems + + def __bool__(self) -> bool: # pragma: no cover - trivial + return self.ok + + def __str__(self) -> str: + return "ok" if self.ok else "; ".join(self.problems) + + +def receipt_fields(message: str) -> dict[str, tuple[str, ...]]: + """Parse one registration receipt into its fields, in emitted order. + + Lets a consumer assert what was registered without copying the kit's format + string into their own test. ```` becomes an empty tuple, so an absent + surface and an empty one read the same way. + """ + fields: dict[str, tuple[str, ...]] = {} + for chunk in message.split("; "): + key, sep, value = chunk.partition("=") + key = key.strip() + if not sep or key not in RECEIPT_FIELD_ORDER: + continue + value = value.strip() + fields[key] = () if value == "" else tuple(value.split(",")) + return {k: fields[k] for k in RECEIPT_FIELD_ORDER if k in fields} + + +def _schema_problems(name: str, schema: Any) -> list[str]: + """A tool's arguments belong under ``parameters``, never flattened beside it. + + The kit hands ``register_tool`` the inner function schema -- + ``{name, description, parameters}`` -- and Hermes' registry wraps it so the + arguments land at ``function.parameters`` in the tool it exposes. So a + top-level ``properties`` here is the defect: it flattens the arguments and + they never reach ``function.parameters`` after conversion. + """ + if not isinstance(schema, dict) or not schema: + return [] + problems: list[str] = [] + if "properties" in schema: + problems.append( + f"tool {name!r} declares arguments beside `parameters` instead of inside " + f"it, so they would not reach function.parameters once Hermes converts " + f"the schema" + ) + parameters = schema.get("parameters") + if parameters is not None and not isinstance(parameters, dict): + problems.append(f"tool {name!r} has a non-object `parameters`") + elif isinstance(parameters, dict) and parameters.get("type") not in (None, "object"): + problems.append( + f"tool {name!r} has parameters.type {parameters.get('type')!r}; " + f"Hermes expects 'object'" + ) + return problems + + +def check_registration(ctx: RecordingPluginContext) -> CheckResult: + """Check what a plugin registered against the kit's standing conventions. + + Covers deterministic ordering, duplicate names, and the + arguments-under-``function.parameters`` schema shape -- the contracts a + consumer would otherwise copy out of the kit's own test suite. + + A name used for both a slash command and a CLI command is allowed; the kit + permits that pairing deliberately, so the duplicate check is per surface. + """ + problems: list[str] = [] + + named_surfaces = { + "tools": [t.get("name") for t in ctx.tools], + "commands": [c.get("name") for c in ctx.commands], + "cli_commands": [c.get("name") for c in ctx.cli_commands], + "skills": [s.get("name") for s in ctx.skills], + "hooks": [h[0] for h in ctx.hooks], + "middlewares": [str(m[0]) for m in ctx.middlewares], + } + + for surface, names in named_surfaces.items(): + present = [n for n in names if n is not None] + duplicates = sorted({n for n in present if present.count(n) > 1}) + if duplicates: + problems.append(f"duplicate {surface} name(s): {', '.join(duplicates)}") + if present != sorted(present): + problems.append( + f"{surface} were recorded out of order ({', '.join(present)}); " + f"register_plugin sorts every registrar, so this indicates a " + f"registration path that bypassed it" + ) + + for tool in ctx.tools: + problems.extend(_schema_problems(tool.get("name"), tool.get("schema"))) + + return CheckResult(tuple(problems)) + + +#: How long a fetch may run before it is abandoned, in seconds. +#: +#: A test-support library must not hang a consumer's suite. When this elapses +#: the result is an ordinary unavailable :class:`ResolvedHost`, not an exception. +FETCH_TIMEOUT_SECONDS = 300 + +_HERMES_REPO_URL = "https://github.com/NousResearch/hermes-agent.git" + + +@dataclass(frozen=True) +class ResolvedHost: + """Where a Hermes checkout is, or why there isn't one. + + ``available`` false is a normal outcome, not an error: offline, sandboxed, + and air-gapped runs all land here, and the caller turns it into the + "unchecked" drift report rather than a failure. + """ + + path: Path | None + revision: str | None + detail: str + + @property + def available(self) -> bool: + return self.path is not None + + def plugin_context_class(self) -> type | None: + """Import the real ``PluginContext`` from this checkout, or ``None``. + + Returns ``None`` when no checkout resolved, which is exactly what + :meth:`RecordingPluginContext.check_against_host` treats as unchecked -- + so a consumer can pass this straight through. + """ + if self.path is None: + return None + root = str(self.path) + if root not in sys.path: + sys.path.insert(0, root) + try: + from hermes_cli.plugins import PluginContext # type: ignore + except Exception: # pragma: no cover - depends on the checkout's shape + return None + return PluginContext + + +def _git(args: list[str], *, cwd: Path | None = None, timeout: int) -> str: + result = subprocess.run( + ["git", *args], + cwd=None if cwd is None else str(cwd), + capture_output=True, + text=True, + timeout=timeout, + check=True, + ) + return result.stdout.strip() + + +def _head_revision(path: Path, *, timeout: int) -> str | None: + try: + return _git(["rev-parse", "HEAD"], cwd=path, timeout=timeout) + except Exception: + return None + + +def _looks_like_hermes(path: Path) -> bool: + return (path / "hermes_cli" / "plugins.py").exists() + + +def _default_fetcher(url: str, revision: str, destination: Path, *, timeout: int) -> None: + """Fetch exactly one revision, shallow, into ``destination``.""" + destination.mkdir(parents=True, exist_ok=True) + _git(["init", "-q", str(destination)], timeout=timeout) + _git(["remote", "add", "origin", url], cwd=destination, timeout=timeout) + _git(["fetch", "-q", "--depth", "1", "origin", revision], cwd=destination, timeout=timeout) + _git(["checkout", "-q", "FETCH_HEAD"], cwd=destination, timeout=timeout) + + +def resolve_hermes_checkout( + *, + revision: str = DEPLOYED_HERMES_REVISION, + cache_dir: Path | str | None = None, + env: Mapping[str, str] | None = None, + timeout: int = FETCH_TIMEOUT_SECONDS, + fetcher: Callable[..., None] | None = None, + url: str = _HERMES_REPO_URL, +) -> ResolvedHost: + """Find a Hermes checkout the drift replay can use, fetching one if needed. + + Without this the replay only ever runs inside this repository: a consumer's + machine has no Hermes checkout, so recording always happens and checking + never does. + + Resolution order, and why: + + 1. ``HERMES_AGENT_PATH`` always wins. An operator who pointed at a checkout + meant it, and a library should not second-guess that or fetch over it. + 2. A cache already at ``revision`` is reused, so the fetch happens at most + once per machine. + 3. Otherwise fetch. A cache sitting at some *other* revision is never + returned as if it were the pin -- that would receipt the wrong host. + + Any failure returns an unavailable result naming the revision and the + reason. It never raises and never hangs past ``timeout``. + """ + environ = os.environ if env is None else env + supplied = (environ.get("HERMES_AGENT_PATH") or "").strip() + if supplied: + path = Path(supplied) + if not _looks_like_hermes(path): + return ResolvedHost( + None, None, + f"HERMES_AGENT_PATH={supplied} has no hermes_cli/plugins.py, so it is " + f"not a Hermes checkout. Point it at one, or unset it to let the " + f"harness fetch {revision}.", + ) + return ResolvedHost(path, _head_revision(path, timeout=timeout), f"supplied: {supplied}") + + cache = Path(cache_dir) if cache_dir is not None else _default_cache_dir() + if _looks_like_hermes(cache): + head = _head_revision(cache, timeout=timeout) + if head == revision: + return ResolvedHost(cache, head, f"cached at {revision}") + + fetch = fetcher if fetcher is not None else _default_fetcher + try: + fetch(url, revision, cache, timeout=timeout) + except subprocess.TimeoutExpired: + return ResolvedHost( + None, None, + f"fetching hermes-agent at {revision} exceeded {timeout}s and was " + f"abandoned; set HERMES_AGENT_PATH to a local checkout to skip the fetch.", + ) + except Exception as exc: + return ResolvedHost( + None, None, + f"could not obtain hermes-agent at {revision}: {exc}. " + f"Set HERMES_AGENT_PATH to a local checkout to run the drift check offline.", + ) + + head = _head_revision(cache, timeout=timeout) + if not _looks_like_hermes(cache) or head != revision: + return ResolvedHost( + None, None, + f"fetch completed but the checkout is not at {revision} (found {head}); " + f"refusing to report a revision the replay did not actually use.", + ) + return ResolvedHost(cache, head, f"fetched {revision}") + + +def _default_cache_dir() -> Path: + base = os.environ.get("XDG_CACHE_HOME") or (Path.home() / ".cache") + return Path(base) / "hermes-plugin-kit" / "hermes-agent" diff --git a/justfile b/justfile index b4ce8c9..6076f06 100644 --- a/justfile +++ b/justfile @@ -1,6 +1,8 @@ set shell := ["bash", "-cu"] 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") @@ -62,6 +64,43 @@ test-contract: prepare-hermes-agent test-context-engine-contract: {{ uv }} run python -m unittest tests.test_context_engine_contract -v +# Refuse to run when the installed OpenSpec predates the archive-correctness fixes. +[private] +openspec-floor: + #!/usr/bin/env bash + set -euo pipefail + have="$({{ openspec }} --version 2>/dev/null | tr -d '[:space:]' || true)" + if [[ -z "$have" ]]; then + echo "openspec not found on PATH; need >= {{ openspec_min }}" >&2 + exit 1 + fi + lowest="$(printf '%s\n%s\n' "$have" "{{ openspec_min }}" | sort -V | head -n1)" + if [[ "$have" != "{{ openspec_min }}" && "$lowest" != "{{ openspec_min }}" ]]; then + echo "openspec $have is below the required {{ openspec_min }}" >&2 + echo "Releases before {{ openspec_min }} could exit 0 from archive having applied" >&2 + echo "less than the delta specified. Upgrade before validating or archiving." >&2 + exit 1 + fi + +# Validate every OpenSpec change, and confirm each authored one will archive. +spec-validate: openspec-floor + #!/usr/bin/env bash + set -euo pipefail + changes="$({{ openspec }} list --json | {{ uv }} run python -c 'import json,sys; print("\n".join(c["name"] for c in json.load(sys.stdin)["changes"]))')" + test -n "$changes" || { echo "no OpenSpec changes found" >&2; exit 1; } + for change in $changes; do + echo "== $change" + {{ openspec }} validate "$change" --strict + # `validate --strict` can pass while `archive` refuses — a MODIFIED header + # matching nothing in the main spec is INFO at validate and fatal at archive. + # Resolving the deltas catches that early, but only once a proposal exists. + if [[ -f "openspec/changes/$change/proposal.md" ]]; then + {{ openspec }} show "$change" --diff >/dev/null + else + echo " (not yet authored — skipping delta resolution)" + fi + done + # Build the wheel and source distribution. build: rm -rf dist @@ -71,6 +110,34 @@ build: check-dist: {{ uv }} run twine check dist/* +# Prove every public name imports from an installed wheel, not just the source tree. +# +# `twine check` validates metadata and never opens the archive, so it cannot see +# a module missing from the build. Only installing and importing can. +check-install: build + #!/usr/bin/env bash + set -euo pipefail + wheel="$(ls dist/*.whl | head -n1)" + test -n "$wheel" || { echo "no wheel in dist/" >&2; exit 1; } + workdir="$(mktemp -d)" + trap 'rm -rf "$workdir"' EXIT + # --no-project keeps the source tree off sys.path, so a name that only + # resolves in-tree fails here instead of passing by accident. + repo="$PWD" + cat > "$workdir/probe.py" <<'PROBE' + import hermes_plugin_kit as hpk + missing = sorted(n for n in hpk.__all__ if not hasattr(hpk, n)) + if missing: + raise SystemExit("not importable from the installed wheel: " + ", ".join(missing)) + import hermes_plugin_kit.testing as t + t.RecordingPluginContext(name="install-probe") + print("installed wheel exports", len(hpk.__all__), "names; harness constructs") + PROBE + cd "$workdir" + {{ uv }} venv --quiet .venv + VIRTUAL_ENV="$workdir/.venv" {{ uv }} pip install --quiet "$repo/$wheel" + VIRTUAL_ENV="$workdir/.venv" {{ uv }} run --no-project python probe.py + # Remove Python caches and build artifacts. clean: find . -type d -name __pycache__ -prune -exec rm -rf {} + diff --git a/openspec/changes/add-plugin-test-harness/.openspec.yaml b/openspec/changes/add-plugin-test-harness/.openspec.yaml new file mode 100644 index 0000000..563fab5 --- /dev/null +++ b/openspec/changes/add-plugin-test-harness/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-09-21 diff --git a/openspec/changes/add-plugin-test-harness/design.md b/openspec/changes/add-plugin-test-harness/design.md new file mode 100644 index 0000000..2c23a79 --- /dev/null +++ b/openspec/changes/add-plugin-test-harness/design.md @@ -0,0 +1,90 @@ +## Context + +The kit's own fake plugin context and its real-Hermes import seam already exist +and work, in `tests/test_kit.py` and `tests/test_hermes_contract.py`. Nothing +about them is wrong; they are simply unreachable. Consumers install the kit via +`git+…@sha`, and the built wheel contains only `hermes_plugin_kit/__init__.py` +and `hermes_plugin_kit/observability.py`. + +Two constraints shape everything below. `pyproject.toml` declares +`packages = ["hermes_plugin_kit"]` as an explicit list, so a new subpackage is +dropped from the wheel with no warning and `twine check` — which validates +metadata, not archive contents — does not notice. And a consumer's machine +generally cannot import hermes-agent at all, so any mechanism that needs the +real class at construction time is unavailable exactly where the harness is +meant to be used. + +## Goals / Non-Goals + +**Goals:** + +- A fake a consumer can import and use with no host present. +- A drift check that fails when the host's registrar signatures change, and + names what changed. +- Registration assertions that do not require copying literals out of the kit's + own test suite. +- Proof that documented public names survive the trip into a wheel. + +**Non-Goals:** + +- Converting any consumer repository's existing fake. Adoption is each + consumer's own call. +- Changing `deliver_media` or `invoke_host_tool` behavior. +- Exposing the harness to the Hermes runtime agent loop. It is dev-time + support, invoked from a consumer's test runner. + +## Decisions + +**Record-and-replay, not a "stricter" fake.** Probing five candidates settled +this. A permissive `**kwargs` fake and a hand-written positional fake mirroring +today's host both pass when the host gains a required parameter — the second is +a frozen snapshot, not a stronger contract. Comparing the fake's own signature +to the real one also catches nothing, because `**kwargs` is compatible with +every signature by construction. `create_autospec` does catch it, but needs the +real class importable, which rules it out as the shipped mechanism. Binding +recorded call arguments through the real signature catches added, renamed, and +removed parameters, and needs the host only at check time. Rejected: shipping +selectable strict and permissive fakes, which would have shipped two shapes that +both miss the defect. + +**The replay lives in the fake, not only in the kit's contract lane.** A +consumer calling the fake directly is invisible to a lane-side check. + +**A flat module, not a subpackage.** Forced by the explicit `packages` list +above; it also matches the existing `observability.py` precedent. A wheel +membership assertion guards it, since `twine check` cannot. + +**Receipt assertions pin the log field order.** The `RegistrationSummary` +dataclass order and the order `log_registration_summary` emits genuinely +differ, and the logged string is the contract `AGENTS.md` pins. + +**Composable pieces, not one entry point.** The fake, the revision constant, +the drift check, and the assertions are separately usable, so an author can take +only registration parity without the whole lane. + +## Risks / Trade-offs + +- A registrar attached dynamically rather than declared on the class has no + signature to bind against. Treat that as "could not check this surface" + rather than clean; partial coverage is the realistic outcome, since the one + registrar with trailing `**kwargs` still binds its required portion. +- The replay proves nothing about host→plugin *callback* drift. If Hermes + changes how it invokes a registered hook, binding outbound registration calls + is silent on it. Only the real dispatchers catch that, which is why the + contract lane stays mandatory rather than being replaced by this harness. +- Adding names to `__all__` grows the public surface and makes this a minor + release. + +## Migration + +None. The module is additive; no existing export changes shape. Consumers adopt +it when they choose, and their current fakes keep working untouched. + +## Open Questions + +- Whether the revision constant should be owned here or read from infra's + deployed-snapshot receipt. Proceeding with local ownership, because a + constant that ships in the wheel is the only form a consumer can read. +- Whether the assertion helpers should stay framework-neutral by returning + structured results rather than raising. Proceeding with neutral results, since + the kit is stdlib `unittest` but consumers may not be. diff --git a/openspec/changes/add-plugin-test-harness/proposal.md b/openspec/changes/add-plugin-test-harness/proposal.md new file mode 100644 index 0000000..18ebf6e --- /dev/null +++ b/openspec/changes/add-plugin-test-harness/proposal.md @@ -0,0 +1,58 @@ +## Why + +A plugin author cannot prove their plugin still satisfies the Hermes runtime +contract, because the kit ships no test support. Fourteen consumer plugin +repositories have each hand-rolled a fake plugin context in response; eight use +a strict positional `register_skill`, three a permissive `**kwargs` form, three +define none at all. None of them catches the failure they exist to catch: a +permissive fake accepts every future signature, and a hand-written positional +fake is a frozen snapshot of one host revision, so both pass unchanged when the +host adds a required parameter. + +The kit already owns a working fake and a real-Hermes import seam, but they live +in `tests/`, which never reaches a consumer install — the wheel carries only +`hermes_plugin_kit/__init__.py` and `hermes_plugin_kit/observability.py`. The +repository states the principle in `skills/hermes-plugins/references/plugin-kit.md` +("a fake context alone can hide signature drift") and cannot deliver it. + +## What Changes + +- A public `hermes_plugin_kit.testing` module, importable from an installed + wheel with no new runtime dependency. +- A recording fake plugin context that captures registration calls, plus a + replay that binds those captured arguments against the real `PluginContext` + signatures wherever a Hermes checkout is importable. Added, renamed, and + removed registrar parameters each fail and name what drifted. +- Assertion helpers for the registration receipt's log field order, duplicate + detection, deterministic ordering, and the schema-under-`function.parameters` + convention, so a consumer asserts them without copying literals out of the + kit's own tests. +- The deployed Hermes revision exposed as a module constant. +- A reachability guard that fails when a documented public name is missing from + `__all__`, plus a build-install-import check that exercises the wheel rather + than the source tree. + +## Capabilities + +### New Capabilities + +- `plugin-test-harness`: the kit's consumer-facing test support — the recording + fake, drift replay against the real host, registration assertions, the + deployed-revision constant, and the guarantee that documented names are + reachable from an installed package. + +### Modified Capabilities + + + +## Impact + +- `hermes_plugin_kit/testing.py` (new), re-exported from + `hermes_plugin_kit/__init__.py` and added to `__all__`. +- `plugin_reference_tool` joins `__all__`; it is documented and tested today but + absent from the public list. +- `pyproject.toml` stays unchanged: `packages` is an explicit list, so a flat + module ships while a subpackage would be silently omitted from the wheel. +- New tests in `tests/test_testing_harness.py`; new `justfile` recipe and CI job + for the installed-artifact check. +- No change to `deliver_media` or `invoke_host_tool`. diff --git a/openspec/changes/add-plugin-test-harness/specs/plugin-test-harness/spec.md b/openspec/changes/add-plugin-test-harness/specs/plugin-test-harness/spec.md new file mode 100644 index 0000000..1a5ccbb --- /dev/null +++ b/openspec/changes/add-plugin-test-harness/specs/plugin-test-harness/spec.md @@ -0,0 +1,115 @@ +## Purpose + +Consumer-facing test support shipped inside the installed package, so a plugin +author can prove their plugin still satisfies the Hermes registration contract +and learn when the host's own signatures have drifted underneath them. + +## ADDED Requirements + +### Requirement: Harness is importable from an installed wheel + +The harness SHALL be importable from an installed distribution through the +package's public path, without adding a runtime dependency and without +importing Hermes or a test framework at module import time. + +#### Scenario: Import from a clean install + +- **WHEN** the built wheel is installed into an environment that has neither + hermes-agent nor a test framework available +- **THEN** importing the harness through the public package path succeeds + +#### Scenario: Import performs no host or test-framework import + +- **WHEN** the harness module is imported +- **THEN** no hermes-agent module and no test framework has been imported as a + side effect + +### Requirement: Recorded calls replay against the real host signatures + +The fake plugin context SHALL record the registration calls a plugin makes, and +those recorded calls SHALL be replayed against the real Hermes `PluginContext` +signatures wherever a Hermes checkout is importable. + +#### Scenario: Host adds a required parameter + +- **WHEN** a plugin registers against a host whose registrar has gained a + required parameter +- **THEN** the replay fails and names the missing parameter + +#### Scenario: Host renames a keyword parameter + +- **WHEN** a plugin registers against a host whose registrar has renamed a + parameter the plugin passes by keyword +- **THEN** the replay fails and names the unexpected keyword + +#### Scenario: Host renames a positional parameter + +- **WHEN** a plugin registers against a host whose registrar has renamed a + parameter the plugin passes positionally, leaving arity unchanged +- **THEN** the replay fails and names both the old and the new parameter name, + rather than reporting clean because the call still binds by position + +#### Scenario: Host removes a registrar + +- **WHEN** a plugin registers a surface the host no longer exposes +- **THEN** the replay fails and names the missing registrar + +#### Scenario: Host is unchanged + +- **WHEN** a plugin registers against the real host with no drift +- **THEN** the replay reports clean and the recorded registration is available + for assertion + +### Requirement: Absent host is reported, never assumed clean + +The harness SHALL remain usable with no Hermes checkout present, and a run that +could not perform the replay SHALL report that fact rather than presenting +itself as drift-checked. It SHALL name the revision a consumer must provision +to enable the replay. + +#### Scenario: No checkout available + +- **WHEN** the harness runs with no importable Hermes checkout +- **THEN** the fake still records calls, the result states that no replay was + performed, and the required revision is named + +### Requirement: Registration assertions are reusable + +The harness SHALL expose assertions for the registration receipt's stable log +field order, duplicate detection, deterministic ordering, and the +schema-under-`function.parameters` convention, so a consumer asserts them +without copying literals. + +#### Scenario: Receipt field order is pinned to the log order + +- **WHEN** a receipt is asserted whose fields are emitted in a different order + than the logged contract +- **THEN** the assertion fails + +#### Scenario: Duplicate registration is rejected + +- **WHEN** a plugin registers two tools under the same name +- **THEN** the assertion fails, while the same name used for both a slash + command and a CLI command is accepted + +#### Scenario: Flattened tool schema is rejected + +- **WHEN** a tool schema declares its arguments at the top level instead of + under `function.parameters` +- **THEN** the assertion fails + +### Requirement: Documented public names are reachable + +Every public name the kit documents SHALL be reachable through the package's +public import path, and a guard SHALL fail when a documented name is not. + +#### Scenario: Documented name missing from the public list + +- **WHEN** a name the documentation presents as public is absent from the + package's export list +- **THEN** the guard fails and names it + +#### Scenario: Reachability is proven against the built artifact + +- **WHEN** the wheel is built and installed into a throwaway environment +- **THEN** every documented public name imports from that installation diff --git a/openspec/changes/add-plugin-test-harness/tasks.md b/openspec/changes/add-plugin-test-harness/tasks.md new file mode 100644 index 0000000..e98820a --- /dev/null +++ b/openspec/changes/add-plugin-test-harness/tasks.md @@ -0,0 +1,85 @@ +## 1. Recording fake and drift replay (U2) + +- [x] 1.1 Add the flat `hermes_plugin_kit/testing.py` module and re-export it + from the package root, following the `observability.py` precedent. + Verify: the module imports from the package root in a fresh interpreter. +- [x] 1.2 Write the failing drift tests first — added required parameter, + renamed parameter, removed registrar — against simulated host shapes. + Verify: each fails for its intended reason before any implementation. +- [x] 1.3 Implement the recording fake, carrying plugin name and config as + first-class constructor arguments so `load_plugin_config` and the receipt + identity resolve. Verify: the three drift tests pass and the unchanged-host + case reports clean. +- [x] 1.4 Add the `references_dir`-unsupported mode and the missing-registrar + mode, so both branches of the kit's capability probe are exercisable. + Verify: the probe takes its retry branch and the unsupported-context error + raises, each under its own test. +- [x] 1.5 Expose the deployed Hermes revision as a module constant, and keep + every Hermes import lazy. Verify: importing the module pulls in neither + hermes-agent nor a test framework. +- [x] 1.6 Catch a positionally renamed parameter by comparing names as well as + arity. Binding alone misses it, because Python binds positionals by + position. Verify: a host renaming `register_hook`'s first parameter is + reported with both names, and an unrenamed positional host stays clean. + +## 2. Registration and schema assertions (U3) + +- [x] 2.1 Add the receipt assertion, pinned to the emitted log field order + rather than the dataclass order. Verify: a permuted field order fails. +- [x] 2.2 Add duplicate-detection and deterministic-ordering assertions. + Verify: a duplicate tool name fails while the same name across a slash and + a CLI command passes; out-of-order registration still yields sorted output. +- [x] 2.3 Add the schema-convention assertion. Verify: a schema with flattened + top-level arguments fails and a conforming one passes. +- [x] 2.4 Add the drift report that names the registrar and parameter, shaped + like the kit's existing structured receipts. Verify: the report names the + added parameter against a drifted host and reports clean otherwise. + +## 3. Host-shape coverage the kit's own tests need (U3) + +- [x] 3.1 Add a mode whose `register_skill` advertises `references_dir` through + a permissive signature but rejects it at call time, reproducing the host + shape that fools the kit's capability probe. Verify: `register_plugin` + takes its documented retry branch and the skill still registers. +- [x] 3.2 Add a mode whose `register_skill` raises a `TypeError` unrelated to + `references_dir`. Verify: the retry does not swallow it and the error + propagates. + +## 4. Migrate the kit's own fake onto the harness (U3) + +- [x] 4.1 Replace `FakeCtx` and `FakePluginCtx` in `tests/test_kit.py` with the + harness. Verify: the suite passes unchanged, with no loss of coverage. +- [x] 4.2 Replace the four bespoke host-shape classes — the strict positional + host, the explicit-`references_dir` host, the fooled-probe host, and the + broken host — with harness modes. Verify: the tests that own those + branches still fail when their branch regresses. +- [x] 4.3 Record the line delta from the migration. Verify: the migration + removes more lines than it adds, which is the success criterion's only + in-repo evidence. + +## 5. Public-surface reachability (U4) + +- [x] 5.1 Add a `justfile` recipe that builds, installs into a throwaway + environment, and imports every `__all__` name, plus the CI job that runs + it after the metadata check. Verify: the recipe fails when the module is + dropped from the packaging manifest, where `twine check` passes. +- [x] 5.2 Add `plugin_reference_tool` to `__all__`, closing the existing gap + between what the kit documents and what it exports. Verify: it is + importable from the package root and present in the export list. +- [x] 5.3 Add the guard asserting every name in the Surface Map's `Kit API` + column is exported and importable. Verify: temporarily removing one name + fails the guard. + +## 6. Shipped checkout resolver (U9) + +- [x] 6.1 Write the offline case first: no checkout, no network. Verify: it + fails before implementation, then returns an explicit unchecked result + naming the revision and the reason, within the timeout. +- [x] 6.2 Export the resolver, honoring an explicit `HERMES_AGENT_PATH` ahead of + any fetch. Verify: a supplied path is used as-is and no fetch is attempted. +- [x] 6.3 Fetch at the pin when nothing resolves, into a reused cache, bounded + by a timeout and never silently retried. Verify: the first call fetches a + checkout whose HEAD is the pin and the replay then runs; the second call + reuses the cache. +- [x] 6.4 Refuse or re-resolve a cache sitting at the wrong revision. Verify: a + cache at an unrelated revision is never used as if it were the pin. diff --git a/openspec/changes/archive/.gitkeep b/openspec/changes/archive/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/openspec/changes/harden-hermes-contract-gates/.openspec.yaml b/openspec/changes/harden-hermes-contract-gates/.openspec.yaml new file mode 100644 index 0000000..42d17fe --- /dev/null +++ b/openspec/changes/harden-hermes-contract-gates/.openspec.yaml @@ -0,0 +1,6 @@ +schema: spec-driven +created: 2026-09-21 + +# This change alters tooling and documentation only; it changes no +# capability-level requirement, so it carries zero spec deltas. +skip_specs: true diff --git a/openspec/changes/route-authors-to-the-harness/.openspec.yaml b/openspec/changes/route-authors-to-the-harness/.openspec.yaml new file mode 100644 index 0000000..42d17fe --- /dev/null +++ b/openspec/changes/route-authors-to-the-harness/.openspec.yaml @@ -0,0 +1,6 @@ +schema: spec-driven +created: 2026-09-21 + +# This change alters tooling and documentation only; it changes no +# capability-level requirement, so it carries zero spec deltas. +skip_specs: true diff --git a/openspec/config.yaml b/openspec/config.yaml new file mode 100644 index 0000000..51924c0 --- /dev/null +++ b/openspec/config.yaml @@ -0,0 +1,36 @@ +schema: spec-driven + +context: | + hermes-plugin-kit is an installable Python package: a convention-correct + helper library for registering hermes-agent plugin commands, tools, + middleware, hooks, and skills. It is not a path-loaded runtime plugin. + Consumer plugins pin it to an immutable commit, and profiles installing + several plugins into one environment keep every consumer on the same kit + revision. + + Stack: Python 3.11, uv, stdlib unittest (no pytest), just as the sole task + runner, python-semantic-release, GitHub Actions. AGENTS.md at the repo root + carries the binding working rules and takes precedence over anything here. + + Conventions that shape most changes: + - Public API is re-exported from hermes_plugin_kit/__init__.py and listed in + __all__. Adding a documented name without adding it to __all__ is a + recurring defect. + - pyproject.toml declares packages as an explicit list, so a new subpackage + is silently omitted from the wheel. Prefer a flat module. + - Tests live in tests/ and run under unittest discovery. Contract tests + against a real hermes-agent checkout are gated on HERMES_AGENT_PATH. + - tests/test_release_contract.py parses the GitHub workflows and asserts + their shape: SHA-pinned actions, just-only steps, no pull_request_target. + Workflow changes belong there rather than in a parallel mechanism. + - Keep skills/hermes-plugins/references/plugin-kit.md aligned with public + API changes. + +rules: + proposal: + - State the user-visible consequence before the mechanism. + - Name the capability paths under Capabilities explicitly. + design: + - Record the alternatives that were rejected and why, not only the choice. + tasks: + - Every task names the verification that proves it done. diff --git a/openspec/specs/.gitkeep b/openspec/specs/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/skills/hermes-plugins/SKILL.md b/skills/hermes-plugins/SKILL.md index 0c156d2..546295e 100644 --- a/skills/hermes-plugins/SKILL.md +++ b/skills/hermes-plugins/SKILL.md @@ -1,9 +1,7 @@ --- name: hermes-plugins description: Build, modify, migrate, review, and debug Hermes Agent plugin repositories. Use for plugin.yaml manifests, PluginContext or register(ctx), hermes-plugin-kit adoption, tools, commands, middleware, hooks, bundled skills, guarded host calls, media delivery, registration tests, and runtime toolset exposure. Do not use for Hermes core tools or specialized provider plugins unless the request explicitly targets those upstream surfaces. -version: 0.2.0 license: MIT -category: Development Workflow metadata: audience: developers keywords: hermes-agent, plugins, hermes-plugin-kit, PluginContext @@ -96,4 +94,21 @@ rg -n "register_tool|register_hook|register_command|register_skill|provides_tool ## Shipping -If the user asks to ship, commit after validation. If the plugin is deployed through infra/GitOps, do not assume the repo change is live; verify the relevant deployment path, branch, tag, or rendered Hermes config when the user asks about runtime truth. +If the user asks to ship, commit after validation. + +When the plugin is deployed through an immutable infra/GitOps snapshot, treat +the source change and snapshot promotion as one shipping objective with +separate proof gates: + +- Merge the plugin change to the snapshot's declared branch before pinning it. + Do not promote an open-PR commit that could become unreachable after a squash + merge or branch deletion. +- From the current infra base, resolve a candidate snapshot, confirm the target + plugin advances to the merged commit without regressing other pins, run the + repository's full snapshot qualification, and open or update the infra PR. +- Keep source, promotion, and runtime claims distinct. A merged plugin PR is not + deployed; a merged snapshot PR is not live until GitOps reconciles and the + effective workload reports the promoted snapshot and plugin revision. + +Read the infra repository's local guidance for its policy file, validation +command, and rollout proof instead of assuming a universal snapshot format. diff --git a/tests/test_kit.py b/tests/test_kit.py index ea6ae57..612b7fc 100644 --- a/tests/test_kit.py +++ b/tests/test_kit.py @@ -14,6 +14,7 @@ from unittest.mock import AsyncMock, Mock, patch import hermes_plugin_kit as hpk +from hermes_plugin_kit.testing import RecordingPluginContext @contextmanager @@ -34,63 +35,16 @@ class ContextEngine: yield ContextEngine -class FakeCtx: - def __init__(self) -> None: - self.tools: list[dict] = [] - - def register_tool(self, **kwargs) -> None: - self.tools.append(kwargs) - - -class FakePluginCtx(FakeCtx): - def __init__(self) -> None: - super().__init__() - self.commands: list[dict] = [] - self.cli_commands: list[dict] = [] - self.middlewares: list[tuple[str, object]] = [] - self.hooks: list[tuple[str, object]] = [] - self.skills: list[dict] = [] - self.image_gen_providers: list[object] = [] - self.video_gen_providers: list[object] = [] - self.memory_providers: list[object] = [] - self.context_engines: list[object] = [] - self.context_engine_result = True - self.subagent_lifecycle = types.SimpleNamespace( - launch=lambda request: request, - status=lambda handle: handle, - wait=lambda handle, **kwargs: handle, - cancel=lambda handle, **kwargs: handle, - result=lambda handle: handle, - reconnect=lambda handle: handle, - ) - - def register_command(self, **kwargs) -> None: - self.commands.append(kwargs) - - def register_cli_command(self, **kwargs) -> None: - self.cli_commands.append(kwargs) - - def register_middleware(self, kind, callback) -> None: - self.middlewares.append((kind, callback)) - - def register_hook(self, hook_name, callback) -> None: - self.hooks.append((hook_name, callback)) - - def register_skill(self, **kwargs) -> None: - self.skills.append(kwargs) - - def register_image_gen_provider(self, provider) -> None: - self.image_gen_providers.append(provider) - - def register_video_gen_provider(self, provider) -> None: - self.video_gen_providers.append(provider) - - def register_memory_provider(self, provider) -> None: - self.memory_providers.append(provider) - - def register_context_engine(self, engine): - self.context_engines.append(engine) - return self.context_engine_result +# The kit's own tests use the harness it ships, so the consumer-facing surface +# is exercised by a real caller rather than only by its own unit tests. These +# aliases keep the historical names at the ~36 call sites below. +# +# Note the registrars are instance attributes on the harness, which is what lets +# a missing one genuinely disappear. A subclass overriding `register_skill` as a +# class attribute would therefore be shadowed -- host shapes are selected with +# constructor modes instead (see `references_dir_probe_lies` and friends). +FakeCtx = RecordingPluginContext +FakePluginCtx = RecordingPluginContext class SessionDBHelperTests(unittest.TestCase): @@ -2020,12 +1974,6 @@ def test_register_plugin_passes_references_dir_to_a_host_that_accepts_it(self) - def test_register_plugin_falls_back_gracefully_when_host_lacks_references_dir_support( self, ) -> None: - class StrictHostCtx(FakePluginCtx): - """Mirrors today's real hermes-agent PluginContext.register_skill signature.""" - - def register_skill(self, name, path, description="") -> None: - self.skills.append({"name": name, "path": path, "description": description}) - with tempfile.TemporaryDirectory() as tmp: skill_path = Path(tmp) / "SKILL.md" skill_path.write_text( @@ -2035,7 +1983,7 @@ def register_skill(self, name, path, description="") -> None: references_dir.mkdir() skill = hpk.plugin_skill("sample", skill_path, "Sample.", references_dir=references_dir) - ctx = StrictHostCtx() + ctx = RecordingPluginContext(supports_references_dir=False) with self.assertLogs(level="WARNING") as logs: hpk.register_plugin(ctx, self._module(), skills=(skill,)) @@ -2107,19 +2055,6 @@ def test_register_plugin_treats_uninspectable_register_skill_as_unsupported(self def test_register_plugin_passes_references_dir_to_a_host_with_an_explicit_parameter( self, ) -> None: - class ExplicitParamHostCtx(FakePluginCtx): - """A host whose register_skill names references_dir directly -- no **kwargs.""" - - def register_skill(self, name, path, description="", references_dir=None) -> None: - self.skills.append( - { - "name": name, - "path": path, - "description": description, - "references_dir": references_dir, - } - ) - with tempfile.TemporaryDirectory() as tmp: skill_path = Path(tmp) / "SKILL.md" skill_path.write_text( @@ -2129,7 +2064,7 @@ def register_skill(self, name, path, description="", references_dir=None) -> Non references_dir.mkdir() skill = hpk.plugin_skill("sample", skill_path, "Sample.", references_dir=references_dir) - ctx = ExplicitParamHostCtx() + ctx = RecordingPluginContext(supports_references_dir=True) hpk.register_plugin(ctx, self._module(), skills=(skill,)) self.assertEqual(ctx.skills[0]["references_dir"], references_dir) @@ -2141,14 +2076,6 @@ def test_register_plugin_retries_without_references_dir_when_host_rejects_it_at_ # Mock(spec=...) or a decorator applied without functools.wraps produces this exact # shape in practice) reports acceptance via inspect.signature, but the real # implementation still raises TypeError for the unexpected keyword at call time. - class FooledProbeHostCtx(FakePluginCtx): - def register_skill(self, **kwargs) -> None: - if "references_dir" in kwargs: - raise TypeError( - "register_skill() got an unexpected keyword argument 'references_dir'" - ) - self.skills.append(kwargs) - with tempfile.TemporaryDirectory() as tmp: skill_path = Path(tmp) / "SKILL.md" skill_path.write_text( @@ -2158,7 +2085,7 @@ def register_skill(self, **kwargs) -> None: references_dir.mkdir() skill = hpk.plugin_skill("sample", skill_path, "Sample.", references_dir=references_dir) - ctx = FooledProbeHostCtx() + ctx = RecordingPluginContext(references_dir_probe_lies=True) with self.assertLogs(level="WARNING") as logs: summary = hpk.register_plugin(ctx, self._module(), skills=(skill,)) @@ -2168,10 +2095,6 @@ def register_skill(self, **kwargs) -> None: self.assertIn("rejected it at call time", "\n".join(logs.output)) def test_register_plugin_reraises_unrelated_type_errors_from_register_skill(self) -> None: - class BrokenHostCtx(FakePluginCtx): - def register_skill(self, **kwargs) -> None: - raise TypeError("register_skill() missing 1 required positional argument") - with tempfile.TemporaryDirectory() as tmp: skill_path = Path(tmp) / "SKILL.md" skill_path.write_text( @@ -2182,7 +2105,15 @@ def register_skill(self, **kwargs) -> None: skill = hpk.plugin_skill("sample", skill_path, "Sample.", references_dir=references_dir) with self.assertRaises(TypeError): - hpk.register_plugin(BrokenHostCtx(), self._module(), skills=(skill,)) + hpk.register_plugin( + RecordingPluginContext( + register_skill_error=TypeError( + "register_skill() missing 1 required positional argument" + ) + ), + self._module(), + skills=(skill,), + ) class PluginReferenceToolTests(unittest.TestCase): diff --git a/tests/test_testing_harness.py b/tests/test_testing_harness.py new file mode 100644 index 0000000..a80fd8a --- /dev/null +++ b/tests/test_testing_harness.py @@ -0,0 +1,618 @@ +"""Contracts for the consumer-facing test harness. + +The harness exists to catch one defect a hand-rolled fake cannot: the host +changing a registrar's signature underneath a plugin. These tests hold it to +that, then to the surrounding promises — usable with no host present, honest +about not having checked, and reachable from an installed package. +""" + +from __future__ import annotations + +import re +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +import hermes_plugin_kit as hpk +from hermes_plugin_kit import testing as hpk_testing + + +class HostV1: + """The host shape the plugin was written against.""" + + def register_tool( + self, name, toolset, schema, handler, requires_env=None, description="", emoji="" + ): ... + + def register_skill(self, name, path, description=""): ... + + +class HostAddedRequired: + """Host gained a required parameter.""" + + def register_tool( + self, + name, + toolset, + schema, + handler, + plugin_name, + requires_env=None, + description="", + emoji="", + ): ... + + def register_skill(self, name, path, description=""): ... + + +class HostRenamed: + """Host renamed a parameter the plugin passes.""" + + def register_tool( + self, name, toolset, schema, handler, requires_env=None, help="", emoji="" + ): ... + + def register_skill(self, name, path, description=""): ... + + +class HostMissingRegistrar: + """Host no longer exposes a surface the plugin registers.""" + + def register_tool( + self, name, toolset, schema, handler, requires_env=None, description="", emoji="" + ): ... + + +def _register_a_tool(ctx) -> None: + """The registration call a plugin makes through the kit.""" + ctx.register_tool( + name="probe_read_note", + toolset="probe", + schema={"type": "function", "function": {"name": "probe_read_note"}}, + handler=lambda args, **kwargs: {"ok": True}, + requires_env=None, + description="Read a note.", + emoji="*", + ) + + +def _register_a_skill(ctx) -> None: + ctx.register_skill(name="probe-skill", path="skills/probe/SKILL.md", description="A probe skill.") + + +class DriftReplayTests(unittest.TestCase): + """Replaying recorded calls through the real signature is the whole point.""" + + def test_added_required_parameter_is_reported_by_name(self) -> None: + ctx = hpk_testing.RecordingPluginContext(name="probe-plugin") + _register_a_tool(ctx) + + report = ctx.check_against_host(HostAddedRequired) + + self.assertFalse(report.clean, report) + self.assertEqual(["register_tool"], [d.registrar for d in report.drifts]) + self.assertIn("plugin_name", report.drifts[0].detail) + + def test_renamed_parameter_is_reported_as_unexpected(self) -> None: + ctx = hpk_testing.RecordingPluginContext(name="probe-plugin") + _register_a_tool(ctx) + + report = ctx.check_against_host(HostRenamed) + + self.assertFalse(report.clean, report) + self.assertIn("description", report.drifts[0].detail) + + def test_positionally_renamed_parameter_is_reported(self) -> None: + """Binding alone cannot see this: Python binds positionals by position.""" + + class HostRenamedPositional: + # Same arity as the real host, first parameter renamed. + def register_hook(self, event_name, callback): ... + + ctx = hpk_testing.RecordingPluginContext(name="probe-plugin") + ctx.register_hook("pre_tool_call", lambda *a, **k: None) + + report = ctx.check_against_host(HostRenamedPositional) + + self.assertFalse(report.clean, report) + self.assertEqual(["register_hook"], [d.registrar for d in report.drifts]) + self.assertIn("hook_name", report.drifts[0].detail) + self.assertIn("event_name", report.drifts[0].detail) + + def test_unrenamed_positional_host_stays_clean(self) -> None: + class HostPositionalV1: + def register_hook(self, hook_name, callback): ... + + ctx = hpk_testing.RecordingPluginContext(name="probe-plugin") + ctx.register_hook("pre_tool_call", lambda *a, **k: None) + + self.assertTrue(ctx.check_against_host(HostPositionalV1).clean) + + def test_removed_registrar_is_reported(self) -> None: + ctx = hpk_testing.RecordingPluginContext(name="probe-plugin") + _register_a_skill(ctx) + + report = ctx.check_against_host(HostMissingRegistrar) + + self.assertFalse(report.clean, report) + self.assertEqual(["register_skill"], [d.registrar for d in report.drifts]) + + def test_unchanged_host_is_clean_and_preserves_the_recording(self) -> None: + ctx = hpk_testing.RecordingPluginContext(name="probe-plugin") + _register_a_tool(ctx) + _register_a_skill(ctx) + + report = ctx.check_against_host(HostV1) + + self.assertTrue(report.clean, report) + self.assertEqual((), report.drifts) + self.assertEqual(["probe_read_note"], [t["name"] for t in ctx.tools]) + self.assertEqual(["probe-skill"], [s["name"] for s in ctx.skills]) + + def test_strict_mode_fails_at_call_time_rather_than_on_replay(self) -> None: + """A consumer calling the fake directly is invisible to a lane-side check.""" + ctx = hpk_testing.RecordingPluginContext(name="probe-plugin", strict_against=HostAddedRequired) + + with self.assertRaises(TypeError) as caught: + _register_a_tool(ctx) + + self.assertIn("plugin_name", str(caught.exception)) + + +class AbsentHostTests(unittest.TestCase): + """An unchecked run must not read as a checked one.""" + + def test_no_host_reports_unchecked_and_names_the_required_revision(self) -> None: + ctx = hpk_testing.RecordingPluginContext(name="probe-plugin") + _register_a_tool(ctx) + + report = ctx.check_against_host(None) + + self.assertFalse(report.checked) + self.assertFalse(report.clean) + self.assertIn(hpk_testing.DEPLOYED_HERMES_REVISION, report.detail) + + def test_deployed_revision_is_a_full_commit_sha(self) -> None: + self.assertRegex(hpk_testing.DEPLOYED_HERMES_REVISION, r"^[0-9a-f]{40}$") + + +class HostShapeModeTests(unittest.TestCase): + """Both branches of the kit's own capability probe must be reachable.""" + + def setUp(self) -> None: + # plugin_skill validates both paths against the filesystem. + self._tmp = tempfile.TemporaryDirectory() + root = Path(self._tmp.name) + (root / "SKILL.md").write_text( + "---\nname: probe-skill\ndescription: A probe skill.\n---\n\n# probe\n" + ) + (root / "references").mkdir() + self.addCleanup(self._tmp.cleanup) + self.skill_path = str(root / "SKILL.md") + self.references_dir = str(root / "references") + + def _skill(self, *, with_references: bool): + return hpk.plugin_skill( + name="probe-skill", + path=self.skill_path, + description="A probe skill.", + references_dir=self.references_dir if with_references else None, + ) + + def test_references_dir_unsupported_host_still_registers_the_skill(self) -> None: + ctx = hpk_testing.RecordingPluginContext( + name="probe-plugin", supports_references_dir=False + ) + + summary = hpk.register_plugin( + ctx, [], skills=[self._skill(with_references=True)], plugin_name="probe-plugin" + ) + + self.assertEqual(("probe-skill",), summary.skills) + self.assertNotIn("references_dir", ctx.skills[0]) + + def test_references_dir_supported_host_receives_it(self) -> None: + ctx = hpk_testing.RecordingPluginContext( + name="probe-plugin", supports_references_dir=True + ) + + hpk.register_plugin( + ctx, [], skills=[self._skill(with_references=True)], plugin_name="probe-plugin" + ) + + self.assertEqual(self.references_dir, str(ctx.skills[0]["references_dir"])) + + def test_lying_probe_host_still_registers_the_skill(self) -> None: + """A permissive signature can report support the host does not have. + + The kit probes `register_skill` for a `references_dir` keyword and + retries without it on a TypeError naming that keyword. A `**kwargs` + host satisfies the probe and can still reject the call, so the retry + branch needs a host shape that lies. + """ + ctx = hpk_testing.RecordingPluginContext( + name="probe-plugin", references_dir_probe_lies=True + ) + + summary = hpk.register_plugin( + ctx, [], skills=[self._skill(with_references=True)], plugin_name="probe-plugin" + ) + + self.assertEqual(("probe-skill",), summary.skills) + self.assertNotIn("references_dir", ctx.skills[0]) + + def test_unrelated_type_error_is_not_swallowed_by_the_retry(self) -> None: + """The retry must be narrow: only a references_dir rejection.""" + ctx = hpk_testing.RecordingPluginContext( + name="probe-plugin", + register_skill_error=TypeError( + "register_skill() missing 1 required positional argument" + ), + ) + + with self.assertRaises(TypeError) as caught: + hpk.register_plugin( + ctx, [], skills=[self._skill(with_references=True)], plugin_name="probe-plugin" + ) + + self.assertIn("missing 1 required positional argument", str(caught.exception)) + + def test_missing_registrar_surfaces_the_unsupported_context_error(self) -> None: + ctx = hpk_testing.RecordingPluginContext( + name="probe-plugin", missing_registrars=("register_skill",) + ) + with self.assertRaises(RuntimeError) as caught: + hpk.register_plugin( + ctx, [], skills=[self._skill(with_references=False)], plugin_name="probe-plugin" + ) + + self.assertIn("register_skill", str(caught.exception)) + + +class ManifestTests(unittest.TestCase): + """The single largest gap between the kit's own fake and a consumer's need.""" + + def test_plugin_config_is_readable_through_load_plugin_config(self) -> None: + ctx = hpk_testing.RecordingPluginContext( + name="probe-plugin", config={"threads_enabled": True} + ) + + self.assertEqual( + {"threads_enabled": True}, hpk.load_plugin_config(ctx, "probe-plugin") + ) + + def test_receipt_identity_comes_from_the_manifest_name(self) -> None: + ctx = hpk_testing.RecordingPluginContext(name="probe-plugin") + + with self.assertLogs("hermes_plugin_kit", level="INFO") as captured: + hpk.register_plugin(ctx, [], plugin_name=None) + + self.assertIn("plugin=probe-plugin", "\n".join(captured.output)) + + +class ReceiptFieldTests(unittest.TestCase): + """The receipt's log order is the external contract, not the dataclass order.""" + + def test_field_order_matches_the_emitted_receipt(self) -> None: + ctx = hpk_testing.RecordingPluginContext(name="probe-plugin") + with self.assertLogs("hermes_plugin_kit", level="INFO") as captured: + hpk.register_plugin(ctx, [], plugin_name="probe-plugin") + + fields = hpk_testing.receipt_fields(captured.records[-1].getMessage()) + + self.assertEqual(list(hpk_testing.RECEIPT_FIELD_ORDER), list(fields)) + + def test_empty_surfaces_read_as_no_values(self) -> None: + ctx = hpk_testing.RecordingPluginContext(name="probe-plugin") + with self.assertLogs("hermes_plugin_kit", level="INFO") as captured: + hpk.register_plugin(ctx, [], plugin_name="probe-plugin") + + fields = hpk_testing.receipt_fields(captured.records[-1].getMessage()) + + self.assertEqual((), fields["tools"]) + + def test_registered_names_appear_under_their_field(self) -> None: + # Captured at the root, not under "hermes_plugin_kit": the kit logs the + # receipt through the decorated handler's own module logger, so the + # logger name depends on where the plugin's tools are defined. + ctx = hpk_testing.RecordingPluginContext(name="probe-plugin") + + @hpk.tool(name="probe_read_note", toolset="probe", description="Read a note.") + def probe_read_note(args, **kwargs): + return {"ok": True} + + with self.assertLogs(level="INFO") as captured: + hpk.register_plugin(ctx, [probe_read_note], plugin_name="probe-plugin") + + fields = hpk_testing.receipt_fields(captured.records[-1].getMessage()) + + self.assertEqual(("probe_read_note",), fields["tools"]) + self.assertEqual((), fields["hooks"]) + + def test_declared_order_is_the_log_order_not_the_dataclass_order(self) -> None: + """These genuinely differ; pinning the wrong one silently passes.""" + import dataclasses + + dataclass_order = [f.name for f in dataclasses.fields(hpk.RegistrationSummary)] + + self.assertNotEqual(dataclass_order, list(hpk_testing.RECEIPT_FIELD_ORDER)) + self.assertEqual( + set(dataclass_order), set(hpk_testing.RECEIPT_FIELD_ORDER), + "the two orders must hold the same fields, only sequenced differently", + ) + + +class RegistrationCheckTests(unittest.TestCase): + """Contracts a consumer would otherwise copy out of the kit's own tests.""" + + def _tool(self, name): + @hpk.tool(name=name, toolset="probe", description=f"{name}.") + def handler(args, **kwargs): + return {"ok": True} + + return handler + + def test_sorted_registration_reports_clean(self) -> None: + ctx = hpk_testing.RecordingPluginContext(name="probe-plugin") + hpk.register_plugin( + ctx, [self._tool("probe_zulu"), self._tool("probe_alpha")], + plugin_name="probe-plugin", + ) + + result = hpk_testing.check_registration(ctx) + + self.assertTrue(result.ok, result) + self.assertEqual((), result.problems) + + def test_unsorted_recording_is_reported(self) -> None: + ctx = hpk_testing.RecordingPluginContext(name="probe-plugin") + ctx.register_tool( + name="probe_zulu", toolset="probe", schema={}, handler=None, + requires_env=None, description="z", emoji="", + ) + ctx.register_tool( + name="probe_alpha", toolset="probe", schema={}, handler=None, + requires_env=None, description="a", emoji="", + ) + + result = hpk_testing.check_registration(ctx) + + self.assertFalse(result.ok, result) + self.assertTrue(any("order" in p for p in result.problems), result.problems) + + def test_duplicate_tool_name_is_reported(self) -> None: + ctx = hpk_testing.RecordingPluginContext(name="probe-plugin") + for _ in range(2): + ctx.register_tool( + name="probe_same", toolset="probe", schema={}, handler=None, + requires_env=None, description="d", emoji="", + ) + + result = hpk_testing.check_registration(ctx) + + self.assertFalse(result.ok, result) + self.assertTrue(any("duplicate" in p for p in result.problems), result.problems) + + def test_same_name_across_slash_and_cli_is_allowed(self) -> None: + ctx = hpk_testing.RecordingPluginContext(name="probe-plugin") + ctx.register_command(name="probe", handler=None, description="d") + ctx.register_cli_command(name="probe", handler=None, description="d") + + self.assertTrue(hpk_testing.check_registration(ctx).ok) + + def test_flattened_tool_schema_is_reported(self) -> None: + ctx = hpk_testing.RecordingPluginContext(name="probe-plugin") + ctx.register_tool( + name="probe_flat", toolset="probe", + schema={"name": "probe_flat", "properties": {"a": {"type": "string"}}}, + handler=None, requires_env=None, description="d", emoji="", + ) + + result = hpk_testing.check_registration(ctx) + + self.assertFalse(result.ok, result) + self.assertTrue( + any("function.parameters" in p for p in result.problems), result.problems + ) + + def test_conforming_schema_passes(self) -> None: + ctx = hpk_testing.RecordingPluginContext(name="probe-plugin") + hpk.register_plugin(ctx, [self._tool("probe_ok")], plugin_name="probe-plugin") + + self.assertTrue(hpk_testing.check_registration(ctx).ok) + + +#: Names the Surface Map documents that the kit deliberately does not export. +#: +#: Keep this short and justified. Every entry is a name the table mentions +#: because a plugin author needs it, but which the kit does not own. +HOST_OWNED_NAMES = { + # Hermes' own class; the kit takes an instance, it does not provide one. + "ContextEngine", +} + + +def _documented_kit_api_names(reference: Path) -> set[str]: + """Backticked identifiers in the Surface Map's `Kit API` column. + + That table is the one place the kit enumerates its own public surface. The + README is not usable for this: it has no API section, and its prose names + host-side calls like `ctx.register_tool` that would fail this guard falsely. + """ + names: set[str] = set() + for line in reference.read_text().splitlines(): + if not line.startswith("| ") or line.count("|") < 5: + continue + column = line.split("|")[2] + for identifier in re.findall(r"`([^`]+)`", column): + names.add(identifier.lstrip("@")) + return names + + +class PublicSurfaceGuardTests(unittest.TestCase): + """A documented name that is not exported is unreachable for a consumer.""" + + REFERENCE = ( + Path(__file__).parents[1] / "skills" / "hermes-plugins" / "references" / "plugin-kit.md" + ) + + def test_the_surface_map_is_readable_and_non_empty(self) -> None: + # A guard whose input set silently became empty would pass forever. + documented = _documented_kit_api_names(self.REFERENCE) + + self.assertGreater(len(documented), 8, "Surface Map parsed as nearly empty") + self.assertIn("tool", documented) + + def test_every_documented_name_is_exported_and_importable(self) -> None: + documented = _documented_kit_api_names(self.REFERENCE) - HOST_OWNED_NAMES + + missing_from_all = sorted(n for n in documented if n not in hpk.__all__) + not_importable = sorted(n for n in documented if not hasattr(hpk, n)) + + self.assertEqual([], missing_from_all, "documented but absent from __all__") + self.assertEqual([], not_importable, "documented but not importable") + + def test_every_exported_name_is_importable(self) -> None: + self.assertEqual([], sorted(n for n in hpk.__all__ if not hasattr(hpk, n))) + + def test_the_guard_fails_when_a_documented_name_is_unexported(self) -> None: + """Proves the guard has teeth rather than trivially passing.""" + documented = {"tool", "a_name_the_kit_does_not_export"} + + self.assertEqual( + ["a_name_the_kit_does_not_export"], + sorted(n for n in documented if n not in hpk.__all__), + ) + + +def _make_checkout(root: Path, revision_marker: str) -> str: + """A real git repo with one commit, so HEAD comparison is genuine.""" + root.mkdir(parents=True, exist_ok=True) + (root / "hermes_cli").mkdir(exist_ok=True) + (root / "hermes_cli" / "plugins.py").write_text(f"# {revision_marker}\n") + run = lambda *a: subprocess.run( # noqa: E731 + ["git", "-C", str(root), *a], check=True, capture_output=True + ) + run("init", "-q") + run("config", "user.email", "probe@example.com") + run("config", "user.name", "Probe") + run("add", "-A") + run("commit", "-q", "-m", revision_marker) + return subprocess.run( + ["git", "-C", str(root), "rev-parse", "HEAD"], + check=True, capture_output=True, text=True, + ).stdout.strip() + + +class CheckoutResolverTests(unittest.TestCase): + """The replay is unreachable for a consumer unless this ships.""" + + def setUp(self) -> None: + self._tmp = tempfile.TemporaryDirectory() + self.addCleanup(self._tmp.cleanup) + self.root = Path(self._tmp.name) + + def test_offline_with_no_checkout_returns_an_unchecked_result(self) -> None: + """The case a consumer in a sandboxed CI run actually hits.""" + resolved = hpk_testing.resolve_hermes_checkout( + cache_dir=self.root / "cache", + env={}, + fetcher=lambda *a, **k: (_ for _ in ()).throw( + OSError("network is unreachable") + ), + ) + + self.assertFalse(resolved.available) + self.assertIsNone(resolved.path) + self.assertIn(hpk_testing.DEPLOYED_HERMES_REVISION, resolved.detail) + self.assertIn("network is unreachable", resolved.detail) + + def test_offline_result_feeds_the_unchecked_report(self) -> None: + ctx = hpk_testing.RecordingPluginContext(name="probe-plugin") + _register_a_tool(ctx) + resolved = hpk_testing.resolve_hermes_checkout( + cache_dir=self.root / "cache", env={}, + fetcher=lambda *a, **k: (_ for _ in ()).throw(OSError("offline")), + ) + + report = ctx.check_against_host(resolved.plugin_context_class()) + + self.assertFalse(report.checked) + self.assertFalse(report.clean) + + def test_explicit_path_wins_and_no_fetch_is_attempted(self) -> None: + head = _make_checkout(self.root / "supplied", "supplied-checkout") + fetched = [] + + resolved = hpk_testing.resolve_hermes_checkout( + cache_dir=self.root / "cache", + env={"HERMES_AGENT_PATH": str(self.root / "supplied")}, + fetcher=lambda *a, **k: fetched.append(a) or None, + ) + + self.assertTrue(resolved.available, resolved.detail) + self.assertEqual(self.root / "supplied", resolved.path) + self.assertEqual(head, resolved.revision) + self.assertEqual([], fetched, "a supplied checkout must not trigger a fetch") + + def test_explicit_path_that_is_not_a_checkout_is_refused(self) -> None: + (self.root / "empty").mkdir() + + resolved = hpk_testing.resolve_hermes_checkout( + cache_dir=self.root / "cache", + env={"HERMES_AGENT_PATH": str(self.root / "empty")}, + fetcher=lambda *a, **k: None, + ) + + self.assertFalse(resolved.available) + self.assertIn("empty", resolved.detail) + + def test_cache_at_the_right_revision_is_reused_without_fetching(self) -> None: + cache = self.root / "cache" + head = _make_checkout(cache, "cached") + fetched = [] + + resolved = hpk_testing.resolve_hermes_checkout( + revision=head, cache_dir=cache, env={}, + fetcher=lambda *a, **k: fetched.append(a) or None, + ) + + self.assertTrue(resolved.available, resolved.detail) + self.assertEqual(head, resolved.revision) + self.assertEqual([], fetched, "a cache at the pin must not refetch") + + def test_cache_at_the_wrong_revision_is_never_used_as_the_pin(self) -> None: + cache = self.root / "cache" + _make_checkout(cache, "some-other-revision") + wanted = "0" * 40 + + resolved = hpk_testing.resolve_hermes_checkout( + revision=wanted, cache_dir=cache, env={}, + fetcher=lambda *a, **k: (_ for _ in ()).throw(OSError("offline")), + ) + + self.assertFalse(resolved.available) + self.assertNotIn("some-other-revision", str(resolved.path)) + + +class ImportHygieneTests(unittest.TestCase): + """The module ships in the wheel and must cost nothing until it is used.""" + + def test_import_pulls_in_neither_hermes_nor_a_test_framework(self) -> None: + probe = ( + "import sys; import hermes_plugin_kit.testing as t; " + "leaked = sorted(m for m in sys.modules " + "if m.split('.')[0] in {'hermes_cli', 'hermes_state', 'agent', 'tools', 'pytest'}); " + "print(','.join(leaked))" + ) + result = subprocess.run( + [sys.executable, "-c", probe], capture_output=True, text=True, check=True + ) + + self.assertEqual("", result.stdout.strip(), f"leaked imports: {result.stdout!r}") + + +if __name__ == "__main__": + unittest.main()