From 7c52ca956e50669c8187c84a62e3d84e62a970ea Mon Sep 17 00:00:00 2001 From: Offending Commit Date: Fri, 13 Nov 2026 09:24:47 -0600 Subject: [PATCH 1/9] docs(plans): plan the @platform annotation Plan for registering Hermes gateway platforms through the kit, with preflight before any registration, a fail-loud replacement guard behind an operator config override, receipt fields, and an option-name drift check. Claude-Session: https://claude.ai/code/session_01B6XeAWUPdrx34tr5dTg5dY --- ...1-13-0900-feat-platform-annotation-plan.md | 356 ++++++++++++++++++ 1 file changed, 356 insertions(+) create mode 100644 docs/plans/2026-11-13-0900-feat-platform-annotation-plan.md diff --git a/docs/plans/2026-11-13-0900-feat-platform-annotation-plan.md b/docs/plans/2026-11-13-0900-feat-platform-annotation-plan.md new file mode 100644 index 0000000..f21b918 --- /dev/null +++ b/docs/plans/2026-11-13-0900-feat-platform-annotation-plan.md @@ -0,0 +1,356 @@ +--- +title: Platform Annotation - Plan +type: feat +date: 2026-11-13 +artifact_contract: ce-unified-plan/v1 +product_contract_source: ce-plan-bootstrap +execution: code +--- + +# Platform Annotation - Plan + +## Goal Capsule + +- **Objective:** A Hermes plugin author can add a messaging platform with the same guarantees the kit already gives tools and hooks: a bad declaration fails before anything registers, an existing platform is never replaced unless the operator allowed it, the registration receipt names the platform, and the drift replay notices when Hermes changes the platform contract. +- **Means:** An `@platform(...)` annotation on the adapter class, discovered and registered by `register_plugin` (KTD1, KTD2). +- **Authority:** This plan's Requirements govern behavior; the deployed Hermes pin (`bf0203a`, `DEPLOYED_HERMES_REVISION` in `hermes_plugin_kit/testing.py`) governs every host fact; repo `AGENTS.md` governs conventions. +- **Base:** `origin/main` at `ca9e1c9`. Local `main` was four merges behind when this plan was written; branch from `origin/main`. +- **Execution profile:** One PR, opened as a draft at the first commit, flipped to ready when the Definition of Done holds. +- **Stop conditions:** Stop and ask if `DEPLOYED_HERMES_REVISION` in `hermes_plugin_kit/testing.py` no longer reads `bf0203a794a07aac3ff764972ab9087baa4e4f4e` and, at the new pin, `register_platform`, `PlatformEntry`, `PlatformRegistry.is_registered`, `PlatformRegistry.snapshot_registration`, `PlatformRegistry.current_scope_key`, `core_ships_platform` or `BasePlatformAdapter` changed shape. +- **Who finishes:** The implementing agent ships through to an open PR; merging needs the owner. + +--- + +## Product Contract + +### Summary + +Add an `@platform(...)` annotation that marks a `BasePlatformAdapter` subclass as a gateway platform, and make `register_plugin` validate and register it through `ctx.register_platform`. Replacing a platform that already exists fails loudly unless the operator names it in the plugin's config. The receipt, the recording test host, the drift replay, the README and the authoring skill all learn about platforms. + +### Problem Frame + +The kit registers commands, tools, middleware, hooks, skills, providers and a context engine, but not platforms. A plugin that adds a messaging channel has to call `ctx.register_platform` directly, outside the kit, which is what the planned private Daphne web channel in the Nightingale plugin was about to do. + +That direct call gets none of the kit's guarantees, and platforms need them more than tools do: + +- **The option surface churns.** `PlatformEntry` had 26 fields at `f80f453` (2026-08-14) and 46 at the pin (2026-10-22). An older host rejects an unknown option with a `TypeError` raised mid-registration, after other surfaces may already be registered. +- **Some options decide who may talk to the agent.** `trusted_inbound`, `allowed_users_env`, `allowlist_suppresses_pairing` and `group_allowed_chats_env` are access policy, not display. +- **Replacement is silent.** The platform registry is last-writer-wins; a plugin that registers `telegram` replaces the real adapter and Hermes logs it at INFO (`PlatformRegistry.register` in `gateway/platform_registry.py`). +- **Refusal is silent.** `PluginContext.register_platform` returns `None` when its registration did not take, and nothing checks it. +- **Drift is invisible.** `register_platform` takes `**entry_kwargs`, so replaying a recorded call against its signature accepts any option name; a removed or renamed field would report clean. + +### Requirements + +**Declaring a platform** + +- R1. A plugin declares a platform by annotating its adapter class with `@platform(...)`, giving at least a name, a label and a passive dependency check. +- R2. A platform name must already be in the form Hermes keys on: non-empty, stripped and lowercase. Anything else fails at decoration time. +- R3. Every other `PlatformEntry` option the host supports can be passed through the annotation without the kit hard-coding it (KTD2). +- R4. Annotating does not import Hermes. + +**Registering it** + +- R5. `register_plugin` discovers annotated adapters alongside the other declarations, rejects two declarations that share a platform name, and registers each platform through `ctx.register_platform`. +- R6. Every platform check finishes before the first `ctx.register_*` call, so a bad platform declaration registers nothing at all. +- R7. An option name the host's `PlatformEntry` does not have fails the registration, unless the plugin marked that option as one it accepts losing; a dropped option is logged by name. +- R8. The annotated class must subclass the host's `BasePlatformAdapter`; checked at `register_plugin` time. +- R9. `trusted_inbound` is never set unless the plugin sets it explicitly, and setting it on a platform Hermes ships fails in preflight rather than mid-registration. +- R10. When Hermes returns `None` from `register_platform`, `register_plugin` raises naming the platform instead of reporting success. + +**Replacing an existing platform** + +- R11. Registering a platform whose name already exists fails loudly before anything registers. "Exists" means Hermes ships it, or it is already registered when this plugin registers. +- R12. The only override is an explicit list of platform names in the plugin's own `plugins.` config. The failure message names the platform, its current owner where known, and the exact config key to set. + +**Receipt and drift** + +- R13. The registration receipt names each registered platform and each platform it replaced under an override. +- R14. The recording test host records `register_platform` calls, and the drift replay reports an option the host's `PlatformEntry` no longer has. + +**Docs** + +- R15. The README, the authoring skill reference and repo `AGENTS.md` describe the annotation, the replacement override, and the "accepts losing" marker. + +### Key Decisions + +- **Replacing an existing platform requires an operator config flag, not a code flag.** (session-settled: user-directed — chosen over a decorator argument the plugin author sets: the person running the profile decides whether a built-in channel is swapped out.) Governs R11, R12. + +### Scope Boundaries + +- Writing any platform adapter, including the Daphne web channel. +- Base-adapter helpers (connection, typing, media) — `BasePlatformAdapter` and Hermes's public helpers already own these. +- `register_platform_handler` / `register_telegram_handler`, which add handlers to platforms that already exist. A separate surface; Nightingale's `getattr(ctx, "register_telegram_handler", None)` path is untouched. +- Considered and not built: **decorating a factory function instead of a class.** Hermes's examples and every bundled plugin pass the class or a one-line lambda over it; a plugin that needs constructor arguments can subclass. Revisit if a consumer needs a factory the class cannot express. +- Considered and not built: **guarding against a plugin that loads after this one and takes the name.** The kit only sees its own registration; Hermes's last-writer-wins applies there. Revisit if Hermes exposes a registration hook the kit can observe. +- Considered and not built: **a kit-owned baseline of `PlatformEntry` field names.** It would go stale at the observed rate of change; the host's own dataclass is the source (KTD2). + +### Sources + +- Host API at the pin: `PluginContext.register_platform` (`hermes_cli/plugins.py`), `PlatformEntry`, `PlatformRegistry.register`, `core_ships_platform` (`gateway/platform_registry.py`), `Platform._missing_` (`gateway/config.py`), `BasePlatformAdapter` (`gateway/platforms/base.py`). +- Guide at the pin: `website/docs/developer-guide/adding-platform-adapters.md` (feature-detect pattern via `dataclasses.fields(PlatformEntry)`, `trusted_inbound` warning) and `gateway/platforms/ADDING_A_PLATFORM.md`. +- Loading: `gate_manifest` (`hermes_cli/plugins_discovery.py`) defers only bundled `kind: platform` plugins; a user plugin with tools and a platform loads eagerly when enabled. +- Reference consumer at the pin: `plugins/platforms/irc/adapter.py` `register`. +- Kit memory: `record-and-bind-beats-strict-fakes` (why option names need their own replay check). + +--- + +## Planning Contract + +### Key Technical Decisions + +- KTD1. **The annotation marks the class and does not wrap it.** `@platform` sets a spec attribute on the class (alongside `_hpk_tool_spec` and friends) and returns the class unchanged, so `isinstance`, subclassing and Hermes's own construction behave as written. The class itself is the `adapter_factory`, because Hermes calls `adapter_factory(PlatformConfig)` and the documented adapter shape is `__init__(self, config)`. +- KTD2. **Options pass through and are checked against the host's own `PlatformEntry`.** `register_plugin` reads `dataclasses.fields(PlatformEntry)` from the host during preflight, importing it lazily the way the context-engine path imports `ContextEngine`. Unknown names fail (R7); names the plugin marked as acceptable to lose are dropped and logged. The kit refuses host-owned keys (`source`, `plugin_name`) and keys that duplicate the annotation's named arguments. Chosen over typed keyword arguments for all 46 fields, which would trail Hermes by weeks. +- KTD3. **Existence is read without materializing deferred loaders.** `PlatformRegistry.get` runs a bundled platform's deferred loader and imports its SDK, so preflight never calls it. Instead it uses `core_ships_platform(name)` (Hermes ships it, answered from manifests) or `platform_registry.is_registered(name)` (public, and documented at the pin to count a deferred loader as registered without importing it). Both are needed: `core_ships_platform` also covers static `Platform` enum members that need not sit in the registry. The owner comes from `snapshot_registration(name, scope=PlatformRegistry.current_scope_key())`, which reads concrete and deferred state without resolving either; `PlatformEntry.plugin_name` names it. An existing entry whose `plugin_name` equals this plugin's host manifest name (`ctx.manifest.name`, the value `register_platform` writes into `plugin_name` at the pin, not the receipt identity) is a re-registration, not a replacement, but only for a name `core_ships_platform` answers false: a core-shipped name always needs the override, whoever registered it last. On a host missing any of these, preflight fails closed rather than skipping the guard. `core_ships_platform`, `PlatformRegistry.is_registered`, `PlatformRegistry.snapshot_registration` and `PlatformRegistry.current_scope_key` were read at the pin on 2026-11-13, alongside `PluginContext.register_platform`, `PlatformEntry` and `BasePlatformAdapter`; U5 binds all seven. +- KTD4. **The override lives at `plugins..replace_platforms`, read through `load_plugin_config`.** A list of platform names. A name on the list that does not currently exist is allowed and changes nothing. (session-settled: user-directed — chosen over a decorator argument: the operator decides.) Instantiates the Key Decision; Governs R11, R12. +- KTD5. **Platforms register first among the mutations, and a refusal rolls back the platforms already registered.** Their refusal (R10) is the most likely late failure, so registering them before the context engine, commands and tools keeps a refusal from leaving those half-registered. Preflight (R6) still catches every known failure before any mutation. A refusal can only appear after a `register_platform` call, so to keep R6's "registers nothing" when a later platform in the same plugin is refused, the kit keeps each returned handle and, on a `None` return, calls `dispose()` on the handles from this call in reverse order before raising. At the pin, `PluginRegistration.dispose` (`hermes_cli/plugins_ledger.py`) releases the scoped lease, which restores the entry an override replaced and is identity-conditional, so it never removes a newer registration. +- KTD6. **The receipt gains `platforms` and `replaced_platforms`, appended after the existing fields.** `log_registration_summary` keeps its current field order and appends the two new fields at the end, so log parsers keyed on position still read the old fields correctly. `RegistrationSummary` gains matching tuple fields defaulting to empty. +- KTD7. **The drift replay checks option names in addition to the signature.** Signature binding cannot see names inside `**entry_kwargs`, so for `register_platform` the replay also compares each recorded option name with the host checkout's `PlatformEntry` fields and reports missing ones as drift. This extends the existing `plugin-test-harness` OpenSpec requirement "Recorded calls replay against the real host signatures" with a new scenario. + +### High-Level Technical Design + +Preflight order inside `register_plugin` for platforms. Every node before "register platforms" is a pure check; a failure there raises with nothing registered. A host refusal can only surface at "register platforms" itself, so that edge disposes the platform handles this call already holds before raising (KTD5); no other surface has registered yet. + +```mermaid +flowchart TB + A[collect @platform classes] --> B{duplicate name in this plugin?} + B -->|yes| X[raise] + B -->|no| C{ctx.register_platform callable?} + C -->|no| X + C -->|yes| D[import host PlatformEntry, BasePlatformAdapter, core_ships_platform] + D -->|import fails| X + D --> E{class subclasses BasePlatformAdapter?} + E -->|no| X + E -->|yes| F{every option a PlatformEntry field?} + F -->|unknown and not marked losable| X + F -->|unknown but losable| F2[drop and log] --> G + F -->|all known| G{trusted_inbound on a core name?} + G -->|yes| X + G -->|no| H{name exists: core-shipped or already registered?} + H -->|registered by this plugin, not core-shipped| J + H -->|yes, not in replace_platforms| X + H -->|yes, in replace_platforms| I[mark as replacement] + H -->|no| J + I --> J[other surfaces' preflight] + J --> K[register platforms] + K -->|host returns None| R[dispose handles registered so far] --> X + K --> L[register remaining surfaces, emit one receipt] +``` + +### Implementation Constraints + +- Keep `@tool`, `@command`, `register_all` and the existing `register_plugin` signature backward compatible; `register_plugin` gains no required argument. +- `register_plugin` emits exactly one receipt through `log_registration_summary`. +- No module-level Hermes import in `hermes_plugin_kit/__init__.py` (offendingcommit/hermes-plugin-kit#49 removed the last one). +- Redact secret-looking values: never log option values, only option names. + +--- + +## Implementation Units + +### U1. `@platform` annotation and decoration-time validation + +**Goal:** A class can be annotated as a platform, and malformed annotations fail at import time. + +**Requirements:** R1, R2, R3, R4, R9 + +**Dependencies:** none + +**Files:** +- `hermes_plugin_kit/__init__.py` — the `platform` decorator, its spec attribute, export in `__all__`. +- `tests/test_platforms.py` (new) — decoration-time behavior. This seam catches bad declarations without any host; it cannot see host fields or registry state. + +**Approach:** +- Named arguments for the always-present fields (name, label, check function, and the optional validate function, required env, install hint), plus a free mapping of further options and a set of option names the plugin accepts losing (KTD2). +- Validate at decoration time only what needs no host: name form (R2), non-empty label, callable check and validate functions, option names are identifiers, the losable set is a subset of the passed options, the target is a class, and `trusted_inbound` is not defaulted on (R9). +- Mark, do not wrap (KTD1). Read the spec back with `vars(cls).get(...)`, never `getattr`: a class attribute is inherited, so `getattr` would make an unannotated subclass of an annotated adapter look like a second declaration of the same platform. + +**Patterns to follow:** `hook` and `middleware` decorators in `hermes_plugin_kit/__init__.py` (spec attribute plus `ValueError` on bad input); `plugin_skill` for a declaration with a validated optional set. + +**Test scenarios:** +- Annotating a class with name `web_chat`, label `Web Chat` and a check function returns the same class object, carrying a spec with those values. +- Name `Web_Chat`, ` web_chat `, or an empty string each raises `ValueError` naming the rule. +- A non-callable check function raises `TypeError`. +- Annotating a function instead of a class raises `TypeError`. +- A losable option that was not passed as an option raises `ValueError` naming it. +- Passing `source` or `plugin_name` as an option raises `ValueError` saying the host owns it. +- Importing a module that uses `@platform` with Hermes absent from `sys.modules` and from the path succeeds (R4). + +**Verification:** The new tests pass and the annotation is reachable as `hermes_plugin_kit.platform` from a built wheel (the existing public-surface check covers this once `__all__` lists it). + +### U2. Discovery, preflight and registration in `register_plugin` + +**Goal:** `register_plugin` registers annotated platforms with every check done before any mutation, and reports them in the receipt. + +**Requirements:** R5, R6, R7, R8, R9, R10, R13 + +**Dependencies:** U1 + +**Files:** +- `hermes_plugin_kit/__init__.py` — discovery in `register_plugin`, platform preflight, registration, `RegistrationSummary` fields, `log_registration_summary` fields (KTD6). +- `hermes_plugin_kit/testing.py` — the receipt assertion helper that pins field order, if it enumerates fields. +- `tests/test_platforms.py` — registration behavior against the recording host plus a stand-in for the host's platform module. + +**Approach:** +- Collect platform specs in the same declaration loop as the other surfaces; duplicate names raise (R5). +- Run the platform preflight from the High-Level Technical Design before any other surface's mutation (R6, KTD5). +- Register with keyword arguments only; on a `None` return, dispose the handles of platforms this call already registered, then raise (R10, KTD5). +- Append `platforms` and `replaced_platforms` to the summary and receipt (KTD6). +- Iterable registration (a list of declarations) must accept annotated classes too, not only decorated callables; the current "declaration iterables must contain only decorated callables" check needs to admit a class carrying the platform spec. + +**Execution note:** Start with a failing test where a bad option name is declared next to a valid tool, asserting the tool was not registered. That is the ordering guarantee this unit exists for. + +**Patterns to follow:** The context-engine block in `register_plugin` (lazy host import, `RuntimeError` when the registrar is missing, preflight before mutation); `_validate_generation_providers`. + +**Test scenarios:** +- A module with one tool and one annotated platform registers both; the receipt line ends with `platforms=web_chat; replaced_platforms=`. +- Two annotated classes sharing the name `web_chat` raise `ValueError` naming it, and nothing is registered. +- An option `display_tier="minimal"` against a host `PlatformEntry` without that field raises naming `display_tier`, and the tool declared alongside was not registered. +- The same option marked losable is dropped; registration proceeds and a warning names `display_tier`. +- A class not subclassing the host's `BasePlatformAdapter` raises `TypeError` naming the class. +- `trusted_inbound=True` on name `telegram` raises before any registration. +- A host `register_platform` returning `None` makes `register_plugin` raise naming the platform. +- Two platforms where the host refuses the second: `register_plugin` raises, the first platform's handle was disposed, and no tool or command declared alongside was registered. +- An unannotated subclass of an annotated adapter, defined in the same module, is not discovered as a platform and raises no duplicate-name error. +- A context without `register_platform` raises `RuntimeError` when a platform is declared, and is fine when none is. +- Passing an iterable that holds an annotated class registers it. +- A module with no platforms produces a receipt with `platforms=` and every pre-existing field in its old position. + +**Verification:** New tests pass; every existing `register_plugin` and receipt test still passes unchanged except for the appended fields. + +### U3. Replacement guard and the `replace_platforms` override + +**Goal:** Registering over an existing platform fails loudly unless the operator listed it. + +**Requirements:** R11, R12, R13 + +**Dependencies:** U2 + +**Files:** +- `hermes_plugin_kit/__init__.py` — existence check and override read inside the platform preflight. +- `tests/test_platforms.py` — guard behavior. + +**Approach:** +- "Exists" per KTD3: `core_ships_platform(name)` or `platform_registry.is_registered(name)`; owner from `snapshot_registration` in the current scope. Never `get`. The own-plugin reload exemption compares `plugin_name` with `ctx.manifest.name` and applies only to names `core_ships_platform` answers false. +- Read `replace_platforms` through `load_plugin_config` (KTD4). A non-list value fails preflight with the key named. +- The error names the platform, the current owner when the registry exposes it (`source`, `plugin_name`), and the exact key `plugins..replace_platforms`. +- A permitted replacement lands in `replaced_platforms` on the receipt. + +**Test scenarios:** +- Declaring `telegram` with no override raises; the message contains `telegram` and `plugins..replace_platforms`, and nothing registered. +- Declaring `telegram` with `replace_platforms: [telegram]` registers it and the receipt shows `replaced_platforms=telegram`. +- Declaring `web_chat` while another plugin's `web_chat` is already registered raises naming that plugin as owner, and nothing is registered. +- Declaring a bundled platform's name while it is still only a deferred loader raises, nothing is registered, and the bundled module is absent from `sys.modules`. +- The same deferred name with `replace_platforms` naming it registers, the receipt lists it under `replaced_platforms`, and the bundled module is still absent from `sys.modules`. +- An existing entry whose `plugin_name` is this plugin's own name (a reload) registers without an override and is not listed under `replaced_platforms`. +- An existing `telegram` entry whose `plugin_name` is this plugin's own name still raises without `replace_platforms`: the reload exemption never covers a core-shipped name. +- Declaring a new name `web_chat` with `replace_platforms: [telegram]` registers normally and the receipt shows `replaced_platforms=`. +- `replace_platforms: telegram` (a string, not a list) raises naming the key. +- A host missing any of `core_ships_platform`, `is_registered`, `snapshot_registration` or `current_scope_key` makes preflight raise once, listing every missing name, rather than skip the guard. One parametrized test, driven from the same tuple of names preflight checks, covers each single absence plus all four absent, and asserts the message names every absent symbol (set membership, not exact text). +- In every raising case above, the recording host shows no registration of any kind, including a tool declared in the same plugin: the guard runs in preflight (R6), not inside platform registration. + +`gate_manifest` at the pin defers only manifests whose `source` is `bundled`, so a user plugin never meets its own name as a deferred loader; a deferred hit is always another owner. + +**Verification:** New tests pass, and the U4 real-host lane shows the guard refusing a core name against the pinned Hermes. + +### U4. Recording host and option-name drift replay + +**Goal:** Plugin tests can record platform registrations, and the drift replay reports a removed or renamed platform option. + +**Requirements:** R14 + +**Dependencies:** U2 + +**Files:** +- `hermes_plugin_kit/testing.py` — `register_platform` on `RecordingPluginContext` (returning a handle with `dispose()`, so KTD5's rollback runs against the recording host), `register_platform` in `_ALL_REGISTRARS`, the option-name check in the replay (KTD7), and the `check_against_host` / `DriftReport` shape change below. +- `openspec/changes//` — a spec delta adding "Host removes a platform option" to the `plugin-test-harness` requirement "Recorded calls replay against the real host signatures". +- `tests/test_testing_harness.py`, `tests/test_drift_classification.py` — replay behavior. + +**Approach:** +- Record keyword calls like the other keyword-only registrars; no `_POSITIONAL_PARAMS` entry is needed. +- In the replay, after signature binding, read `PlatformEntry` field names from the host checkout and diff them against each recorded option name. `check_against_host(host)` takes only the `PluginContext` class today, so it gains an optional keyword carrying the `PlatformEntry` field names, which `ResolvedHost` fills from the checkout. Existing callers that pass only the class keep working. +- `DriftReport.checked` is one boolean for the whole report, so it cannot say "signatures checked, platform options not". Give the report a per-surface unchecked record (for example a tuple of unchecked surface names with reasons) and keep `checked` meaning "every surface was checked". +- A host checkout without `gateway/platform_registry.py`, or a call that passes no field names while a `register_platform` call was recorded, reports the platform-option surface as not checked, never clean (spec requirement "Absent host is reported, never assumed clean"). + +**Test scenarios:** +- A plugin registering `web_chat` through `RecordingPluginContext` shows one recorded `register_platform` call with its options. +- Replaying that call against a host whose `PlatformEntry` lacks `display_tier` reports drift naming `register_platform` and `display_tier`. +- Replaying against a host that has every recorded option reports clean. +- Replaying against a host checkout with no platform registry module reports the surface as not checked. +- Every existing replay scenario (added parameter, renamed keyword, renamed positional, removed registrar, unchanged host) still passes. + +**Verification:** Harness tests pass; `openspec validate` (through `just spec-validate`) accepts the change. + +### U5. Real-host contract test at the pin + +**Goal:** Prove the annotation registers against the real pinned Hermes, not only the recording host. + +**Requirements:** R5, R8, R10, R11 + +**Dependencies:** U3 + +**Files:** +- `tests/test_hermes_contract.py` — platform cases using the real `PluginContext` and `platform_registry`. + +**Approach:** +- Reuse the module's existing real-host setup; build a minimal `BasePlatformAdapter` subclass inside the test. +- Unregister what the test registers so the shared registry stays clean for other cases. + +**Patterns to follow:** The existing context-engine and skill cases in `tests/test_hermes_contract.py`. + +**Test scenarios:** +- Registering `hpk_contract_platform` through `register_plugin` leaves a `PlatformEntry` in the real registry with the declared label, check function and options. +- Declaring `telegram` without an override is refused before the real registry changes. +- Declaring an option the pinned `PlatformEntry` lacks is refused before the real registry changes. +- Rollback against the real registry: register a fresh platform and an overriding `telegram` (with `replace_platforms`), force the host to refuse a third (wrap the real `platform_registry.register` so it skips storing that one entry; at the pin `register_platform` then sees `snapshot_registration` disagree and returns `None`, which is the host's own refusal path, not an option error; the test also asserts the wrapper ran, so it cannot pass if the host stops calling through the instance), and assert that the fresh name is gone and the original `telegram` entry is back, compared with `snapshot_registration` taken before the call. +- Every host symbol the preflight depends on accepts the call the kit makes, checked by binding the kit's own call shape with `inspect.signature`, not by `hasattr`: `PluginContext.register_platform`, the `PlatformEntry` dataclass, `PlatformRegistry.is_registered`, `PlatformRegistry.snapshot_registration`, the static `PlatformRegistry.current_scope_key`, the module function `core_ships_platform` in `gateway/platform_registry.py`, `BasePlatformAdapter` in `gateway/platforms/base.py` (importable, and the minimal test adapter subclasses it), and `PluginRegistration.dispose` on the handle `register_platform` returns. A pin bump that breaks any of them fails this case, so the Goal Capsule stop condition never depends on someone remembering it. Falsify once by renaming a parameter in a scratch checkout. + +**Verification:** `just test-contract-pinned` runs these cases against `bf0203a` and reports them as run, not skipped (memory `skipped-is-not-passed-on-py311`: check the count, not the exit code). + +### U6. Docs and authoring skill + +**Goal:** Plugin authors can find and use the annotation without reading the source. + +**Requirements:** R15 + +**Dependencies:** U3 + +**Files:** +- `README.md` — a platform section next to "Subagents and specialized providers", and the receipt fields in "Structured plugin lifecycle receipts". +- `skills/hermes-plugins/references/plugin-kit.md` — Surface Map, What The Kit Owns, Failure Traps (replacement, losable options, deferred bundled platforms). +- `AGENTS.md` — one working rule for platform registration. + +**Approach:** Show one complete adapter-plus-annotation example, the `replace_platforms` config snippet, and the losable-option marker. Point to Hermes's adapter guide for the adapter itself rather than restating it. + +**Test expectation:** none -- documentation; the existing documented-names check in `test_kit.py` covers that `platform` is exported. + +**Verification:** Every name the README uses is exported, and the skill reference matches the shipped API. + +--- + +## Open Questions + +- **Deferred to implementation:** the exact name of the losable-options argument. Keep it consistent with `skipped_optional_skills`; the summary fields are fixed by KTD6. + +--- + +## Verification Contract + +| Gate | Command | Proves | +|---|---|---| +| Unit and harness tests | `just test` | U1–U4 behavior; check the printed test count went up by the new cases | +| Pinned real host | `just test-contract-pinned` | U5 against `bf0203a`; cases reported as run | +| Spec | `just spec-validate` | U4's OpenSpec change is valid | +| Packaging | `just build`, `just check-dist`, `just check-install` | `platform` is exported from the built wheel | + +Capture each command's own exit status (`cmd > log 2>&1; echo "EXIT=$?" >> log`), not one read through a pipe. + +--- + +## Definition of Done + +- Every test scenario above exists and passes. Each guard named in R6–R12 has been falsified: removing it makes its own test fail and no other test fail. +- Every existing test case is kept; any case whose expected receipt line changed is adapted in place, not deleted. +- The receipt keeps every pre-existing field in its old position. +- The OpenSpec change is valid and archived with the merge, per the repo's spec-driven rule. +- No abandoned-attempt code remains in the diff. +- The PR is up to date with `origin/main` by merge, every gate in the Verification Contract is green on the final head, and the PR body names the deployed pin it was proven against. From 2af44e5b4d458eabccba722e7f098c4f63d215a3 Mon Sep 17 00:00:00 2001 From: Offending Commit Date: Fri, 13 Nov 2026 09:24:47 -0600 Subject: [PATCH 2/9] feat(platforms): add the @platform annotation Marks a BasePlatformAdapter subclass as a gateway platform without wrapping it, so the class itself is the adapter factory Hermes calls. Decoration validates what needs no host: the name is already in the lowercase form Hermes keys on, the label is non-empty, check and validate are callable, option names are identifiers that neither duplicate a named argument nor claim a host-owned field, and every optional option was actually passed. Annotating never imports Hermes. Registration through register_plugin follows in the next commits. Claude-Session: https://claude.ai/code/session_01B6XeAWUPdrx34tr5dTg5dY --- hermes_plugin_kit/__init__.py | 82 +++++++++++++++++++++++ tests/test_platforms.py | 118 ++++++++++++++++++++++++++++++++++ 2 files changed, 200 insertions(+) create mode 100644 tests/test_platforms.py diff --git a/hermes_plugin_kit/__init__.py b/hermes_plugin_kit/__init__.py index fe9c423..a1b53f8 100644 --- a/hermes_plugin_kit/__init__.py +++ b/hermes_plugin_kit/__init__.py @@ -81,6 +81,7 @@ def register(ctx): "command", "middleware", "hook", + "platform", "plugin_skill", "get_subagent_lifecycle", "register_plugin", @@ -136,6 +137,15 @@ def register(ctx): _COMMAND_SPEC_ATTR = "_hpk_command_spec" _MIDDLEWARE_SPEC_ATTR = "_hpk_middleware_spec" _HOOK_SPEC_ATTR = "_hpk_hook_spec" +_PLATFORM_SPEC_ATTR = "_hpk_platform_spec" +# PlatformEntry fields Hermes fills itself; a plugin passing them would forge +# its own provenance. +_HOST_OWNED_PLATFORM_OPTIONS = frozenset({"source", "plugin_name"}) +# register_platform parameters the annotation already names. +_NAMED_PLATFORM_OPTIONS = frozenset({ + "name", "label", "adapter_factory", "check_fn", + "validate_config", "required_env", "install_hint", +}) _REDACT_HINTS = ("token", "secret", "password", "passwd", "api_key", "apikey", "auth") _MAX_LOG_CHARS = 200 _TOOL_NAME_RE = re.compile(r"^[a-z][a-z0-9_]*$") @@ -1261,6 +1271,78 @@ def wrapper(**kwargs: Any) -> Any: return decorate +def platform( + name: str, + *, + label: str, + check: Callable[[], bool], + validate: Callable[..., Any] | None = None, + required_env: Iterable[str] = (), + install_hint: str = "", + options: Mapping[str, Any] | None = None, + optional_options: Iterable[str] = (), +) -> Callable[[type], type]: + """Mark a ``BasePlatformAdapter`` subclass as a Hermes gateway platform. + + The class is returned unchanged and becomes the ``adapter_factory``; + :func:`register_plugin` validates it against the host and registers it. + ``options`` passes further ``PlatformEntry`` fields through unchanged. + An option named in ``optional_options`` is dropped, with a warning, on a + host whose ``PlatformEntry`` lacks it; any other unknown option fails + registration. Nothing here imports Hermes. + """ + if not isinstance(name, str) or not name or name != name.strip().lower(): + raise ValueError( + f"platform name must be non-empty, stripped and lowercase: {name!r}" + ) + if not isinstance(label, str) or not label.strip(): + raise ValueError("platform label must be a non-empty string") + if not callable(check): + raise TypeError("platform check must be callable") + if validate is not None and not callable(validate): + raise TypeError("platform validate must be callable") + if not isinstance(install_hint, str): + raise TypeError("platform install_hint must be a string") + env_names = list(required_env) + if not all(isinstance(env, str) and env.strip() for env in env_names): + raise ValueError("platform required_env must contain non-empty strings") + passed = dict(options or {}) + for key in passed: + if not isinstance(key, str) or not key.isidentifier(): + raise ValueError(f"platform option names must be identifiers: {key!r}") + if key in _HOST_OWNED_PLATFORM_OPTIONS: + raise ValueError(f"platform option {key!r}: the host owns this field") + if key in _NAMED_PLATFORM_OPTIONS: + raise ValueError( + f"platform option {key!r} duplicates a named argument of @platform" + ) + optional = frozenset(optional_options) + not_passed = sorted(optional - passed.keys()) + if not_passed: + raise ValueError( + "optional_options must name passed options; not passed: " + + ", ".join(not_passed) + ) + spec = { + "name": name, + "label": label.strip(), + "check_fn": check, + "validate_config": validate, + "required_env": tuple(env_names), + "install_hint": install_hint, + "options": passed, + "optional_options": optional, + } + + def decorate(cls: type) -> type: + if not inspect.isclass(cls): + raise TypeError("@platform annotates an adapter class, not a function") + setattr(cls, _PLATFORM_SPEC_ATTR, spec) + return cls + + return decorate + + def _require_string_list(value: Any, field: str) -> None: if not isinstance(value, list) or any( not isinstance(item, str) or not item.strip() for item in value diff --git a/tests/test_platforms.py b/tests/test_platforms.py new file mode 100644 index 0000000..79ade51 --- /dev/null +++ b/tests/test_platforms.py @@ -0,0 +1,118 @@ +from __future__ import annotations + +import subprocess +import sys +import textwrap +import unittest + +import hermes_plugin_kit as hpk + + +def _check() -> bool: + return True + + +class PlatformAnnotationTests(unittest.TestCase): + """Decoration-time behavior: what needs no Hermes host to judge.""" + + def test_annotation_returns_the_same_class_carrying_its_spec(self) -> None: + class WebChat: + pass + + annotated = hpk.platform("web_chat", label="Web Chat", check=_check)(WebChat) + + self.assertIs(annotated, WebChat) + spec = vars(WebChat)["_hpk_platform_spec"] + self.assertEqual(spec["name"], "web_chat") + self.assertEqual(spec["label"], "Web Chat") + self.assertIs(spec["check_fn"], _check) + self.assertEqual(spec["options"], {}) + self.assertNotIn("trusted_inbound", spec["options"]) + + def test_name_not_already_in_host_form_is_rejected(self) -> None: + for bad in ("Web_Chat", " web_chat ", ""): + with self.subTest(name=bad): + with self.assertRaisesRegex(ValueError, "lowercase"): + hpk.platform(bad, label="Web Chat", check=_check) + + def test_empty_label_is_rejected(self) -> None: + with self.assertRaisesRegex(ValueError, "label"): + hpk.platform("web_chat", label=" ", check=_check) + + def test_non_callable_check_is_rejected(self) -> None: + with self.assertRaises(TypeError): + hpk.platform("web_chat", label="Web Chat", check="yes") + + def test_non_callable_validate_is_rejected(self) -> None: + with self.assertRaises(TypeError): + hpk.platform("web_chat", label="Web Chat", check=_check, validate=1) + + def test_annotating_a_function_is_rejected(self) -> None: + decorate = hpk.platform("web_chat", label="Web Chat", check=_check) + with self.assertRaisesRegex(TypeError, "class"): + decorate(_check) + + def test_optional_option_that_was_not_passed_is_rejected(self) -> None: + with self.assertRaisesRegex(ValueError, "display_tier"): + hpk.platform( + "web_chat", label="Web Chat", check=_check, + options={"emoji": "x"}, optional_options={"display_tier"}, + ) + + def test_host_owned_options_are_rejected(self) -> None: + for key in ("source", "plugin_name"): + with self.subTest(option=key): + with self.assertRaisesRegex(ValueError, "host owns"): + hpk.platform( + "web_chat", label="Web Chat", check=_check, + options={key: "x"}, + ) + + def test_option_duplicating_a_named_argument_is_rejected(self) -> None: + with self.assertRaisesRegex(ValueError, "install_hint"): + hpk.platform( + "web_chat", label="Web Chat", check=_check, + options={"install_hint": "pip install x"}, + ) + + def test_non_identifier_option_name_is_rejected(self) -> None: + with self.assertRaisesRegex(ValueError, "identifier"): + hpk.platform( + "web_chat", label="Web Chat", check=_check, + options={"not-a-name": 1}, + ) + + def test_options_are_copied_not_aliased(self) -> None: + options = {"emoji": "x"} + + @hpk.platform("web_chat", label="Web Chat", check=_check, options=options) + class WebChat: + pass + + options["emoji"] = "changed" + self.assertEqual(vars(WebChat)["_hpk_platform_spec"]["options"], {"emoji": "x"}) + + def test_annotating_does_not_import_hermes(self) -> None: + script = textwrap.dedent( + """ + import sys + import hermes_plugin_kit as hpk + + @hpk.platform("web_chat", label="Web Chat", check=lambda: True) + class WebChat: + pass + + leaked = sorted(m for m in sys.modules if m == "gateway" or m.startswith("gateway.")) + assert not leaked, leaked + print("ok") + """ + ) + result = subprocess.run( + [sys.executable, "-c", script], capture_output=True, text=True, check=False + ) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout.strip(), "ok") + + +if __name__ == "__main__": + unittest.main() From d91499b2692e443e267e72cba17c7205637f3907 Mon Sep 17 00:00:00 2001 From: Offending Commit Date: Fri, 13 Nov 2026 09:29:16 -0600 Subject: [PATCH 3/9] feat(platforms): register @platform classes through register_plugin register_plugin now discovers annotated adapter classes, from a module or an iterable, and registers them through ctx.register_platform. A class's spec is read from its own namespace, so an unannotated subclass of an annotated adapter is not mistaken for a second declaration. Every platform check runs before the first registration: duplicate names, the host's platform module and base adapter (a host without them refuses registration), the BasePlatformAdapter subclass check, option names against the host's own PlatformEntry fields (unknown ones fail unless the plugin marked them optional, in which case they are dropped and logged by name), and trusted_inbound on a platform Hermes ships. A host refusal only appears once register_platform returns None, so platforms register first and a refusal disposes the handles this call already holds before raising. That keeps "a bad declaration registers nothing" true for the refusal case as well. The receipt appends platforms and replaced_platforms after the existing fields; every earlier field keeps its position. The recording host gains register_platform, returning a disposable handle, with a refuse_platforms knob for the refusal path. Claude-Session: https://claude.ai/code/session_01B6XeAWUPdrx34tr5dTg5dY --- hermes_plugin_kit/__init__.py | 155 ++++++++++++++++- hermes_plugin_kit/testing.py | 48 +++++ tests/test_kit.py | 3 +- tests/test_platforms.py | 317 ++++++++++++++++++++++++++++++++++ 4 files changed, 519 insertions(+), 4 deletions(-) diff --git a/hermes_plugin_kit/__init__.py b/hermes_plugin_kit/__init__.py index a1b53f8..55b5de8 100644 --- a/hermes_plugin_kit/__init__.py +++ b/hermes_plugin_kit/__init__.py @@ -62,7 +62,7 @@ def register(ctx): import threading import time from contextlib import contextmanager -from dataclasses import dataclass, replace as _dataclass_replace +from dataclasses import dataclass, fields as _dataclass_fields, replace as _dataclass_replace from enum import Enum from pathlib import Path from typing import Any, Callable, Iterable, Iterator, Mapping, Protocol @@ -504,6 +504,8 @@ class RegistrationSummary: capabilities: tuple[str, ...] = () context_engine: str | None = None context_engine_registration: str | None = None + platforms: tuple[str, ...] = () + replaced_platforms: tuple[str, ...] = () class CommandType(str, Enum): @@ -530,7 +532,7 @@ def log_registration_summary( "skills=%s; skipped_optional_skills=%s; memory_providers=%s; " "image_gen_providers=%s; " "video_gen_providers=%s; capabilities=%s; context_engine=%s; " - "context_engine_registration=%s", + "context_engine_registration=%s; platforms=%s; replaced_platforms=%s", clean_plugin_name, ",".join(summary.commands) or "", ",".join(summary.cli_commands) or "", @@ -545,6 +547,8 @@ def log_registration_summary( ",".join(summary.capabilities) or "", summary.context_engine or "", summary.context_engine_registration or "", + ",".join(summary.platforms) or "", + ",".join(summary.replaced_platforms) or "", ) @@ -2523,6 +2527,131 @@ def _validate_generation_providers( return registrar, tuple(validated) +def _platform_spec(obj: Any) -> dict[str, Any] | None: + """The class's own @platform spec; an inherited one is not a declaration.""" + if not inspect.isclass(obj): + return None + return vars(obj).get(_PLATFORM_SPEC_ATTR) + + +def _platform_host() -> tuple[Any, frozenset[str], type]: + """Import the host's platform registry module, entry fields and base adapter. + + Fails closed: a host without them cannot be checked, so nothing registers. + """ + try: + registry_module = importlib.import_module("gateway.platform_registry") + base_module = importlib.import_module("gateway.platforms.base") + except ImportError as exc: + raise RuntimeError( + "hermes-agent platform registry is unavailable; platform registration refused" + ) from exc + try: + entry_fields = frozenset( + field.name for field in _dataclass_fields(registry_module.PlatformEntry) + ) + except (AttributeError, TypeError) as exc: + raise RuntimeError( + "hermes-agent PlatformEntry is missing or not a dataclass; " + "platform registration refused" + ) from exc + base = getattr(base_module, "BasePlatformAdapter", None) + if not inspect.isclass(base): + raise RuntimeError( + "hermes-agent BasePlatformAdapter is unavailable; platform registration refused" + ) + core_ships = getattr(registry_module, "core_ships_platform", None) + if not callable(core_ships): + raise RuntimeError( + "hermes-agent core_ships_platform is unavailable; platform registration refused" + ) + return registry_module, entry_fields, base + + +def _preflight_platforms( + platforms: Mapping[str, type], + log: logging.Logger, +) -> list[dict[str, Any]]: + """Check every declared platform against the host; return register_platform kwargs. + + Pure: nothing here registers, so a failure leaves the host untouched. + """ + registry_module, entry_fields, base = _platform_host() + prepared: list[dict[str, Any]] = [] + for name in sorted(platforms): + cls = platforms[name] + spec = vars(cls)[_PLATFORM_SPEC_ATTR] + if not issubclass(cls, base): + raise TypeError( + f"platform {name!r}: {cls.__qualname__} must subclass Hermes' " + "BasePlatformAdapter" + ) + options = dict(spec["options"]) + unknown = sorted(set(options) - entry_fields) + refused = [key for key in unknown if key not in spec["optional_options"]] + if refused: + raise ValueError( + f"platform {name!r}: this Hermes PlatformEntry has no option " + f"{', '.join(refused)}; upgrade Hermes or list it in optional_options" + ) + for key in unknown: + del options[key] + log.warning( + "hermes_plugin_kit: platform option unsupported by this Hermes, dropped; " + "platform=%s; option=%s", + name, + key, + ) + if options.get("trusted_inbound") and registry_module.core_ships_platform(name): + raise ValueError( + f"platform {name!r}: trusted_inbound cannot be set on a platform " + "Hermes ships; it would waive allowlists and pairing" + ) + prepared.append({ + "name": name, + "label": spec["label"], + "adapter_factory": cls, + "check_fn": spec["check_fn"], + "validate_config": spec["validate_config"], + "required_env": list(spec["required_env"]), + "install_hint": spec["install_hint"], + **options, + }) + return prepared + + +def _register_platforms( + ctx: Any, + prepared: list[dict[str, Any]], + log: logging.Logger, +) -> list[str]: + """Register prepared platforms; on a host refusal, undo this call's earlier ones.""" + handles: list[tuple[str, Any]] = [] + for kwargs in prepared: + name = kwargs["name"] + handle = ctx.register_platform(**kwargs) + if handle is None: + stranded: list[str] = [] + for registered, earlier in reversed(handles): + try: + earlier.dispose() + except Exception as exc: # keep unwinding; the refusal is the error to raise + stranded.append(registered) + log.warning( + "hermes_plugin_kit: platform rollback failed; platform=%s; error_type=%s", + registered, + type(exc).__name__, + ) + left = ( + f"rollback failed for {', '.join(stranded)}" + if stranded + else "nothing from this plugin was left registered" + ) + raise RuntimeError(f"Hermes refused platform {name!r}; {left}") + handles.append((name, handle)) + return [name for name, _ in handles] + + def register_plugin( ctx: Any, module: Any | Iterable[Callable], @@ -2560,6 +2689,8 @@ def register_plugin( "module must be a module, module name, or iterable of decorated callables" ) from exc for declaration in declarations: + if _platform_spec(declaration): + continue if not callable(declaration) or not any( getattr(declaration, attr, None) for attr in ( @@ -2570,7 +2701,8 @@ def register_plugin( ) ): raise TypeError( - "declaration iterables must contain only decorated callables" + "declaration iterables must contain only decorated callables " + "or @platform classes" ) declaration_module_name = next( ( @@ -2606,7 +2738,16 @@ def register_plugin( tools: dict[str, Callable] = {} middlewares: dict[str, Callable] = {} hooks: dict[str, Callable] = {} + platforms: dict[str, type] = {} for obj in declarations: + platform_spec = _platform_spec(obj) + if platform_spec: + existing = platforms.get(platform_spec["name"]) + if existing is not None and existing is not obj: + raise ValueError(f"duplicate platform name: {platform_spec['name']}") + platforms[platform_spec["name"]] = obj + continue + command_spec = getattr(obj, _COMMAND_SPEC_ATTR, None) if command_spec: raw_command_type = command_spec.get("type", CommandType.SLASH.value) @@ -2696,6 +2837,7 @@ def register_plugin( "register_middleware": middlewares, "register_hook": hooks, "register_skill": available_skills, + "register_platform": platforms, } for registrar_name, surfaces in required_registrars.items(): if surfaces and not callable(getattr(ctx, registrar_name, None)): @@ -2760,6 +2902,12 @@ def register_plugin( "context_engine must be an instance of agent.context_engine.ContextEngine" ) + prepared_platforms = _preflight_platforms(platforms, log) if platforms else [] + + # Platforms go first: a host refusal surfaces only at registration, and the + # rollback can undo platforms but not the surfaces registered after them. + registered_platforms = _register_platforms(ctx, prepared_platforms, log) + context_engine_registration = None if context_engine_registrar is not None: registration_result = context_engine_registrar(context_engine) @@ -2898,6 +3046,7 @@ def register_plugin( capabilities=resolved_capabilities, context_engine=context_engine_name, context_engine_registration=context_engine_registration, + platforms=tuple(registered_platforms), ) log_registration_summary(log, resolved_plugin_name, summary) return summary diff --git a/hermes_plugin_kit/testing.py b/hermes_plugin_kit/testing.py index 8879a68..5ef7a9a 100644 --- a/hermes_plugin_kit/testing.py +++ b/hermes_plugin_kit/testing.py @@ -72,6 +72,8 @@ "capabilities", "context_engine", "context_engine_registration", + "platforms", + "replaced_platforms", ) #: The hermes-agent revision this kit's contract lanes are pinned to. @@ -107,9 +109,25 @@ "register_image_gen_provider", "register_video_gen_provider", "register_context_engine", + "register_platform", ) +class _RecordedRegistration: + """What the recording host's ``register_platform`` returns: a disposable handle, + shaped like the host's ``PluginRegistration`` (``active`` and ``dispose()``).""" + + def __init__(self, release: Callable[[], None]) -> None: + self._release = release + self.active = True + + def dispose(self) -> None: + if not self.active: + return + self.active = False + self._release() + + @dataclass(frozen=True) class Drift: """One registrar whose recorded call no longer fits the host's signature.""" @@ -219,6 +237,9 @@ class RecordingPluginContext: 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. + - ``refuse_platforms`` -- platform names ``register_platform`` refuses by + returning ``None``, the way the host reports a registration that did not + take. Accepted platforms return a handle whose ``dispose()`` removes them. """ def __init__( @@ -232,6 +253,7 @@ def __init__( missing_registrars: Iterable[str] = (), strict_against: type | None = None, context_engine_result: bool = True, + refuse_platforms: Iterable[str] = (), ) -> None: unknown = sorted(set(missing_registrars) - set(_ALL_REGISTRARS)) if unknown: @@ -253,8 +275,10 @@ def __init__( self.image_gen_providers: list[Any] = [] self.video_gen_providers: list[Any] = [] self.context_engines: list[Any] = [] + self.platforms: list[dict[str, Any]] = [] self.context_engine_result = context_engine_result + self.refuse_platforms = frozenset(refuse_platforms) self.subagent_lifecycle = SimpleNamespace( launch=lambda request: request, status=lambda handle: handle, @@ -371,6 +395,29 @@ def register_context_engine(engine): self.context_engines.append(engine) return self.context_engine_result + def register_platform( + name, label, adapter_factory, check_fn, validate_config=None, + required_env=None, install_hint="", **entry_kwargs, + ): + kwargs = dict( + name=name, label=label, adapter_factory=adapter_factory, + check_fn=check_fn, validate_config=validate_config, + required_env=required_env, install_hint=install_hint, **entry_kwargs, + ) + self._record("register_platform", (), kwargs) + if name in self.refuse_platforms: + return None + self.platforms.append(kwargs) + + def release() -> None: + # By identity: two equal option dicts are still two registrations. + for i, registered in enumerate(self.platforms): + if registered is kwargs: + del self.platforms[i] + return + + return _RecordedRegistration(release) + 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. @@ -393,6 +440,7 @@ def _pick_skill_registrar() -> Callable[..., Any]: "register_image_gen_provider": register_image_gen_provider, "register_video_gen_provider": register_video_gen_provider, "register_context_engine": register_context_engine, + "register_platform": register_platform, } for registrar, impl in implementations.items(): diff --git a/tests/test_kit.py b/tests/test_kit.py index 156be60..18ea8c0 100644 --- a/tests/test_kit.py +++ b/tests/test_kit.py @@ -1755,7 +1755,8 @@ def test_logs_one_stable_registration_receipt_with_actual_names(self) -> None: "memory_providers=; " "image_gen_providers=; video_gen_providers=; " "capabilities=image,video; context_engine=; " - "context_engine_registration=", + "context_engine_registration=; " + "platforms=; replaced_platforms=", ) def test_register_plugin_reports_selected_capabilities(self) -> None: diff --git a/tests/test_platforms.py b/tests/test_platforms.py index 79ade51..2be2a3c 100644 --- a/tests/test_platforms.py +++ b/tests/test_platforms.py @@ -1,17 +1,147 @@ from __future__ import annotations +import dataclasses +import logging import subprocess import sys import textwrap +import types import unittest +from contextlib import contextmanager +from unittest.mock import patch import hermes_plugin_kit as hpk +from hermes_plugin_kit.testing import RecordingPluginContext, receipt_fields + +# PlatformEntry fields every pinned Hermes has, mirroring register_platform's +# named parameters plus the two fields the host fills itself. +_BASE_ENTRY_FIELDS = ( + "name", "label", "adapter_factory", "check_fn", "validate_config", + "required_env", "install_hint", "source", "plugin_name", +) def _check() -> bool: return True +class _FakeRegistry: + """Stand-in for the host's PlatformRegistry: concrete and deferred state.""" + + def __init__(self) -> None: + self.entries: dict[str, object] = {} + self.deferred: dict[str, object] = {} + + @staticmethod + def current_scope_key() -> str: + return "" + + def is_registered(self, name: str) -> bool: + return name in self.entries or name in self.deferred + + def snapshot_registration(self, name: str, *, scope=None): + return self.entries.get(name), self.deferred.get(name) + + +@contextmanager +def fake_platform_host( + *, + extra_fields=("emoji", "allowed_users_env", "trusted_inbound"), + core=("telegram",), +): + """Install a stand-in for the host's platform registry and base adapter.""" + gateway = types.ModuleType("gateway") + registry_module = types.ModuleType("gateway.platform_registry") + platforms_package = types.ModuleType("gateway.platforms") + base_module = types.ModuleType("gateway.platforms.base") + + class BasePlatformAdapter: + def __init__(self, config, platform=None) -> None: + self.config = config + + entry_type = dataclasses.make_dataclass( + "PlatformEntry", + [(field, object, None) for field in (*_BASE_ENTRY_FIELDS, *extra_fields)], + ) + registry = _FakeRegistry() + registry_module.PlatformEntry = entry_type + registry_module.PlatformRegistry = _FakeRegistry + registry_module.platform_registry = registry + registry_module.core_ships_platform = lambda name: name in core + base_module.BasePlatformAdapter = BasePlatformAdapter + gateway.platform_registry = registry_module + gateway.platforms = platforms_package + platforms_package.base = base_module + with patch.dict( + sys.modules, + { + "gateway": gateway, + "gateway.platform_registry": registry_module, + "gateway.platforms": platforms_package, + "gateway.platforms.base": base_module, + }, + ): + yield types.SimpleNamespace( + BasePlatformAdapter=BasePlatformAdapter, + registry=registry, + module=registry_module, + entry_type=entry_type, + ) + + +def _module(**attrs) -> types.ModuleType: + module = types.ModuleType("sample_plugin") + for name, value in attrs.items(): + setattr(module, name, value) + return module + + +@hpk.tool(toolset="sample", params={"q": hpk.str_arg("query", required=True)}) +def sample_read_thread(args, **kwargs): + """Read a thread.""" + return {"ok": True} + + +def _register(ctx, module, **kwargs): + """Run register_plugin and return (summary, receipt message).""" + logger = logging.getLogger("tests.platforms") + with RecordingCaptureLogs(logger) as cap: + summary = hpk.register_plugin(ctx, module, logger=logger, **kwargs) + return summary, cap.message + + +class RecordingCaptureLogs: + """Capture the one receipt line, without assertLogs' failure on silence.""" + + def __init__(self, logger: logging.Logger) -> None: + self.logger = logger + self.records: list[logging.LogRecord] = [] + + def __enter__(self): + handler = logging.Handler() + handler.emit = self.records.append + self._handler = handler + self._level = self.logger.level + self.logger.addHandler(handler) + self.logger.setLevel(logging.DEBUG) + return self + + def __exit__(self, *exc) -> None: + self.logger.removeHandler(self._handler) + self.logger.setLevel(self._level) + + @property + def message(self) -> str: + receipts = [ + r.getMessage() for r in self.records + if "registered plugin lifecycle" in r.getMessage() + ] + return receipts[-1] if receipts else "" + + def warnings(self) -> list[str]: + return [r.getMessage() for r in self.records if r.levelno == logging.WARNING] + + class PlatformAnnotationTests(unittest.TestCase): """Decoration-time behavior: what needs no Hermes host to judge.""" @@ -114,5 +244,192 @@ class WebChat: self.assertEqual(result.stdout.strip(), "ok") +class PlatformRegistrationTests(unittest.TestCase): + """register_plugin discovers, checks and registers annotated platforms.""" + + def _platform(self, host, name="web_chat", base=None, **kwargs): + @hpk.platform(name, label="Web Chat", check=_check, **kwargs) + class Adapter(base or host.BasePlatformAdapter): + pass + + return Adapter + + def test_registers_a_platform_alongside_a_tool(self) -> None: + with fake_platform_host() as host: + adapter = self._platform(host, options={"emoji": "💬"}) + ctx = RecordingPluginContext() + summary, receipt = _register( + ctx, _module(WebChat=adapter, sample_read_thread=sample_read_thread) + ) + + self.assertEqual([t["name"] for t in ctx.tools], ["sample_read_thread"]) + self.assertEqual(len(ctx.platforms), 1) + registered = ctx.platforms[0] + self.assertEqual(registered["name"], "web_chat") + self.assertEqual(registered["label"], "Web Chat") + self.assertIs(registered["adapter_factory"], adapter) + self.assertIs(registered["check_fn"], _check) + self.assertEqual(registered["emoji"], "💬") + self.assertNotIn("trusted_inbound", registered) + self.assertEqual(summary.platforms, ("web_chat",)) + self.assertEqual(summary.replaced_platforms, ()) + self.assertTrue( + receipt.endswith("platforms=web_chat; replaced_platforms="), receipt + ) + + def test_two_declarations_sharing_a_name_register_nothing(self) -> None: + with fake_platform_host() as host: + first = self._platform(host) + second = self._platform(host) + ctx = RecordingPluginContext() + with self.assertRaisesRegex(ValueError, "web_chat"): + _register( + ctx, + _module(A=first, B=second, sample_read_thread=sample_read_thread), + ) + + self.assertEqual(ctx.calls, []) + + def test_unknown_option_fails_before_anything_registers(self) -> None: + with fake_platform_host() as host: + adapter = self._platform(host, options={"display_tier": "minimal"}) + ctx = RecordingPluginContext() + with self.assertRaisesRegex(ValueError, "display_tier"): + _register( + ctx, _module(WebChat=adapter, sample_read_thread=sample_read_thread) + ) + + self.assertEqual(ctx.calls, []) + + def test_optional_unknown_option_is_dropped_and_named(self) -> None: + with fake_platform_host() as host: + adapter = self._platform( + host, + options={"display_tier": "minimal", "emoji": "💬"}, + optional_options={"display_tier"}, + ) + ctx = RecordingPluginContext() + logger = logging.getLogger("tests.platforms") + with RecordingCaptureLogs(logger) as cap: + hpk.register_plugin(ctx, _module(WebChat=adapter), logger=logger) + + self.assertNotIn("display_tier", ctx.platforms[0]) + self.assertEqual(ctx.platforms[0]["emoji"], "💬") + self.assertTrue(any("display_tier" in w for w in cap.warnings()), cap.warnings()) + + def test_class_not_subclassing_the_host_adapter_is_rejected(self) -> None: + with fake_platform_host() as host: + adapter = self._platform(host, base=object) + ctx = RecordingPluginContext() + with self.assertRaisesRegex(TypeError, "Adapter"): + _register( + ctx, _module(WebChat=adapter, sample_read_thread=sample_read_thread) + ) + + self.assertEqual(ctx.calls, []) + + def test_trusted_inbound_on_a_core_platform_fails_in_preflight(self) -> None: + with fake_platform_host() as host: + adapter = self._platform( + host, name="telegram", options={"trusted_inbound": True} + ) + ctx = RecordingPluginContext(config={"replace_platforms": ["telegram"]}) + with self.assertRaisesRegex(ValueError, "trusted_inbound"): + _register( + ctx, _module(Tg=adapter, sample_read_thread=sample_read_thread) + ) + + self.assertEqual(ctx.calls, []) + + def test_host_refusal_raises_naming_the_platform(self) -> None: + with fake_platform_host() as host: + adapter = self._platform(host) + ctx = RecordingPluginContext(refuse_platforms=("web_chat",)) + with self.assertRaisesRegex(RuntimeError, "web_chat"): + _register(ctx, _module(WebChat=adapter)) + + def test_host_refusal_rolls_back_platforms_already_registered(self) -> None: + with fake_platform_host() as host: + first = self._platform(host, name="aaa_chat") + second = self._platform(host, name="zzz_chat") + ctx = RecordingPluginContext(refuse_platforms=("zzz_chat",)) + with self.assertRaisesRegex(RuntimeError, "zzz_chat"): + _register( + ctx, + _module(A=first, Z=second, sample_read_thread=sample_read_thread), + ) + + registered = [name for name, _, kwargs in ctx.calls] + self.assertEqual(registered, ["register_platform", "register_platform"]) + self.assertEqual(ctx.platforms, []) + self.assertEqual(ctx.tools, []) + + def test_context_without_register_platform(self) -> None: + with fake_platform_host() as host: + adapter = self._platform(host) + ctx = RecordingPluginContext(missing_registrars=("register_platform",)) + with self.assertRaisesRegex(RuntimeError, "register_platform"): + _register(ctx, _module(WebChat=adapter)) + summary, _ = _register(ctx, _module(sample_read_thread=sample_read_thread)) + + self.assertEqual(summary.tools, ("sample_read_thread",)) + + def test_missing_host_platform_module_refuses_registration(self) -> None: + @hpk.platform("web_chat", label="Web Chat", check=_check) + class Adapter: + pass + + ctx = RecordingPluginContext() + with patch.dict(sys.modules, {"gateway": None}): + with self.assertRaisesRegex(RuntimeError, "platform"): + _register( + ctx, _module(WebChat=Adapter, sample_read_thread=sample_read_thread) + ) + + self.assertEqual(ctx.calls, []) + + def test_iterable_holding_an_annotated_class_registers_it(self) -> None: + with fake_platform_host() as host: + adapter = self._platform(host) + ctx = RecordingPluginContext() + summary, _ = _register(ctx, [adapter, sample_read_thread]) + + self.assertEqual(summary.platforms, ("web_chat",)) + self.assertEqual(summary.tools, ("sample_read_thread",)) + + def test_unannotated_subclass_is_not_a_second_declaration(self) -> None: + with fake_platform_host() as host: + adapter = self._platform(host) + + class Variant(adapter): + pass + + ctx = RecordingPluginContext() + summary, _ = _register(ctx, _module(WebChat=adapter, Variant=Variant)) + + self.assertEqual(summary.platforms, ("web_chat",)) + self.assertEqual(len(ctx.platforms), 1) + self.assertIs(ctx.platforms[0]["adapter_factory"], adapter) + + def test_receipt_without_platforms_keeps_every_old_field_in_place(self) -> None: + ctx = RecordingPluginContext() + _, receipt = _register(ctx, _module(sample_read_thread=sample_read_thread)) + + fields = list(receipt_fields(receipt)) + self.assertEqual( + fields, + [ + "commands", "cli_commands", "tools", "middlewares", "hooks", + "skills", "skipped_optional_skills", "memory_providers", + "image_gen_providers", "video_gen_providers", "capabilities", + "context_engine", "context_engine_registration", + "platforms", "replaced_platforms", + ], + ) + self.assertTrue( + receipt.endswith("platforms=; replaced_platforms="), receipt + ) + + if __name__ == "__main__": unittest.main() From bd2f6df53d312b16fc4db99abc935b85f95f70b9 Mon Sep 17 00:00:00 2001 From: Offending Commit Date: Fri, 13 Nov 2026 09:31:41 -0600 Subject: [PATCH 4/9] feat(platforms): refuse to replace an existing platform without an operator override The platform registry is last-writer-wins and logs a replacement at INFO, so a plugin naming `telegram` would silently swap out the real adapter. Preflight now refuses any platform name that Hermes ships or that is already registered, unless the operator lists it under plugins..replace_platforms. The error names the platform, its current owner where the registry exposes one, and that exact key. A permitted replacement is named in the receipt's replaced_platforms. Existence is read without resolving deferred loaders, which would import a bundled platform's SDK: core_ships_platform, is_registered, and snapshot_registration in the registry's current scope. A host missing any of these fails closed and names every missing read. A reload of this plugin's own platform (the existing entry's plugin_name is this plugin's manifest name) registers without the override, but only for names Hermes does not ship: a core platform needs the override whoever registered it last. Claude-Session: https://claude.ai/code/session_01B6XeAWUPdrx34tr5dTg5dY --- hermes_plugin_kit/__init__.py | 102 +++++++++++++++++++++--- tests/test_platforms.py | 142 ++++++++++++++++++++++++++++++++++ 2 files changed, 234 insertions(+), 10 deletions(-) diff --git a/hermes_plugin_kit/__init__.py b/hermes_plugin_kit/__init__.py index 55b5de8..9a0f1a9 100644 --- a/hermes_plugin_kit/__init__.py +++ b/hermes_plugin_kit/__init__.py @@ -142,6 +142,11 @@ def register(ctx): # its own provenance. _HOST_OWNED_PLATFORM_OPTIONS = frozenset({"source", "plugin_name"}) # register_platform parameters the annotation already names. +# Host reads the replacement guard needs; checked together so a host missing +# any of them names every gap at once. +_PLATFORM_EXISTENCE_SYMBOLS = ( + "core_ships_platform", "is_registered", "snapshot_registration", "current_scope_key", +) _NAMED_PLATFORM_OPTIONS = frozenset({ "name", "label", "adapter_factory", "check_fn", "validate_config", "required_env", "install_hint", @@ -2560,24 +2565,76 @@ def _platform_host() -> tuple[Any, frozenset[str], type]: raise RuntimeError( "hermes-agent BasePlatformAdapter is unavailable; platform registration refused" ) - core_ships = getattr(registry_module, "core_ships_platform", None) - if not callable(core_ships): + return registry_module, entry_fields, base + + +def _platform_existence_reads(registry_module: Any) -> dict[str, Callable[..., Any]]: + """The host reads that tell whether a platform name already exists. + + None of them resolves a deferred loader: ``PlatformRegistry.get`` would import + a bundled platform's SDK, so the guard never calls it. A host missing any of + them fails closed rather than skipping the guard. + """ + registry = getattr(registry_module, "platform_registry", None) + reads = { + symbol: getattr( + registry_module if symbol == "core_ships_platform" else registry, + symbol, + None, + ) + for symbol in _PLATFORM_EXISTENCE_SYMBOLS + } + missing = [symbol for symbol, read in reads.items() if not callable(read)] + if missing: raise RuntimeError( - "hermes-agent core_ships_platform is unavailable; platform registration refused" + "hermes-agent platform registry lacks " + f"{', '.join(missing)}; cannot check for an existing platform, " + "so platform registration is refused" ) - return registry_module, entry_fields, base + return reads + + +def _replace_platforms_setting(ctx: Any, plugin_name: str) -> frozenset[str]: + """The operator's ``plugins..replace_platforms`` list.""" + key = f"plugins.{plugin_name}.replace_platforms" + value = load_plugin_config(ctx, plugin_name).get("replace_platforms", []) + if not isinstance(value, list) or not all(isinstance(item, str) for item in value): + raise ValueError(f"{key} must be a list of platform names") + return frozenset(item.strip().lower() for item in value) + + +def _describe_platform_owner(core: bool, entry: Any, loader: Any) -> str: + owners = [] + if core: + owners.append("shipped by Hermes") + owner_plugin = getattr(entry, "plugin_name", None) + if owner_plugin: + owners.append(f"registered by plugin {owner_plugin!r}") + elif entry is not None: + owners.append(f"registered ({getattr(entry, 'source', 'unknown source')})") + if loader is not None: + owners.append("pending as a deferred platform") + return "; ".join(owners) or "already registered" def _preflight_platforms( + ctx: Any, platforms: Mapping[str, type], + plugin_name: str, log: logging.Logger, -) -> list[dict[str, Any]]: - """Check every declared platform against the host; return register_platform kwargs. +) -> tuple[list[dict[str, Any]], list[str]]: + """Check every declared platform against the host. - Pure: nothing here registers, so a failure leaves the host untouched. + Returns the ``register_platform`` keyword arguments and the names this + registration replaces. Pure: nothing here registers, so a failure leaves + the host untouched. """ registry_module, entry_fields, base = _platform_host() + reads = _platform_existence_reads(registry_module) + allowed_replacements = _replace_platforms_setting(ctx, plugin_name) + manifest_name = getattr(getattr(ctx, "manifest", None), "name", None) prepared: list[dict[str, Any]] = [] + replaced: list[str] = [] for name in sorted(platforms): cls = platforms[name] spec = vars(cls)[_PLATFORM_SPEC_ATTR] @@ -2602,11 +2659,31 @@ def _preflight_platforms( name, key, ) - if options.get("trusted_inbound") and registry_module.core_ships_platform(name): + core = bool(reads["core_ships_platform"](name)) + if options.get("trusted_inbound") and core: raise ValueError( f"platform {name!r}: trusted_inbound cannot be set on a platform " "Hermes ships; it would waive allowlists and pairing" ) + if core or reads["is_registered"](name): + entry, loader = reads["snapshot_registration"]( + name, scope=reads["current_scope_key"]() + ) + own_reload = ( + not core + and entry is not None + and manifest_name is not None + and getattr(entry, "plugin_name", None) == manifest_name + ) + if not own_reload: + if name not in allowed_replacements: + raise ValueError( + f"platform {name!r} already exists " + f"({_describe_platform_owner(core, entry, loader)}). " + f"To replace it, the operator must list it in " + f"plugins.{plugin_name}.replace_platforms" + ) + replaced.append(name) prepared.append({ "name": name, "label": spec["label"], @@ -2617,7 +2694,7 @@ def _preflight_platforms( "install_hint": spec["install_hint"], **options, }) - return prepared + return prepared, replaced def _register_platforms( @@ -2902,7 +2979,11 @@ def register_plugin( "context_engine must be an instance of agent.context_engine.ContextEngine" ) - prepared_platforms = _preflight_platforms(platforms, log) if platforms else [] + prepared_platforms, replaced_platforms = ( + _preflight_platforms(ctx, platforms, resolved_plugin_name, log) + if platforms + else ([], []) + ) # Platforms go first: a host refusal surfaces only at registration, and the # rollback can undo platforms but not the surfaces registered after them. @@ -3047,6 +3128,7 @@ def register_plugin( context_engine=context_engine_name, context_engine_registration=context_engine_registration, platforms=tuple(registered_platforms), + replaced_platforms=tuple(replaced_platforms), ) log_registration_summary(log, resolved_plugin_name, summary) return summary diff --git a/tests/test_platforms.py b/tests/test_platforms.py index 2be2a3c..583a8b1 100644 --- a/tests/test_platforms.py +++ b/tests/test_platforms.py @@ -42,6 +42,22 @@ def is_registered(self, name: str) -> bool: def snapshot_registration(self, name: str, *, scope=None): return self.entries.get(name), self.deferred.get(name) + def get(self, name: str): + # Like the host, resolving a deferred name runs its loader, which + # imports the platform's module. Preflight must never come here. + loader = self.deferred.pop(name, None) + if loader is not None: + self.entries[name] = loader() + return self.entries.get(name) + + +_BUNDLED_MODULE = "gateway.platforms.fake_bundled" + + +def _deferred_loader(): + sys.modules[_BUNDLED_MODULE] = types.ModuleType(_BUNDLED_MODULE) + return types.SimpleNamespace(source="bundled", plugin_name="fake_bundled") + @contextmanager def fake_platform_host( @@ -431,5 +447,131 @@ def test_receipt_without_platforms_keeps_every_old_field_in_place(self) -> None: ) +class PlatformReplacementGuardTests(unittest.TestCase): + """An existing platform is replaced only when the operator listed it.""" + + def _module_with(self, host, name): + @hpk.platform(name, label="Chat", check=_check) + class Adapter(host.BasePlatformAdapter): + pass + + return _module(Adapter=Adapter, sample_read_thread=sample_read_thread) + + def assertNothingRegistered(self, ctx) -> None: + self.assertEqual(ctx.calls, []) + + def test_core_platform_without_override_fails_naming_the_key(self) -> None: + with fake_platform_host() as host: + ctx = RecordingPluginContext() + with self.assertRaises(ValueError) as caught: + _register(ctx, self._module_with(host, "telegram")) + + message = str(caught.exception) + self.assertIn("telegram", message) + self.assertIn("plugins.test-plugin.replace_platforms", message) + self.assertNothingRegistered(ctx) + + def test_core_platform_listed_in_override_is_replaced(self) -> None: + with fake_platform_host() as host: + ctx = RecordingPluginContext(config={"replace_platforms": ["telegram"]}) + summary, receipt = _register(ctx, self._module_with(host, "telegram")) + + self.assertEqual(summary.platforms, ("telegram",)) + self.assertEqual(summary.replaced_platforms, ("telegram",)) + self.assertEqual(receipt_fields(receipt)["replaced_platforms"], ("telegram",)) + + def test_platform_registered_by_another_plugin_names_the_owner(self) -> None: + with fake_platform_host() as host: + host.registry.entries["web_chat"] = types.SimpleNamespace( + source="plugin", plugin_name="other-plugin" + ) + ctx = RecordingPluginContext() + with self.assertRaisesRegex(ValueError, "other-plugin"): + _register(ctx, self._module_with(host, "web_chat")) + + self.assertNothingRegistered(ctx) + + def test_deferred_platform_counts_as_existing_without_being_imported(self) -> None: + with fake_platform_host() as host: + host.registry.deferred["irc_like"] = _deferred_loader + ctx = RecordingPluginContext() + with self.assertRaisesRegex(ValueError, "irc_like"): + _register(ctx, self._module_with(host, "irc_like")) + imported = _BUNDLED_MODULE in sys.modules + + self.assertFalse(imported) + self.assertNothingRegistered(ctx) + + def test_deferred_platform_listed_in_override_is_replaced_without_import(self) -> None: + with fake_platform_host() as host: + host.registry.deferred["irc_like"] = _deferred_loader + ctx = RecordingPluginContext(config={"replace_platforms": ["irc_like"]}) + summary, _ = _register(ctx, self._module_with(host, "irc_like")) + imported = _BUNDLED_MODULE in sys.modules + + self.assertFalse(imported) + self.assertEqual(summary.replaced_platforms, ("irc_like",)) + + def test_reload_of_this_plugins_own_platform_needs_no_override(self) -> None: + with fake_platform_host() as host: + host.registry.entries["web_chat"] = types.SimpleNamespace( + source="plugin", plugin_name="test-plugin" + ) + ctx = RecordingPluginContext() + summary, _ = _register(ctx, self._module_with(host, "web_chat")) + + self.assertEqual(summary.platforms, ("web_chat",)) + self.assertEqual(summary.replaced_platforms, ()) + + def test_reload_exemption_never_covers_a_core_platform(self) -> None: + with fake_platform_host() as host: + host.registry.entries["telegram"] = types.SimpleNamespace( + source="plugin", plugin_name="test-plugin" + ) + ctx = RecordingPluginContext() + with self.assertRaisesRegex(ValueError, "replace_platforms"): + _register(ctx, self._module_with(host, "telegram")) + + self.assertNothingRegistered(ctx) + + def test_override_naming_another_platform_changes_nothing(self) -> None: + with fake_platform_host() as host: + ctx = RecordingPluginContext(config={"replace_platforms": ["telegram"]}) + summary, receipt = _register(ctx, self._module_with(host, "web_chat")) + + self.assertEqual(summary.platforms, ("web_chat",)) + self.assertEqual(receipt_fields(receipt)["replaced_platforms"], ()) + + def test_override_that_is_not_a_list_fails_naming_the_key(self) -> None: + with fake_platform_host() as host: + ctx = RecordingPluginContext(config={"replace_platforms": "telegram"}) + with self.assertRaisesRegex(ValueError, "plugins.test-plugin.replace_platforms"): + _register(ctx, self._module_with(host, "telegram")) + + self.assertNothingRegistered(ctx) + + def test_host_missing_existence_symbols_fails_closed(self) -> None: + symbols = hpk._PLATFORM_EXISTENCE_SYMBOLS + cases = [(symbol,) for symbol in symbols] + [tuple(symbols)] + for absent in cases: + with self.subTest(absent=absent): + with fake_platform_host() as host: + for symbol in absent: + if symbol == "core_ships_platform": + host.module.core_ships_platform = None + else: + setattr(host.registry, symbol, None) + ctx = RecordingPluginContext() + with self.assertRaises(RuntimeError) as caught: + _register(ctx, self._module_with(host, "web_chat")) + + message = str(caught.exception) + for symbol in absent: + self.assertIn(symbol, message) + for present in set(symbols) - set(absent): + self.assertNotIn(present, message) + self.assertNothingRegistered(ctx) + + if __name__ == "__main__": unittest.main() From 7dbe1d6c150e7e2d499afbf9648b1e699630e1bb Mon Sep 17 00:00:00 2001 From: Offending Commit Date: Fri, 13 Nov 2026 09:35:28 -0600 Subject: [PATCH 5/9] feat(testing): check recorded platform options against the host's PlatformEntry register_platform takes its options as **entry_kwargs, so replaying a recorded call against its signature accepts any option name: a Hermes release that drops or renames a PlatformEntry field would replay clean while the plugin fails at registration. check_against_host gains an optional platform_entry_fields keyword and reports each recorded option the host's PlatformEntry lacks as drift naming the option. ResolvedHost.platform_entry_fields() reads those names from the checkout. A recorded platform call replayed without them is reported unchecked, never clean, and the report still lists any signature drift it did find. Callers that record no platform call see no change. The OpenSpec change check-platform-option-drift adds both scenarios to the "Recorded calls replay against the real host signatures" requirement. Claude-Session: https://claude.ai/code/session_01B6XeAWUPdrx34tr5dTg5dY --- hermes_plugin_kit/testing.py | 58 +++++++- .../.openspec.yaml | 2 + .../check-platform-option-drift/proposal.md | 32 ++++ .../specs/plugin-test-harness/spec.md | 52 +++++++ .../check-platform-option-drift/tasks.md | 16 ++ tests/test_testing_harness.py | 139 ++++++++++++++++++ 6 files changed, 293 insertions(+), 6 deletions(-) create mode 100644 openspec/changes/check-platform-option-drift/.openspec.yaml create mode 100644 openspec/changes/check-platform-option-drift/proposal.md create mode 100644 openspec/changes/check-platform-option-drift/specs/plugin-test-harness/spec.md create mode 100644 openspec/changes/check-platform-option-drift/tasks.md diff --git a/hermes_plugin_kit/testing.py b/hermes_plugin_kit/testing.py index 5ef7a9a..b409f61 100644 --- a/hermes_plugin_kit/testing.py +++ b/hermes_plugin_kit/testing.py @@ -28,6 +28,7 @@ from __future__ import annotations +import dataclasses import inspect import os import subprocess @@ -160,11 +161,10 @@ def __bool__(self) -> bool: # pragma: no cover - trivial return self.clean def __str__(self) -> str: + found = "; ".join(str(d) for d in self.drifts) if not self.checked: - return f"unchecked: {self.detail}" - if not self.drifts: - return "clean" - return "; ".join(str(d) for d in self.drifts) + return f"unchecked: {self.detail}" + (f"; drift found: {found}" if found else "") + return found or "clean" def _positional_names(target: Callable[..., Any]) -> list[str] | None: @@ -449,12 +449,22 @@ def _pick_skill_registrar() -> Callable[..., Any]: # -- checking ------------------------------------------------------------ - def check_against_host(self, host: type | None) -> DriftReport: + def check_against_host( + self, + host: type | None, + *, + platform_entry_fields: Iterable[str] | None = 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. + + ``register_platform`` takes its options as ``**entry_kwargs``, so binding + accepts any option name. Pass the host's ``PlatformEntry`` field names + (:meth:`ResolvedHost.platform_entry_fields`) to check them too; a + recorded platform call without them leaves the report unchecked. """ if host is None: return DriftReport( @@ -477,7 +487,25 @@ def check_against_host(self, host: type | None) -> DriftReport: detail = _bind(target, args, kwargs, _POSITIONAL_PARAMS.get(registrar, ())) if detail is not None: drifts.append(Drift(registrar, detail)) - + if registrar == "register_platform" and platform_entry_fields is not None: + gone = sorted(set(kwargs) - set(platform_entry_fields)) + if gone: + drifts.append( + Drift(registrar, f"host PlatformEntry has no option: {', '.join(gone)}") + ) + + if platform_entry_fields is None and any( + registrar == "register_platform" for registrar, _, _ in self.calls + ): + return DriftReport( + checked=False, + drifts=tuple(drifts), + detail=( + "register_platform options were not checked: signature binding accepts " + "any option name, so pass platform_entry_fields " + "(ResolvedHost.platform_entry_fields()) to check them" + ), + ) return DriftReport(checked=True, drifts=tuple(drifts)) @@ -633,6 +661,24 @@ def plugin_context_class(self) -> type | None: return None return PluginContext + def platform_entry_fields(self) -> frozenset[str] | None: + """``PlatformEntry``'s field names from this checkout, or ``None``. + + ``None`` (no checkout, or one without ``gateway/platform_registry.py``) + leaves a recorded ``register_platform`` call unchecked, never clean. + """ + if self.path is None or not (self.path / "gateway" / "platform_registry.py").exists(): + return None + root = str(self.path) + if root not in sys.path: + sys.path.insert(0, root) + try: + from gateway.platform_registry import PlatformEntry # type: ignore + + return frozenset(field.name for field in dataclasses.fields(PlatformEntry)) + except Exception: # pragma: no cover - depends on the checkout's shape + return None + def _git(args: list[str], *, cwd: Path | None = None, timeout: int) -> str: result = subprocess.run( diff --git a/openspec/changes/check-platform-option-drift/.openspec.yaml b/openspec/changes/check-platform-option-drift/.openspec.yaml new file mode 100644 index 0000000..22ca07d --- /dev/null +++ b/openspec/changes/check-platform-option-drift/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-13 diff --git a/openspec/changes/check-platform-option-drift/proposal.md b/openspec/changes/check-platform-option-drift/proposal.md new file mode 100644 index 0000000..533f602 --- /dev/null +++ b/openspec/changes/check-platform-option-drift/proposal.md @@ -0,0 +1,32 @@ +## Why + +The kit is gaining `@platform`, which registers gateway platforms through +`PluginContext.register_platform`. That registrar takes its options as +`**entry_kwargs`, so replaying a recorded call against its signature accepts +any option name. A Hermes release that removes or renames a `PlatformEntry` +field would leave the replay reporting clean while the plugin breaks at +registration. `PlatformEntry` went from 26 fields to 46 between two pinned +Hermes revisions, so this is the drift most likely to happen. + +## What Changes + +- The recording context records `register_platform` calls. +- The drift replay also compares each recorded platform option name with the + host's `PlatformEntry` fields, read from the checkout, and reports a missing + one as drift naming the option. +- A recorded platform call replayed without those field names is reported as + not checked, never as clean. + +## Capabilities + +### Modified Capabilities + +- `plugin-test-harness`: the replay requirement gains the platform-option + scenarios. + +## Impact + +`hermes_plugin_kit/testing.py` (`RecordingPluginContext.check_against_host` +gains an optional `platform_entry_fields` keyword; `ResolvedHost` gains +`platform_entry_fields()`). Existing callers that pass only the host class keep +their behavior unless they record a platform call. diff --git a/openspec/changes/check-platform-option-drift/specs/plugin-test-harness/spec.md b/openspec/changes/check-platform-option-drift/specs/plugin-test-harness/spec.md new file mode 100644 index 0000000..6c2346d --- /dev/null +++ b/openspec/changes/check-platform-option-drift/specs/plugin-test-harness/spec.md @@ -0,0 +1,52 @@ +## MODIFIED Requirements + +### 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 + +#### Scenario: Host removes a platform option + +- **WHEN** a plugin registers a platform with an option the host's + `PlatformEntry` no longer has, and the replay is given the host's + `PlatformEntry` field names +- **THEN** the replay fails and names `register_platform` and the missing + option, even though the call still binds to the registrar's signature + +#### Scenario: Platform options cannot be checked + +- **WHEN** a plugin registers a platform and the replay is not given the host's + `PlatformEntry` field names +- **THEN** the replay reports the run as not checked rather than clean, and + still names any signature drift it found diff --git a/openspec/changes/check-platform-option-drift/tasks.md b/openspec/changes/check-platform-option-drift/tasks.md new file mode 100644 index 0000000..6cb985f --- /dev/null +++ b/openspec/changes/check-platform-option-drift/tasks.md @@ -0,0 +1,16 @@ +Implementation follows `docs/plans/2026-11-13-0900-feat-platform-annotation-plan.md`. + +## 1. Record and check platform options + +- [x] 1.1 Record `register_platform` calls on the recording context, returning + a disposable handle. Verify: `tests/test_platforms.py` + `PlatformRegistrationTests.test_registers_a_platform_alongside_a_tool`. +- [x] 1.2 Report a recorded option the host's `PlatformEntry` lacks as drift. + Verify: `tests/test_testing_harness.py` + `PlatformOptionDriftTests.test_host_without_a_recorded_option_reports_drift_naming_it` + fails when the comparison is removed. +- [x] 1.3 Report a recorded platform call without field names as not checked. + Verify: `PlatformOptionDriftTests.test_platform_call_without_field_names_is_reported_unchecked` + fails when that branch is removed. +- [x] 1.4 Read the field names from a checkout. Verify: + `ResolvedHostPlatformFieldsTests`. diff --git a/tests/test_testing_harness.py b/tests/test_testing_harness.py index 42b6c06..4159fbf 100644 --- a/tests/test_testing_harness.py +++ b/tests/test_testing_harness.py @@ -164,6 +164,145 @@ def test_strict_mode_fails_at_call_time_rather_than_on_replay(self) -> None: self.assertIn("plugin_name", str(caught.exception)) +class HostWithPlatforms(HostV1): + """The pinned register_platform shape: named fields plus **entry_kwargs.""" + + def register_platform( + self, name, label, adapter_factory, check_fn, validate_config=None, + required_env=None, install_hint="", **entry_kwargs, + ): ... + + +# Every PlatformEntry field the recorded call below uses, as a host would list them. +_ENTRY_FIELDS = frozenset({ + "name", "label", "adapter_factory", "check_fn", "validate_config", + "required_env", "install_hint", "source", "plugin_name", "emoji", "display_tier", +}) + + +def _register_a_platform(ctx) -> None: + ctx.register_platform( + name="web_chat", label="Web Chat", adapter_factory=object, + check_fn=lambda: True, validate_config=None, required_env=[], + install_hint="", emoji="*", display_tier="minimal", + ) + + +class PlatformOptionDriftTests(unittest.TestCase): + """Signature binding accepts any name inside **entry_kwargs, so options get + their own check against the host's PlatformEntry fields.""" + + def test_host_without_a_recorded_option_reports_drift_naming_it(self) -> None: + ctx = hpk_testing.RecordingPluginContext(name="probe-plugin") + _register_a_platform(ctx) + + report = ctx.check_against_host( + HostWithPlatforms, platform_entry_fields=_ENTRY_FIELDS - {"display_tier"} + ) + + self.assertTrue(report.checked) + self.assertFalse(report.clean) + self.assertEqual(["register_platform"], [d.registrar for d in report.drifts]) + self.assertIn("display_tier", report.drifts[0].detail) + + def test_host_with_every_recorded_option_is_clean(self) -> None: + ctx = hpk_testing.RecordingPluginContext(name="probe-plugin") + _register_a_platform(ctx) + + report = ctx.check_against_host(HostWithPlatforms, platform_entry_fields=_ENTRY_FIELDS) + + self.assertTrue(report.clean, report) + + def test_unknown_option_names_are_invisible_to_signature_binding_alone(self) -> None: + """Why the extra check exists: the signature replay alone calls this clean.""" + ctx = hpk_testing.RecordingPluginContext(name="probe-plugin") + _register_a_platform(ctx) + + report = ctx.check_against_host( + HostWithPlatforms, platform_entry_fields=frozenset({"name"}) + ) + + self.assertEqual( + {"label", "adapter_factory", "check_fn", "validate_config", "required_env", + "install_hint", "emoji", "display_tier"}, + set(re.findall(r"\b[a-z_]+\b", report.drifts[0].detail.split(":", 1)[1])), + ) + + def test_platform_call_without_field_names_is_reported_unchecked(self) -> None: + ctx = hpk_testing.RecordingPluginContext(name="probe-plugin") + _register_a_tool(ctx) + _register_a_platform(ctx) + + report = ctx.check_against_host(HostWithPlatforms) + + self.assertFalse(report.checked) + self.assertFalse(report.clean) + self.assertIn("register_platform", report.detail) + self.assertIn("platform_entry_fields", report.detail) + + def test_unchecked_options_still_report_signature_drift_found(self) -> None: + ctx = hpk_testing.RecordingPluginContext(name="probe-plugin") + _register_a_tool(ctx) + _register_a_platform(ctx) + + report = ctx.check_against_host(HostAddedRequired) + + self.assertFalse(report.checked) + self.assertIn("register_tool", [d.registrar for d in report.drifts]) + self.assertIn("plugin_name", str(report)) + + def test_no_platform_calls_need_no_field_names(self) -> None: + ctx = hpk_testing.RecordingPluginContext(name="probe-plugin") + _register_a_tool(ctx) + + self.assertTrue(ctx.check_against_host(HostV1).clean) + + +class ResolvedHostPlatformFieldsTests(unittest.TestCase): + """ResolvedHost reads PlatformEntry's field names from the checkout itself.""" + + def setUp(self) -> None: + self._tmp = tempfile.TemporaryDirectory() + self.root = Path(self._tmp.name) + self.addCleanup(self._tmp.cleanup) + + def _isolated_imports(self): + stack = contextlib.ExitStack() + stack.enter_context(patch.dict(sys.modules)) + for name in [m for m in sys.modules if m == "gateway" or m.startswith("gateway.")]: + del sys.modules[name] + stack.enter_context(patch.object(sys, "path", list(sys.path))) + return stack + + def test_reads_field_names_from_the_checkout(self) -> None: + gateway = self.root / "gateway" + gateway.mkdir() + (gateway / "__init__.py").write_text("") + (gateway / "platform_registry.py").write_text( + "from dataclasses import dataclass\n" + "@dataclass\n" + "class PlatformEntry:\n" + " name: str\n" + " label: str\n" + " emoji: str = ''\n" + ) + resolved = hpk_testing.ResolvedHost(self.root, "abc", "test") + + with self._isolated_imports(): + fields = resolved.platform_entry_fields() + + self.assertEqual(frozenset({"name", "label", "emoji"}), fields) + + def test_checkout_without_a_platform_registry_yields_none(self) -> None: + resolved = hpk_testing.ResolvedHost(self.root, "abc", "test") + + with self._isolated_imports(): + self.assertIsNone(resolved.platform_entry_fields()) + + def test_unavailable_host_yields_none(self) -> None: + self.assertIsNone(hpk_testing.ResolvedHost(None, None, "offline").platform_entry_fields()) + + class AbsentHostTests(unittest.TestCase): """An unchecked run must not read as a checked one.""" From 3c036f79a21f11f4b7c80e2aadf5ba6ddfb19427 Mon Sep 17 00:00:00 2001 From: Offending Commit Date: Fri, 13 Nov 2026 09:40:52 -0600 Subject: [PATCH 6/9] test(platforms): pin platform registration against the real Hermes host Registers a platform through the real PluginManager and PlatformRegistry at the deployed revision, and checks that a core name without an override, an option the pinned PlatformEntry lacks, and a host refusal all leave the registry exactly as it was. The refusal case disposes earlier handles through PluginRegistration, and it fails when that dispose is removed. A binding case replays every host symbol the preflight reads. Claude-Session: https://claude.ai/code/session_01B6XeAWUPdrx34tr5dTg5dY --- tests/test_hermes_contract.py | 160 ++++++++++++++++++++++++++++++++++ 1 file changed, 160 insertions(+) diff --git a/tests/test_hermes_contract.py b/tests/test_hermes_contract.py index 24e87fb..9124867 100644 --- a/tests/test_hermes_contract.py +++ b/tests/test_hermes_contract.py @@ -941,5 +941,165 @@ def test_host_serves_plugin_skill_companion_files_from_four_fixed_dirs(self) -> self.assertIn(str(Path("assets") / "logo.png"), linked["assets"]) + +def _platform_host(): + """The pinned host's platform registry, base adapter and registration handle.""" + from gateway import platform_registry as registry_module # type: ignore + from gateway.platforms.base import BasePlatformAdapter # type: ignore + from hermes_cli.plugins_ledger import PluginRegistration # type: ignore + + return types.SimpleNamespace( + module=registry_module, + registry=registry_module.platform_registry, + BasePlatformAdapter=BasePlatformAdapter, + PluginRegistration=PluginRegistration, + ) + + +@unittest.skipUnless(_REAL is not None, "hermes-agent source not importable") +class HermesPlatformContractTests(unittest.TestCase): + """@platform against the real pinned PluginContext and platform registry.""" + + def setUp(self) -> None: + self.host = _platform_host() + self.manager = _REAL.PluginManager() + self.manifest = _REAL.PluginManifest(name="contract-plugin") + # A non-empty config keeps load_plugin_config from reading the machine's + # own Hermes config. + self.manifest.config = {"replace_platforms": []} + self.ctx = _REAL.PluginContext(self.manifest, self.manager) + self.scope = self.manager.scope_key + + def _adapter(self, name, **kwargs): + base = self.host.BasePlatformAdapter + + @hpk.platform(name, label="Contract Chat", check=_platform_check, **kwargs) + class ContractAdapter(base): + async def connect(self, *, is_reconnect=False): + return True + + async def disconnect(self): + return None + + async def send(self, chat_id, content, reply_to=None, metadata=None): + return None + + async def get_chat_info(self, chat_id): + return {"name": chat_id} + + return ContractAdapter + + def _snapshot(self, name): + return self.host.registry.snapshot_registration(name, scope=self.scope) + + def _cleanup(self, *names): + for name in names: + self.addCleanup(self.host.registry.unregister, name, scope=self.scope) + + def test_registers_a_platform_entry_in_the_real_registry(self) -> None: + self._cleanup("hpk_contract_platform") + adapter = self._adapter("hpk_contract_platform", options={"emoji": "*"}) + + summary = hpk.register_plugin(self.ctx, [adapter]) + + entry, loader = self._snapshot("hpk_contract_platform") + self.assertEqual(summary.platforms, ("hpk_contract_platform",)) + self.assertIsNotNone(entry) + self.assertIsNone(loader) + self.assertEqual(entry.label, "Contract Chat") + self.assertIs(entry.check_fn, _platform_check) + self.assertIs(entry.adapter_factory, adapter) + self.assertEqual(entry.emoji, "*") + self.assertEqual(entry.plugin_name, "contract-plugin") + + def test_core_platform_without_override_leaves_the_registry_unchanged(self) -> None: + before = self._snapshot("telegram") + + with self.assertRaisesRegex(ValueError, "plugins.contract-plugin.replace_platforms"): + hpk.register_plugin(self.ctx, [self._adapter("telegram")]) + + after = self._snapshot("telegram") + self.assertIs(after[0], before[0]) + self.assertIs(after[1], before[1]) + + def test_option_the_pinned_entry_lacks_leaves_the_registry_unchanged(self) -> None: + adapter = self._adapter( + "hpk_contract_platform", options={"hpk_not_a_platform_field": 1} + ) + + with self.assertRaisesRegex(ValueError, "hpk_not_a_platform_field"): + hpk.register_plugin(self.ctx, [adapter]) + + self.assertFalse(self.host.registry.is_registered("hpk_contract_platform")) + + def test_host_refusal_rolls_back_through_the_real_registry(self) -> None: + self._cleanup("hpk_contract_a", "telegram", "zz_hpk_contract") + self.manifest.config = {"replace_platforms": ["telegram"]} + before = {name: self._snapshot(name) for name in ("hpk_contract_a", "telegram")} + registry = self.host.registry + original = registry.register + skipped = [] + + def register(entry, *, scope=None): + if entry.name == "zz_hpk_contract": + skipped.append(entry.name) # store nothing: the host then returns None + return None + return original(entry, scope=scope) + + with patch.object(registry, "register", register): + with self.assertRaisesRegex(RuntimeError, "zz_hpk_contract"): + hpk.register_plugin( + self.ctx, + [ + self._adapter("hpk_contract_a"), + self._adapter("telegram"), + self._adapter("zz_hpk_contract"), + ], + ) + + self.assertEqual(skipped, ["zz_hpk_contract"]) + for name, (entry, loader) in before.items(): + with self.subTest(platform=name): + after = self._snapshot(name) + self.assertIs(after[0], entry) + self.assertIs(after[1], loader) + + def test_every_host_symbol_the_preflight_uses_accepts_the_kits_call(self) -> None: + sig = inspect.signature(_REAL.PluginContext.register_platform) + sig.bind( + None, + name="hpk_contract_platform", label="Contract Chat", + adapter_factory=object, check_fn=_platform_check, + validate_config=None, required_env=[], install_hint="", emoji="*", + ) + + module = self.host.module + import dataclasses + + entry_fields = {f.name for f in dataclasses.fields(module.PlatformEntry)} + self.assertTrue({"source", "plugin_name", "trusted_inbound"} <= entry_fields) + + registry_cls = module.PlatformRegistry + inspect.signature(registry_cls.is_registered).bind(None, "x") + inspect.signature(registry_cls.snapshot_registration).bind(None, "x", scope="s") + self.assertIsInstance( + inspect.getattr_static(registry_cls, "current_scope_key"), staticmethod + ) + inspect.signature(registry_cls.current_scope_key).bind() + inspect.signature(module.core_ships_platform).bind("x") + self.assertTrue(module.core_ships_platform("telegram")) + for symbol in hpk._PLATFORM_EXISTENCE_SYMBOLS: + owner = module if symbol == "core_ships_platform" else self.host.registry + self.assertTrue(callable(getattr(owner, symbol, None)), symbol) + + adapter = self._adapter("hpk_contract_platform") + self.assertTrue(issubclass(adapter, self.host.BasePlatformAdapter)) + self.assertFalse(inspect.isabstract(adapter)) + inspect.signature(self.host.PluginRegistration.dispose).bind(None) + + +def _platform_check() -> bool: + return True + if __name__ == "__main__": unittest.main() From b2dfe822e0ddc53310699e958345ffddf13a1cda Mon Sep 17 00:00:00 2001 From: Offending Commit Date: Fri, 13 Nov 2026 09:40:52 -0600 Subject: [PATCH 7/9] docs(platforms): document @platform registration and the replacement override README gains a gateway platforms section: the annotation, option checks against the host's PlatformEntry, optional options, the operator-only plugins..replace_platforms override, rollback on host refusal, and the two new receipt fields. The skill reference, its harness snippet and AGENTS.md teach the same contract, and the public-surface guard treats BasePlatformAdapter as host-owned. Claude-Session: https://claude.ai/code/session_01B6XeAWUPdrx34tr5dTg5dY --- AGENTS.md | 7 +++ README.md | 60 +++++++++++++++++++ skills/hermes-plugins/SKILL.md | 5 +- .../hermes-plugins/references/plugin-kit.md | 17 +++++- tests/test_testing_harness.py | 2 + 5 files changed, 89 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index c6e2d46..d583b0d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -72,6 +72,13 @@ plugin. before submitting it or mutating another host registry. Keep engine schemas and recovery dispatch on `get_tool_schemas` / `handle_tool_call`; do not duplicate native engine tools through `@tool`. +- Register gateway platforms with `@platform` on a `BasePlatformAdapter` + subclass through `register_plugin`. Check options against the host's own + `PlatformEntry`, never a kit-owned field list; read platform existence with + `core_ships_platform`, `is_registered` and `snapshot_registration`, never + `PlatformRegistry.get`, which imports deferred SDKs. Replacing an existing + platform stays operator-gated through `plugins..replace_platforms`, and + a host refusal must dispose this call's earlier platform handles. - Redact secret-looking values in logs and avoid logging full untrusted payloads. - Get Python, `uv` and `just` from `mise.toml` and `mise.lock` (`mise trust && mise install --locked`), the same toolchain CI installs; diff --git a/README.md b/README.md index e202583..dfedcc6 100644 --- a/README.md +++ b/README.md @@ -450,6 +450,8 @@ visible in container logs without forcing verbose plugin logging everywhere. `log_registration_summary(logger, plugin_name, summary)` helper. The receipt uses the Hermes manifest name when available and lists the actual registered command, tool, middleware, hook, and skill names, plus skipped optional skills. +Platform fields (`platforms`, `replaced_platforms`) come last, after every +older field, so position-based parsers keep reading the fields they knew. Runtime-gated consumers should pass their active decorated declarations to `register_plugin`; a truly custom registration path can call the same helper with its own `RegistrationSummary` instead of inventing a second receipt @@ -760,6 +762,64 @@ and `send_voice` with the expected files, without separate text messages. It also runs the kit-owned spoiler extension against Hermes' real config, session, async bridge, and Telegram library shapes while mocking only Bot network calls. +## Gateway platforms + +A plugin that adds a messaging channel annotates its adapter class with +`@platform` and passes it to `register_plugin` like any other declaration. The +class must subclass Hermes' `BasePlatformAdapter`; it is registered as-is and +becomes the `adapter_factory` Hermes calls with the platform config. Follow +Hermes' own adapter guide (`website/docs/developer-guide/adding-platform-adapters.md`) +for the adapter itself. + +```python +from gateway.platforms.base import BasePlatformAdapter +from hermes_plugin_kit import platform, register_plugin + + +def web_chat_ready() -> bool: # passive: report whether dependencies import + return True + + +@platform( + "web_chat", + label="Web Chat", + check=web_chat_ready, + required_env=["WEB_CHAT_TOKEN"], + options={"emoji": "💬", "display_tier": "minimal"}, + optional_options={"display_tier"}, +) +class WebChatAdapter(BasePlatformAdapter): + ... + + +def register(ctx): + return register_plugin(ctx, [WebChatAdapter]) +``` + +`options` passes further `PlatformEntry` fields through unchanged, and +`register_plugin` checks every name against the running host's own +`PlatformEntry` before anything registers. An unknown option fails registration; +one listed in `optional_options` is dropped on a host that lacks it and logged +by name. `source` and `plugin_name` belong to the host and are refused. +`trusted_inbound` is never set unless you pass it, and is refused on any +platform Hermes ships. + +Replacing a platform that already exists, one Hermes ships or one already +registered, fails loudly. Only the operator can allow it, by naming the +platform in the plugin's config: + +```yaml +plugins: + my-plugin: + replace_platforms: [telegram] +``` + +A reload of the plugin's own platform needs no entry, except for a platform +Hermes ships. If Hermes refuses a registration (`register_platform` returns +`None`), `register_plugin` disposes the platforms it already registered in that +call and raises, so a refused plugin leaves no platform behind. The receipt +names `platforms` and `replaced_platforms`. + ## Agent skill The repo owns a Hermes plugin authoring skill at diff --git a/skills/hermes-plugins/SKILL.md b/skills/hermes-plugins/SKILL.md index 4af4922..88c4242 100644 --- a/skills/hermes-plugins/SKILL.md +++ b/skills/hermes-plugins/SKILL.md @@ -98,7 +98,10 @@ ctx = RecordingPluginContext(name="your-plugin", config={}) register(ctx) # your plugin's own registration entry point host = resolve_hermes_checkout() # honors HERMES_AGENT_PATH; fetches at the pin otherwise -report = ctx.check_against_host(host.plugin_context_class()) +report = ctx.check_against_host( + host.plugin_context_class(), + platform_entry_fields=host.platform_entry_fields(), # needed if the plugin registers platforms +) assert report.clean, report # `checked` is False when no host was available ``` diff --git a/skills/hermes-plugins/references/plugin-kit.md b/skills/hermes-plugins/references/plugin-kit.md index 3ec3c93..19b7cc9 100644 --- a/skills/hermes-plugins/references/plugin-kit.md +++ b/skills/hermes-plugins/references/plugin-kit.md @@ -39,6 +39,7 @@ guidance, not a second implementation specification. | Plugin-owned skill | `plugin_skill` | `register_plugin(..., skills=...)` | Hermes adds the plugin namespace; missing required skills fail, optional skills warn and skip. Optional `references_dir` (a companion reference-files directory) drives kit-side validation and `plugin_reference_tool`; the host serves companion files by convention instead, from `references`/`templates`/`assets`/`scripts` beside `SKILL.md`, so name the directory accordingly. See [`README.md`](../../../README.md#commands-middleware-hooks-and-plugin-skills). | | Agent-visible skill reference files (today) | `plugin_reference_tool` | `register_plugin` (its return value is an ordinary `@tool` function — add it to the plugin's declarations) | Sidesteps `register_skill` entirely by exposing `references_dir` as a normal tool call; accepts both paths listed by the tool and skill-relative `references/` forms, while rejecting any path that resolves outside `references_dir` (symlink, absolute path, or `../`) and any non-string `file_path`. `references_dir` itself must be inside the skill's own directory — enforced by `plugin_skill` and re-checked here. | | Context engine | Hermes `ContextEngine` instance | `register_plugin(..., context_engine=...)` | Singular native engine registration; schemas and recovery dispatch stay in `get_tool_schemas()` / `handle_tool_call()`, never duplicated with `@tool`. | +| Gateway platform | `@platform` on a `BasePlatformAdapter` subclass | `register_plugin` | The class is the adapter factory. Options are checked against the host's `PlatformEntry` before anything registers; `optional_options` may be dropped on an older host. Replacing a platform that exists fails unless the operator lists it in `plugins..replace_platforms`. A host refusal rolls back this call's platforms. | | Host-managed call | `invoke_host_tool` | None | Use for supported non-registry capabilities such as `send_message`; pre/post-tool hooks remain active. | | Local media delivery | `MediaPayload`, `MediaType`, `deliver_media` | Consumer registers suppression hooks | File must be absolute, present, and non-empty; `origin` resolves from task-local Hermes context. | | Checking a plugin against the real host | `RecordingPluginContext`, `resolve_hermes_checkout`, `check_registration`, `DEPLOYED_HERMES_REVISION` | None — test-time only | Records what the plugin registers, and its `check_against_host()` replays those calls against the real `PluginContext` signatures. Needs no host to record; reports `checked == False` rather than clean when it could not check. Requires kit 0.9.0 or newer. | @@ -56,6 +57,8 @@ registration state. - Redacted lifecycle logging and registration inventories. - A versioned, correlated lifecycle-event shape with bounded local JSON logging. - Duplicate lifecycle declaration checks before registration. +- Gateway platform registration: host option checks, the replacement guard + and its operator override, and rollback when Hermes refuses a platform. - Guarded host invocation for supported host-managed tools. - Typed Hermes media directives, origin resolution, privacy-safe results, and the narrow Telegram spoiler-photo extension. @@ -66,7 +69,8 @@ Use the direct Hermes API or the specialized upstream plugin interface for: - `ctx.register_cli_command`, `ctx.dispatch_tool`, `ctx.inject_message`, or `ctx.llm.complete*`. -- Gateway platform adapters. +- Gateway platform adapter behavior (connect, send, media); the kit registers + adapters but `BasePlatformAdapter` and Hermes' helpers own what they do. - Memory, model, image, video, browser, web-search, secret source, desktop, or dashboard provider interfaces. The one supported context-engine seam is the singular typed `register_plugin` adapter; the kit does not abstract engine @@ -105,6 +109,17 @@ the same operations with `@tool` shadows the active-context-aware dispatch. - Plain Hermes handlers return encoded strings. Kit-decorated handlers may return dictionaries because the wrapper encodes them. Do not double-encode by habit. - `send_message` is host-managed, not guaranteed to be registry-backed. +- A platform name that Hermes ships or that is already registered is refused + unless the operator lists it in `plugins..replace_platforms`; setting it + from plugin code is not possible by design. +- `optional_options` lets a platform register without an option on an older + host. Do not list an access-policy option (`allowed_users_env`, + `group_allowed_chats_env`) there unless losing it is acceptable. +- Bundled platforms load as deferred loaders. The kit checks for them without + importing their SDKs; never call `PlatformRegistry.get` just to test a name. +- Replaying a recorded `register_platform` call needs + `platform_entry_fields=host.platform_entry_fields()`, or the report is + unchecked: signature binding cannot see option names. - A successful `deliver_media` call needs `transform_media_delivery_output` registered as `transform_llm_output` and `clear_media_delivery_state` registered as `on_session_end`, or the gateway diff --git a/tests/test_testing_harness.py b/tests/test_testing_harness.py index 4159fbf..b6f12e3 100644 --- a/tests/test_testing_harness.py +++ b/tests/test_testing_harness.py @@ -587,6 +587,8 @@ def test_conforming_schema_passes(self) -> None: HOST_OWNED_NAMES = { # Hermes' own class; the kit takes an instance, it does not provide one. "ContextEngine", + # Hermes' adapter base; a @platform class subclasses it. + "BasePlatformAdapter", } From 639a993f128ad767dbc443e94f737f73306ad585 Mon Sep 17 00:00:00 2001 From: Offending Commit Date: Fri, 13 Nov 2026 09:41:39 -0600 Subject: [PATCH 8/9] chore(openspec): archive check-platform-option-drift The harness now checks recorded platform options against the host's PlatformEntry, so the change is folded into the plugin-test-harness spec. Claude-Session: https://claude.ai/code/session_01B6XeAWUPdrx34tr5dTg5dY --- .../.openspec.yaml | 0 .../proposal.md | 0 .../specs/plugin-test-harness/spec.md | 0 .../tasks.md | 0 openspec/specs/plugin-test-harness/spec.md | 15 +++++++++++++++ 5 files changed, 15 insertions(+) rename openspec/changes/{check-platform-option-drift => archive/2026-11-13-check-platform-option-drift}/.openspec.yaml (100%) rename openspec/changes/{check-platform-option-drift => archive/2026-11-13-check-platform-option-drift}/proposal.md (100%) rename openspec/changes/{check-platform-option-drift => archive/2026-11-13-check-platform-option-drift}/specs/plugin-test-harness/spec.md (100%) rename openspec/changes/{check-platform-option-drift => archive/2026-11-13-check-platform-option-drift}/tasks.md (100%) diff --git a/openspec/changes/check-platform-option-drift/.openspec.yaml b/openspec/changes/archive/2026-11-13-check-platform-option-drift/.openspec.yaml similarity index 100% rename from openspec/changes/check-platform-option-drift/.openspec.yaml rename to openspec/changes/archive/2026-11-13-check-platform-option-drift/.openspec.yaml diff --git a/openspec/changes/check-platform-option-drift/proposal.md b/openspec/changes/archive/2026-11-13-check-platform-option-drift/proposal.md similarity index 100% rename from openspec/changes/check-platform-option-drift/proposal.md rename to openspec/changes/archive/2026-11-13-check-platform-option-drift/proposal.md diff --git a/openspec/changes/check-platform-option-drift/specs/plugin-test-harness/spec.md b/openspec/changes/archive/2026-11-13-check-platform-option-drift/specs/plugin-test-harness/spec.md similarity index 100% rename from openspec/changes/check-platform-option-drift/specs/plugin-test-harness/spec.md rename to openspec/changes/archive/2026-11-13-check-platform-option-drift/specs/plugin-test-harness/spec.md diff --git a/openspec/changes/check-platform-option-drift/tasks.md b/openspec/changes/archive/2026-11-13-check-platform-option-drift/tasks.md similarity index 100% rename from openspec/changes/check-platform-option-drift/tasks.md rename to openspec/changes/archive/2026-11-13-check-platform-option-drift/tasks.md diff --git a/openspec/specs/plugin-test-harness/spec.md b/openspec/specs/plugin-test-harness/spec.md index a861c11..19a5d7d 100644 --- a/openspec/specs/plugin-test-harness/spec.md +++ b/openspec/specs/plugin-test-harness/spec.md @@ -61,6 +61,21 @@ signatures wherever a Hermes checkout is importable. - **THEN** the replay reports clean and the recorded registration is available for assertion +#### Scenario: Host removes a platform option + +- **WHEN** a plugin registers a platform with an option the host's + `PlatformEntry` no longer has, and the replay is given the host's + `PlatformEntry` field names +- **THEN** the replay fails and names `register_platform` and the missing + option, even though the call still binds to the registrar's signature + +#### Scenario: Platform options cannot be checked + +- **WHEN** a plugin registers a platform and the replay is not given the host's + `PlatformEntry` field names +- **THEN** the replay reports the run as not checked rather than clean, and + still names any signature drift it found + ### Requirement: Absent host is reported, never assumed clean The harness SHALL remain usable with no Hermes checkout present, and a run that From 5f3ffa86f841ca36fba2aa5b3a96ff837fa0c021 Mon Sep 17 00:00:00 2001 From: Offending Commit Date: Fri, 13 Nov 2026 09:46:55 -0600 Subject: [PATCH 9/9] fix(platforms): bar optional access-policy options and read the host's write scope Two owner decisions from review: Access-policy PlatformEntry options can no longer be optional. Dropping one on an older Hermes would silently change who can reach the agent: losing own_policy_env skips the startup refusal of an open policy, and losing allowlist_suppresses_pairing hands strangers pairing codes. Hermes tags no field as policy, so the kit lists the seven names. The replacement guard now reads existence in the scope Hermes' register_platform writes to, its plugin manager's scope_key, falling back to current_scope_key() without a manager, plus the global scope. In a multiplexer HERMES_HOME's scope can differ, and the guard then refused a free name or missed a real owner. is_registered is no longer read: it always uses current_scope_key(). A real-host case reproduces the divergence at the pin. Claude-Session: https://claude.ai/code/session_01B6XeAWUPdrx34tr5dTg5dY --- AGENTS.md | 6 +- README.md | 5 +- hermes_plugin_kit/__init__.py | 29 ++++++++-- .../hermes-plugins/references/plugin-kit.md | 5 +- tests/test_hermes_contract.py | 35 +++++++++++- tests/test_platforms.py | 56 +++++++++++++++++-- 6 files changed, 121 insertions(+), 15 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index d583b0d..68e7ce5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -75,8 +75,10 @@ plugin. - Register gateway platforms with `@platform` on a `BasePlatformAdapter` subclass through `register_plugin`. Check options against the host's own `PlatformEntry`, never a kit-owned field list; read platform existence with - `core_ships_platform`, `is_registered` and `snapshot_registration`, never - `PlatformRegistry.get`, which imports deferred SDKs. Replacing an existing + `core_ships_platform` and `snapshot_registration` under the plugin manager's + scope (the one Hermes writes to) plus the global scope, never + `PlatformRegistry.get`, which imports deferred SDKs. Access-policy options + are never optional. Replacing an existing platform stays operator-gated through `plugins..replace_platforms`, and a host refusal must dispose this call's earlier platform handles. - Redact secret-looking values in logs and avoid logging full untrusted payloads. diff --git a/README.md b/README.md index dfedcc6..8ce0d51 100644 --- a/README.md +++ b/README.md @@ -800,7 +800,10 @@ def register(ctx): `register_plugin` checks every name against the running host's own `PlatformEntry` before anything registers. An unknown option fails registration; one listed in `optional_options` is dropped on a host that lacks it and logged -by name. `source` and `plugin_name` belong to the host and are refused. +by name. Access-policy options (`trusted_inbound`, `allowed_users_env`, +`allow_all_env`, `allow_bots_env`, `own_policy_env`, `group_allowed_chats_env`, +`allowlist_suppresses_pairing`) cannot be optional: losing one would change who +can reach the agent. `source` and `plugin_name` belong to the host and are refused. `trusted_inbound` is never set unless you pass it, and is refused on any platform Hermes ships. diff --git a/hermes_plugin_kit/__init__.py b/hermes_plugin_kit/__init__.py index 9a0f1a9..e65f667 100644 --- a/hermes_plugin_kit/__init__.py +++ b/hermes_plugin_kit/__init__.py @@ -145,8 +145,15 @@ def register(ctx): # Host reads the replacement guard needs; checked together so a host missing # any of them names every gap at once. _PLATFORM_EXISTENCE_SYMBOLS = ( - "core_ships_platform", "is_registered", "snapshot_registration", "current_scope_key", + "core_ships_platform", "snapshot_registration", "current_scope_key", ) +# PlatformEntry fields that decide who can reach the agent. Dropping one on an +# older host would silently change that, so none may be optional. Hermes tags +# no field as policy, so the kit keeps this list. +_ACCESS_POLICY_PLATFORM_OPTIONS = frozenset({ + "trusted_inbound", "allowed_users_env", "allow_all_env", "allow_bots_env", + "own_policy_env", "group_allowed_chats_env", "allowlist_suppresses_pairing", +}) _NAMED_PLATFORM_OPTIONS = frozenset({ "name", "label", "adapter_factory", "check_fn", "validate_config", "required_env", "install_hint", @@ -1332,6 +1339,12 @@ def platform( "optional_options must name passed options; not passed: " + ", ".join(not_passed) ) + policy = sorted(optional & _ACCESS_POLICY_PLATFORM_OPTIONS) + if policy: + raise ValueError( + "access-policy options cannot be optional; dropping one on an older " + "Hermes would change who can reach the agent: " + ", ".join(policy) + ) spec = { "name": name, "label": label.strip(), @@ -2633,6 +2646,11 @@ def _preflight_platforms( reads = _platform_existence_reads(registry_module) allowed_replacements = _replace_platforms_setting(ctx, plugin_name) manifest_name = getattr(getattr(ctx, "manifest", None), "name", None) + # Read the scope Hermes' register_platform writes to: its plugin manager's. + # In a multiplexer that can differ from HERMES_HOME's current_scope_key(). + scope = getattr(getattr(ctx, "_manager", None), "scope_key", None) + if not isinstance(scope, str) or not scope: + scope = reads["current_scope_key"]() prepared: list[dict[str, Any]] = [] replaced: list[str] = [] for name in sorted(platforms): @@ -2665,10 +2683,11 @@ def _preflight_platforms( f"platform {name!r}: trusted_inbound cannot be set on a platform " "Hermes ships; it would waive allowlists and pairing" ) - if core or reads["is_registered"](name): - entry, loader = reads["snapshot_registration"]( - name, scope=reads["current_scope_key"]() - ) + scoped = reads["snapshot_registration"](name, scope=scope) + shared = reads["snapshot_registration"](name, scope=None) + entry = scoped[0] if scoped[0] is not None else shared[0] + loader = scoped[1] if scoped[1] is not None else shared[1] + if core or entry is not None or loader is not None: own_reload = ( not core and entry is not None diff --git a/skills/hermes-plugins/references/plugin-kit.md b/skills/hermes-plugins/references/plugin-kit.md index 19b7cc9..104031c 100644 --- a/skills/hermes-plugins/references/plugin-kit.md +++ b/skills/hermes-plugins/references/plugin-kit.md @@ -113,8 +113,9 @@ the same operations with `@tool` shadows the active-context-aware dispatch. unless the operator lists it in `plugins..replace_platforms`; setting it from plugin code is not possible by design. - `optional_options` lets a platform register without an option on an older - host. Do not list an access-policy option (`allowed_users_env`, - `group_allowed_chats_env`) there unless losing it is acceptable. + host. Access-policy options (`trusted_inbound`, `allowed_users_env`, + `allow_all_env`, `allow_bots_env`, `own_policy_env`, + `group_allowed_chats_env`, `allowlist_suppresses_pairing`) are refused there. - Bundled platforms load as deferred loaders. The kit checks for them without importing their SDKs; never call `PlatformRegistry.get` just to test a name. - Replaying a recorded `register_platform` call needs diff --git a/tests/test_hermes_contract.py b/tests/test_hermes_contract.py index 9124867..83d3af1 100644 --- a/tests/test_hermes_contract.py +++ b/tests/test_hermes_contract.py @@ -1032,6 +1032,37 @@ def test_option_the_pinned_entry_lacks_leaves_the_registry_unchanged(self) -> No self.assertFalse(self.host.registry.is_registered("hpk_contract_platform")) + def test_guard_reads_the_managers_scope_in_a_multiplexer(self) -> None: + import tempfile + + home = tempfile.TemporaryDirectory() + self.addCleanup(home.cleanup) + mux = _REAL.PluginManager(scope_key=home.name) + registry = self.host.registry + self.assertNotEqual(mux.scope_key, registry.current_scope_key()) + + def context(name, manager): + manifest = _REAL.PluginManifest(name=name) + manifest.config = {"replace_platforms": []} + return _REAL.PluginContext(manifest, manager) + + name = "hpk_contract_mux" + self._cleanup(name) + self.addCleanup(registry.unregister, name, scope=mux.scope_key) + hpk.register_plugin(context("other-plugin", self.manager), [self._adapter(name)]) + home_entry = registry.snapshot_registration(name, scope=self.scope)[0] + + # Another profile owns the name under HERMES_HOME's scope; this one does not. + hpk.register_plugin(context("contract-plugin", mux), [self._adapter(name)]) + mux_entry = registry.snapshot_registration(name, scope=mux.scope_key)[0] + self.assertEqual(mux_entry.plugin_name, "contract-plugin") + self.assertIs(registry.snapshot_registration(name, scope=self.scope)[0], home_entry) + + # A third plugin in the multiplexed profile meets the owner there. + with self.assertRaisesRegex(ValueError, "contract-plugin"): + hpk.register_plugin(context("third-plugin", mux), [self._adapter(name)]) + self.assertIs(registry.snapshot_registration(name, scope=mux.scope_key)[0], mux_entry) + def test_host_refusal_rolls_back_through_the_real_registry(self) -> None: self._cleanup("hpk_contract_a", "telegram", "zz_hpk_contract") self.manifest.config = {"replace_platforms": ["telegram"]} @@ -1080,7 +1111,9 @@ def test_every_host_symbol_the_preflight_uses_accepts_the_kits_call(self) -> Non self.assertTrue({"source", "plugin_name", "trusted_inbound"} <= entry_fields) registry_cls = module.PlatformRegistry - inspect.signature(registry_cls.is_registered).bind(None, "x") + # The guard reads the scope Hermes' register_platform writes to. + self.assertIs(self.ctx._manager, self.manager) + self.assertIsInstance(self.manager.scope_key, str) inspect.signature(registry_cls.snapshot_registration).bind(None, "x", scope="s") self.assertIsInstance( inspect.getattr_static(registry_cls, "current_scope_key"), staticmethod diff --git a/tests/test_platforms.py b/tests/test_platforms.py index 583a8b1..97ac8fe 100644 --- a/tests/test_platforms.py +++ b/tests/test_platforms.py @@ -29,18 +29,20 @@ class _FakeRegistry: """Stand-in for the host's PlatformRegistry: concrete and deferred state.""" def __init__(self) -> None: + # entries/deferred are the global (scope=None) maps; scoped holds the + # entries registered under a profile's scope key. self.entries: dict[str, object] = {} self.deferred: dict[str, object] = {} + self.scoped: dict[str, dict[str, object]] = {} @staticmethod def current_scope_key() -> str: return "" - def is_registered(self, name: str) -> bool: - return name in self.entries or name in self.deferred - def snapshot_registration(self, name: str, *, scope=None): - return self.entries.get(name), self.deferred.get(name) + if scope is None: + return self.entries.get(name), self.deferred.get(name) + return self.scoped.get(scope, {}).get(name), None def get(self, name: str): # Like the host, resolving a deferred name runs its loader, which @@ -159,6 +161,19 @@ def warnings(self) -> list[str]: class PlatformAnnotationTests(unittest.TestCase): + def test_access_policy_options_cannot_be_optional(self) -> None: + for option in ( + "trusted_inbound", "allowed_users_env", "allow_all_env", "allow_bots_env", + "own_policy_env", "group_allowed_chats_env", "allowlist_suppresses_pairing", + ): + with self.subTest(option=option): + with self.assertRaisesRegex(ValueError, f"access-policy.*{option}"): + hpk.platform( + "web_chat", label="Chat", check=_check, + options={option: "X", "emoji": "x"}, + optional_options={option, "emoji"}, + ) + """Decoration-time behavior: what needs no Hermes host to judge.""" def test_annotation_returns_the_same_class_carrying_its_spec(self) -> None: @@ -491,6 +506,39 @@ def test_platform_registered_by_another_plugin_names_the_owner(self) -> None: self.assertNothingRegistered(ctx) + def test_guard_reads_the_scope_hermes_writes_to(self) -> None: + other = types.SimpleNamespace(source="plugin", plugin_name="other-plugin") + with fake_platform_host() as host: + # Another profile in the same process owns the name under HERMES_HOME's scope. + host.registry.scoped[""] = {"web_chat": other} + ctx = RecordingPluginContext() + ctx._manager = types.SimpleNamespace(scope_key="") + summary, _ = _register(ctx, self._module_with(host, "web_chat")) + + self.assertEqual(summary.platforms, ("web_chat",)) + self.assertEqual(summary.replaced_platforms, ()) + + def test_guard_refuses_an_owner_in_the_managers_scope(self) -> None: + other = types.SimpleNamespace(source="plugin", plugin_name="other-plugin") + with fake_platform_host() as host: + host.registry.scoped[""] = {"web_chat": other} + ctx = RecordingPluginContext() + ctx._manager = types.SimpleNamespace(scope_key="") + with self.assertRaisesRegex(ValueError, "other-plugin"): + _register(ctx, self._module_with(host, "web_chat")) + + self.assertNothingRegistered(ctx) + + def test_guard_falls_back_to_the_current_scope_without_a_manager(self) -> None: + other = types.SimpleNamespace(source="plugin", plugin_name="other-plugin") + with fake_platform_host() as host: + host.registry.scoped[""] = {"web_chat": other} + ctx = RecordingPluginContext() + with self.assertRaisesRegex(ValueError, "other-plugin"): + _register(ctx, self._module_with(host, "web_chat")) + + self.assertNothingRegistered(ctx) + def test_deferred_platform_counts_as_existing_without_being_imported(self) -> None: with fake_platform_host() as host: host.registry.deferred["irc_like"] = _deferred_loader