Files
hermes-agent/tests/wisdom/test_client.py
shannonsands a6ee31f55a feat(wisdom): add Hermes Collective Wisdom Agent V1 (#94266)
* feat(wisdom): add trusted publish and install foundation

* feat(wisdom): add private contribution loop

* feat(wisdom): add managed consumption workflows

* fix(wisdom): close cross-repository safety gaps

* fix(wisdom): align local package and lifecycle policy

* fix(wisdom): require explicit profile setup

* docs(wisdom): repin reconciled gateway head

* fix(wisdom): fence content downloads and approval receipts

* docs(wisdom): record generation-fenced downloads

* docs(wisdom): record unified delivery PR

* fix(ci): stop passing invalid classifier inputs

* docs(wisdom): remove internal requirements ledger

* feat(wisdom): localize dashboard and desktop copy

* feat(wisdom): complete local contribution and consumption UX

* style(wisdom): satisfy desktop lint

* chore(wisdom): refresh requirements pin

* test(dashboard): allow formatted profile copy

* test(wisdom): stabilize desktop interaction coverage

* fix(wisdom): surface dashboard action failures

* fix(wisdom): add repeatable Portal demo login

* feat(wisdom): add actionable skill notifications

* feat(wisdom): add notification install and update actions

* fix(wisdom): make Telegram skill alerts actionable

* fix(wisdom): always refresh demo Agent login

* feat(wisdom): embed Telegram notification actions

* fix(wisdom): preserve Telegram notifications after actions

* fix(wisdom): keep Telegram notification cards readable

* feat(wisdom): add Telegram candidate approval flow

* feat(wisdom): explain Telegram qualification reasons

* fix(wisdom): reconcile cross-surface candidate actions

* feat(telegram): add Collective Wisdom management command

* chore(wisdom): refresh Gateway contract pin

* chore(wisdom): advance Gateway contract pin

* feat(wisdom): align command UX across clients

* feat(slack): add Collective Wisdom management parity

* feat(wisdom): add security and professionalism reviews

* feat(wisdom): add first-time qualification guidance

* feat(wisdom): simplify qualification sharing choices

* feat(skills): add optional editorial metadata

* feat(wisdom): enrich legacy skill presentation

* fix(wisdom): harden review and update boundaries

* fix(wisdom): emit canonical review timestamps

* fix(wisdom): align with merged gateway and main

* wisdom: add agent-led sharing core (policy, evidence, schemas, templates, delivery, weekly job, share/install flows)

- hermes_wisdom/agent_led/: policy resolution (server > local > defaults),
  7-day evidence builder that excludes bundled/hub/managed skills and
  dismissed/handled/recently-suggested content hashes, strict pydantic
  schemas for agent output with repair-or-reject, fixed copy templates
  (Share / Teammate / Published / Update / Mute), idempotent retried
  delivery ledger with stale-action resolution, weekly review job,
  resumable Share and Install flows.
- prompts/: candidate review, recipient recommendation, share packaging.
- tests/wisdom/test_agent_led.py: 30 tests.

* wisdom: agent-led renderers and button action dispatcher

- render.py: Telegram HTML, Slack blocks, Desktop payload; editorial name
  is the emphasized line, product label stays separate.
- actions.py: resolve opaque wa:<action>:<dedup> targets via the delivery
  ledger; Not now -> dismissal, Mute -> fixed options, Share -> resumable
  packaging flow, Install/Update -> plan command. Never publishes/installs.

* wisdom: CLI verbs, agent_led config default, conversational catalog skill

- hermes wisdom browse/review-week/act/share/dismiss/mute (all --json).
- wisdom.agent_led config block, default enabled.
- SKILL.md rewritten so natural-language catalog questions map to the CLI
  verbs, share/install flows and fixed notification templates.

* wisdom: wire agent-led weekly review into gateway tick and Telegram buttons

- gateway housekeeping tick calls maybe_run_weekly_review with a home
  channel sender when a Telegram adapter is available.
- Telegram: wa: callbacks resolved through the ledger (stale-safe), mute
  duration keyboard, send_wisdom_agent_recommendation rich card + fallback.

* fix(wisdom): integrate local mediation and harden model and setup boundaries

* fix(wisdom): honor authoritative recommendation policy and defer on failure

* fix(wisdom): synchronize opaque suppression and recheck delivery preferences

* feat(wisdom): route weekly selection through the session-owned assessment queue

* fix(wisdom): prepare and submit the reviewed generated share package

* feat(wisdom): separate native Share preparation from publication consent

* feat(wisdom): sync native mute choices through a leased preference outbox

* feat(wisdom): bind native mute controls to durable preference choices

* feat(wisdom): add scoped desktop and dashboard notification settings

* fix(wisdom): revalidate feed recommendations before assessment and delivery

* fix(wisdom): persist validated delivery receipts before completing notices

* feat(wisdom): add private notification claim and receipt client

* Persist Wisdom send reservations and recover delivery acknowledgements

* Route legacy Wisdom controls through current native review

* Add typed private Wisdom operation outcome client

* fix(wisdom): make agent-led advice usable in the local demo

* fix(wisdom): keep requested consent outside proactive limits

* fix(wisdom): distinguish unavailable assessments and preserve digest text

* fix(wisdom): assess ongoing usefulness beyond the current task

* fix(wisdom): restore immediate qualification sharing controls

* fix(wisdom): separate qualification review from installation advice

* fix(wisdom): collapse review checklists and simplify sharing copy

* fix(wisdom): show compact sharing progress and publication receipts

* fix(wisdom): require credential prefixes rather than matching skill names

* fix(wisdom): finish package checks before presenting sharing consent

* fix(wisdom): scan local skills before qualification cards

* fix(wisdom): update moderation results on existing sharing cards

* fix(wisdom): keep sharing review accessible from receipt cards

* fix(wisdom): align mediated review cards and collapsible checks

* fix(wisdom): clarify clean security summary wording

* fix(wisdom): normalize consent plans and add explicit recheck

* fix(wisdom): keep install and update receipts concise

* fix(wisdom): collapse assessments and deduplicate operation cards

* fix(wisdom): restore private Portal review from native cards

* fix(wisdom): sync Portal publication to original consent card

* fix(wisdom): show local skill version on sharing cards

* fix(wisdom): skip agent recommendations for self-published versions

* fix(wisdom): simplify candidate notices and local-edit recovery copy

* feat(wisdom): submit locally reviewed packages with one confirmation

* feat(wisdom): expose safe receipt and outcome sync recovery

* wisdom: onboarding notice says detect and share, names the user's own skill

Copy review from the product owner on the first and returning
qualification notices (fixed delivery mode):
- the feature blurb now says the org enabled detection *and sharing*
- both notices say the detected skill is one the user created
- both close with an exclamation mark

Applied identically to hermes_wisdom.notice, the desktop and web i18n
strings, and the tests that assert the sentences.

* wisdom: one opener, no approval line, ask to share after the skill is shown

Product owner review of the candidate card.

- The Hermes written card now opens with the same sentence as the fixed card
  ("Your organisation has enabled Collective Wisdom, a feature designed to
  automatically detect and share useful skills across all team members.")
  instead of its own blurb, so there is one first time message.
- "Nothing is shared without your approval." removed from Telegram, Slack
  and Desktop. The buttons already make the permission explicit.
- "Would you like to share?" no longer appears before the skill is named.
  It is now the last line, after the skill name, description, why suggested
  and the checks, and reads "Would you like to share it?" (matching the
  agent led template wording).

Tests updated for the new order; proposalNotice removed from all desktop locales.

* wisdom: American spelling, organization

Product owner decision: user facing copy uses American spelling.
Changes "Your organisation" to "Your organization" in the chat notice,
the Hermes written card opener, the desktop and web strings, and the
tests that assert them. Identifiers such as nas_organisation:* and the
German and French locales are untouched.

* wisdom: candidate card copy round 4 (owner review)

Apply the product owner's round 4 copy decisions to the Hermes Collective
Wisdom candidate card on Telegram, Slack, Desktop and the shared views:

1. Hermes-written cards are titled "Hermes Collective Wisdom" instead of
   the bare "Collective Wisdom".
2. The "Reusable skill ready to review" line is gone from the candidate
   card (Telegram rich card and plain fallback, legacy agent-led share
   template).
3. The skill name and description are labelled: "Skill name: <name>" and
   "What it does: <description>" (Telegram, Slack, Desktop).
4. "Why suggested:" is now "Why others might benefit:".
5. A passing professionalism review reads "Safe to share at work ✓ (no
   inappropriate content found)" with no per-check bullets and no "Pass";
   a failed review reads "Needs a look before sharing at work (possible
   inappropriate content)" and lists only the checks that flagged
   something. Pending/unavailable wording is unchanged.
6. Telegram button toasts: "Will ask later...", "Preparing more
   details...", "Sharing...".
7. Qualification reasons: "You used this skill consistently across many
   days." and "You've really refined this skill."
8. prompts/wisdom_candidate_review.md asks for a compelling
   editorial_name, a simple one_line_description and a compelling
   why_coworkers_benefit under 300 characters; "Be concise and
   convincing." becomes "Be concise and compelling: the goal is that the
   user wants to share it."

Tests updated for the new strings; review_text() gains direct coverage.

* wisdom: re-apply owner copy after rebase

- Native share cards (advice_view/interaction_view): drop the approval line, ask "Would you like to share it?" as the last line after the checks
- Hermes-written completion card titled "Hermes Collective Wisdom"
- Qualification reasons use the owner wording (consistently across many days / really refined)
- American spelling (organization) in remaining English copy
- Desktop test asserts the current Share button; web test matches the returning notice

* fix(wisdom): pin reconciled Gateway and verify Unicode hash vectors

Pin Gateway 60cd2d6b613ae3cd4a6e65155d1142006d907e78 and byte-identical producer artifacts. Verify every content-order case and package-manifest binding. Validation: 186 focused Python tests, Ruff and contract verifier.

* fix(wisdom): reconcile optional SDK tests and frontend lint

* fix(wisdom): default to agent-written notification summaries

* fix(wisdom): restore deferred install review and browse controls

* feat(wisdom): inspect installed setup with exact package provenance

* feat(wisdom): run native-approved installed setup steps with durable evidence

* fix(wisdom): recover interrupted setup with explicit native consent

* feat(wisdom): hand native installs into guided setup review

* fix(wisdom): continue requested setup with fixed notification copy

* fix(wisdom): preserve setup while waiting for a session model

* fix(wisdom): expose canonical setup review controls on desktop

* fix(wisdom): resume setup after recorded automatic updates

* fix(wisdom): make missing setup prerequisites recheckable

* chore(wisdom): align Agent with verified Gateway contract

* fix(wisdom): stop guessing team slugs in portal links

* fix(wisdom): retire pending advice on account sign-out

* fix(wisdom): cancel advice after terminal account revocation

* fix(wisdom): fence feed responses across account sign-out

* fix(wisdom): checkpoint signed-out feed before reactivation

* fix(wisdom): link proactive advice to scoped notification settings

* fix(wisdom): coalesce queued publication recommendations by version

* fix(wisdom): keep package review navigation local and deferable

* fix(wisdom): reflect installed state in discovery controls

* fix(wisdom): show exact checks before command confirmation

* chore(wisdom): pin bounded analytics privacy contract

* chore(wisdom): pin retired legacy notification contract

* feat(wisdom): review publisher usage with exact sharing copy

* fix(wisdom): align discovery and review check summaries

* fix(wisdom): show expired consent before confirmation

* fix(wisdom): require fresh review for legacy install controls

* fix(wisdom): preserve review expiry across check toggles

* fix(wisdom): retain update policy in native install reviews

* fix(wisdom): surface failed native card edits

* fix(wisdom): persist local command approval reviews

* fix(wisdom): use saved approvals for messaging commands

* test(wisdom): provide scan result in setup handoff fixture

* test(wisdom): exercise Telegram approvals with saved review state

* fix(wisdom): retain suppression policy for offline deferral

* fix(wisdom): reconsider candidates after deferred suppression expires

* fix(wisdom): bind review checks and report verified readiness separately

* fix(wisdom): persist accepted publication intent and recover exact outcomes

* fix(sync): pin UTF-8 tree ordering across writers

* chore(wisdom): pin organisation-scoped Gateway authorization

* fix(wisdom): restrict consent delivery to user-facing sessions

* chore(wisdom): refresh reviewed Gateway contract pin

* fix(wisdom): preserve kept tools in Blank Slate exclusions

* test(auth): reset anonymous fixture with a profile-scoped cache

* fix(wisdom): gate local surfaces and work on current profile entitlement

* fix(wisdom): invalidate quiet tool cache on entitlement changes

* test(wisdom): authorize local consent gateway fixtures

* fix(wisdom): keep entitlement decoding free of native crypto imports

* test(wisdom): provide local entitlement to demo CLI subprocess

* ci: leave upstream workflow unchanged in Wisdom PR

* fix(wisdom): ship package and contracts in Nix wheels

---------

Co-authored-by: hbizi <36184542+hbizi@users.noreply.github.com>
2026-09-11 19:04:06 +10:00

697 lines
25 KiB
Python

import json
import base64
import hashlib
from uuid import uuid4
import pytest
from hermes_wisdom.client import (
Draft,
WisdomClient,
WisdomError,
WisdomNotFound,
WisdomValidationError,
)
from hermes_wisdom.package import verify_content_files
from hermes_wisdom.delivery import DeliveryReceipt
from hermes_wisdom.client_delivery import receipt_projection
def _draft(**overrides):
value = {
"id": "d1",
"orgId": "o1",
"ownerUserId": "u1",
"slug": "my-skill",
"draftCommit": "sha256:" + "a" * 64,
"contentHash": "sha256:" + "b" * 64,
"authorDescription": "Does a task.",
"authorDescriptionHash": "sha256:" + "c" * 64,
"state": "ready",
"packageManifestHash": "sha256:" + "d" * 64,
"packageManifestSchemaVersion": 1,
"systemSpec": None,
"scan": None,
"scanVerdict": "pass",
"explanation": None,
"updatedAt": "now",
}
value.update(overrides)
return value
def test_changes_requested_requires_complete_moderator_metadata():
with pytest.raises(ValueError, match="moderator return metadata"):
Draft.model_validate(_draft(state="changes_requested"))
returned = Draft.model_validate(
_draft(
state="changes_requested",
moderationNote="Remove the hostname.",
moderationDeciderUserId="moderator-1",
moderationDecidedAt="2026-08-25T00:00:00Z",
)
)
assert returned.moderationNote == "Remove the hostname."
class Response:
def __init__(self, status: int, body):
self.status_code = status
self._body = body
self.content = json.dumps(body).encode() if body is not None else b""
def json(self):
return self._body
def raise_for_status(self):
if self.status_code < 200 or self.status_code >= 300:
raise RuntimeError(f"HTTP {self.status_code}")
class Session:
def __init__(self, response):
self.response = response
self.calls = []
def request(self, method, url, **kwargs):
self.calls.append((method, url, kwargs))
return self.response
def get(self, url, **kwargs):
self.calls.append(("GET", url, kwargs))
return self.response
def client(response):
value = WisdomClient.__new__(WisdomClient)
value.base = "https://gateway.example"
value.timeout = 7
value.session = Session(response)
return value
def delivery_client(**overrides):
body = {
"org_id": "o1", "recipient_user_id": "u1", "event_id": "event-1",
"request_id": str(uuid4()), "reference": {"kind": "candidate", "key": "sha256:" + "a" * 64},
"state": "claimed", "lease_until": "2026-09-07T12:02:00.000Z", "reason": None,
**overrides,
}
c = client(Response(200, body))
c.identity = {"owner": "u1", "claims": {"org_id": "o1"}}
return c, body
def test_delivery_claim_is_minimal_and_does_not_upload_private_metadata():
c, body = delivery_client()
result = c.claim_notification_delivery(body["request_id"], body["reference"])
assert result.state == "claimed"
assert c.session.calls[0][2]["json"] == {"request_id": body["request_id"], "reference": body["reference"]}
for reference in [
{**body["reference"], "skill_name": "private-name"},
{"kind": "candidate", "key": "private-name"},
{"kind": "skill", "skill_id": "shared", "version": True, "event_type": "teammate_published"},
{"kind": "skill", "skill_id": "shared", "version": 0, "event_type": "teammate_published"},
]:
with pytest.raises(WisdomValidationError):
c.claim_notification_delivery(body["request_id"], reference)
assert len(c.session.calls) == 1
def operation_client():
report = {"request_id": str(uuid4()), "operation_key": "sha256:" + "a" * 64,
"operation": "install", "state": "completed"}
body = {"org_id": "o1", "recipient_user_id": "u1", "event_id": "e1", "outcome": report,
"attestation": "client_reported", "duplicate": False}
c = client(Response(200, body))
c.identity = {"owner": "u1", "claims": {"org_id": "o1"}}
return c, body, report
def test_operation_outcome_sends_only_typed_metadata_and_replays_same_identity():
c, body, report = operation_client()
result = c.report_operation_outcome("e1", report)
assert result.attestation == "client_reported"
assert c.session.calls[0][2]["json"] == report
assert c.session.calls[0][1].endswith("/agent-led/deliveries/e1/outcomes")
c.session.response = Response(200, {**body, "duplicate": True})
assert c.report_operation_outcome("e1", report).duplicate is True
assert c.session.calls[1][2]["json"] == report
@pytest.mark.parametrize("patch", [
{"state": "queued"}, {"operation": "share"}, {"state": "verified"},
{"operation_key": "local-consent-secret"}, {"description": "private-skill-description"},
{"receipt": "local-consent-token"}, {"user_id": "override"}, {"request_id": "bad"},
])
def test_operation_outcome_refuses_invalid_or_private_fields_before_http(patch):
c, _, report = operation_client()
with pytest.raises(WisdomValidationError):
c.report_operation_outcome("e1", {**report, **patch})
assert c.session.calls == []
@pytest.mark.parametrize("field,value", [
("org_id", "other"), ("recipient_user_id", "other"), ("event_id", "other"),
("outcome", {"request_id": str(uuid4()), "operation_key": "sha256:" + "a" * 64,
"operation": "install", "state": "completed"}),
])
def test_operation_outcome_rejects_misbound_responses(field, value):
c, body, report = operation_client()
c.session.response = Response(200, {**body, field: value})
with pytest.raises(WisdomError, match="does not match"):
c.report_operation_outcome("e1", report)
def test_operation_outcome_rechecks_account_after_request():
c, _, report = operation_client()
original = c.session.request
def change_identity(*args, **kwargs):
c.identity["owner"] = "other"
return original(*args, **kwargs)
c.session.request = change_identity
with pytest.raises(WisdomError, match="does not match"):
c.report_operation_outcome("e1", report)
@pytest.mark.parametrize("patch", [{"attestation": "verified"}, {"duplicate": 1}, {"advice": "unexpected"}])
def test_operation_outcome_rejects_untrusted_response_claims(patch):
c, body, report = operation_client()
c.session.response = Response(200, {**body, **patch})
with pytest.raises(WisdomError, match="schema validation"):
c.report_operation_outcome("e1", report)
@pytest.mark.parametrize("operation,state", [
("share", "queued"), ("share", "failed"), ("publish", "completed"),
("install", "completed"), ("update", "completed"), ("update", "needs_review"),
("install", "stale"), ("publish", "expired"),
])
def test_operation_outcome_preserves_exact_result_without_implying_verification(operation, state):
c, body, report = operation_client()
report = {**report, "operation": operation, "state": state}
c.session.response = Response(200, {**body, "outcome": report})
result = c.report_operation_outcome("e1", report)
assert result.outcome.model_dump() == report
@pytest.mark.parametrize("field,value", [
("org_id", "other-org"), ("recipient_user_id", "other-user"),
("request_id", str(uuid4())),
("reference", {"kind": "candidate", "key": "sha256:" + "b" * 64}),
])
def test_delivery_claim_rejects_misbound_responses(field, value):
c, body = delivery_client()
request = {"request_id": body["request_id"], "reference": body["reference"]}
c.session.response = Response(200, {**body, field: value})
with pytest.raises(WisdomError, match="does not match"):
c.claim_notification_delivery(**request)
@pytest.mark.parametrize("overrides", [
{"lease_until": None}, {"lease_until": "2026-09-07T12:02:00"},
{"lease_until": "invalid"}, {"reason": "recipient_muted"},
{"state": "deferred"}, {"state": "acknowledged"},
{"untrusted_payload": "not part of this contract"},
])
def test_delivery_claim_rejects_inconsistent_directives(overrides):
c, body = delivery_client(**overrides)
with pytest.raises(WisdomError, match="schema validation"):
c.claim_notification_delivery(body["request_id"], body["reference"])
def test_delivery_response_rechecks_identity_after_request():
c, body = delivery_client()
original = c.session.request
def change_identity(*args, **kwargs):
c.identity["owner"] = "other-user"
return original(*args, **kwargs)
c.session.request = change_identity
with pytest.raises(WisdomError, match="does not match"):
c.claim_notification_delivery(body["request_id"], body["reference"])
def test_settlement_sends_only_hashed_receipt_identifiers():
c, body = delivery_client(state="acknowledged", lease_until=None)
receipt = DeliveryReceipt(platform="slack", destination="private-channel", message_id="123.456",
thread_id="100.200", scope_id="private-workspace", acknowledgement="provider_accepted")
result = c.settle_notification_delivery(body["event_id"], body["request_id"], body["reference"], outcome="acknowledged", receipt=receipt)
assert result.state == "acknowledged"
sent = c.session.calls[0][2]["json"]
assert sent == {"request_id": body["request_id"], "outcome": "acknowledged", "receipt": receipt_projection(receipt).model_dump()}
serialized = json.dumps(sent)
for private in [receipt.destination, receipt.message_id, receipt.thread_id, receipt.scope_id]:
assert private not in serialized
assert receipt_projection(receipt) == receipt_projection(receipt)
assert receipt_projection(receipt).message_key != receipt_projection(receipt).destination_key
changed = receipt.model_copy(update={"scope_id": "different-workspace"})
assert receipt_projection(changed).message_key != receipt_projection(receipt).message_key
@pytest.mark.parametrize("outcome", ["not_sent", "uncertain"])
def test_settlement_without_send_never_fabricates_a_receipt(outcome):
c, body = delivery_client(state=outcome, lease_until=None)
c.settle_notification_delivery(body["event_id"], body["request_id"], body["reference"], outcome=outcome)
assert c.session.calls[0][2]["json"] == {"request_id": body["request_id"], "outcome": outcome}
def test_settlement_requires_a_valid_receipt_and_matching_result():
c, body = delivery_client(state="acknowledged", lease_until=None)
args = (body["event_id"], body["request_id"], body["reference"])
with pytest.raises(WisdomValidationError):
c.settle_notification_delivery(*args, outcome="acknowledged")
with pytest.raises(WisdomValidationError):
c.settle_notification_delivery(*args, outcome="acknowledged", receipt={"success": True})
assert c.session.calls == []
with pytest.raises(WisdomError, match="was not acknowledged"):
c.settle_notification_delivery(*args, outcome="not_sent")
c.session.response = Response(200, {**body, "event_id": "other-event", "state": "not_sent"})
with pytest.raises(WisdomError, match="does not match"):
c.settle_notification_delivery(*args, outcome="not_sent")
def test_capability_uses_gateway_features_field():
value = client(Response(200, {"features": ["personal", "org", "wisdom"]}))
assert value.capability()["features"][-1] == "wisdom"
def _agent_led_policy(**overrides):
return {
"org_id": "o1",
"usage_evidence_window_days": 7,
"min_aggregate_invocations": 3,
"consecutive_day_usage_counts": True,
"repeated_edits_count": True,
"max_recommendations_per_user_per_week": 3,
"publication_mode": "moderated",
"install_popularity_threshold": 10,
"notification_defaults": {
"skill_ready_to_share": True,
"teammate_published": False,
"update_available": True,
},
"manager_review_email_cadence": "daily",
"not_now_suppression_days": 30,
"version": 1,
"updated_by_user_id": None,
**overrides,
}
def test_agent_led_policy_reads_member_endpoint_with_bounded_request():
value = client(Response(200, _agent_led_policy()))
value.identity = {"claims": {"org_id": "o1"}}
result = value.agent_led_policy()
assert result.notification_defaults.teammate_published is False
assert value.session.calls == [
(
"GET",
"https://gateway.example/v1/sync/wisdom/agent-led/policy",
{
"json": None,
"params": None,
"timeout": 7,
},
)
]
@pytest.mark.parametrize(
"override",
[
{"org_id": "other-org"},
{"min_aggregate_invocations": "3"},
{"notification_defaults": {"teammate_published": True}},
{"max_recommendations_per_user_per_week": -1},
],
)
def test_agent_led_policy_rejects_wrong_org_or_invalid_response(override):
value = client(Response(200, _agent_led_policy(**override)))
value.identity = {"claims": {"org_id": "o1"}}
with pytest.raises(WisdomError):
value.agent_led_policy()
@pytest.mark.parametrize("status", [401, 403, 404, 503])
def test_unavailable_agent_led_policy_defers_instead_of_enabling_defaults(
monkeypatch, status
):
from hermes_wisdom.agent_led.policy import load_policy
monkeypatch.setattr("hermes_wisdom.mediation.delivery_mode", lambda: "agent")
value = client(Response(status, {"error": "unavailable"}))
value.identity = {"claims": {"org_id": "o1"}}
result = load_policy(client=value, local={"enabled": True})
assert result.enabled is False
assert result.source == "server_unavailable"
def test_fixed_mode_does_not_fetch_agent_led_policy(monkeypatch):
from hermes_wisdom.agent_led.policy import load_policy
monkeypatch.setattr("hermes_wisdom.mediation.delivery_mode", lambda: "fixed")
value = client(Response(200, _agent_led_policy()))
value.identity = {"claims": {"org_id": "o1"}}
assert load_policy(client=value, local={"enabled": True}).enabled is False
assert not value.session.calls
def test_suppression_wire_contains_only_opaque_keys_and_empty_write_body():
key = "sha256:" + "a" * 64
value = client(
Response(
200, {"org_id": "o1", "key": key, "suppress_until": "2026-10-01T00:00:00Z"}
)
)
value.identity = {"claims": {"org_id": "o1"}}
assert value.suppress_recommendation(key).key == key
assert value.session.calls[0][2]["json"] == {}
assert value.session.calls[0][1].endswith("/suppressions/sha256%3A" + "a" * 64)
value.session.response = Response(200, {"org_id": "o1", "suppressions": []})
assert value.recommendation_suppressions([key]) == []
assert value.session.calls[-1][2]["json"] == {"keys": [key]}
def test_suppression_response_cannot_inject_unrequested_or_foreign_keys():
key = "sha256:" + "a" * 64
value = client(
Response(
200,
{
"org_id": "o1",
"suppressions": [
{
"key": "sha256:" + "b" * 64,
"suppress_until": "2026-10-01T00:00:00Z",
}
],
},
)
)
value.identity = {"claims": {"org_id": "o1"}}
with pytest.raises(WisdomError):
value.recommendation_suppressions([key])
value.session.response = Response(200, {"org_id": "other", "suppressions": []})
with pytest.raises(WisdomError):
value.recommendation_suppressions([key])
def test_mute_wire_preserves_native_duration_vocabulary():
value = client(
Response(
200,
{
"org_id": "o1",
"muted": True,
"duration": "1_week",
"muted_until": "2026-10-01T00:00:00Z",
"forever": False,
},
)
)
value.identity = {"claims": {"org_id": "o1"}}
assert value.set_recommendation_mute("1_week").muted
assert value.session.calls[-1][2]["json"] == {"duration": "1_week"}
with pytest.raises(WisdomValidationError):
value.set_recommendation_mute("arbitrary")
value.recommendation_mute()
assert value.session.calls[-1][2]["params"] == {"include_revision": "1"}
def test_guarded_mute_clear_keeps_idempotency_metadata_on_put():
response = {"org_id": "o1", "muted": False, "duration": None, "muted_until": None,
"forever": False, "revision": 3, "mutation_id": "a" * 32, "updated_at": "2026-09-07T00:00:00.000Z"}
value = client(Response(200, response))
value.identity = {"claims": {"org_id": "o1"}}
result = value.set_recommendation_mute(None, expected_revision=2, mutation_id="a" * 32, requested_at="2026-09-07T00:00:00.000Z")
assert result.revision == 3
method, _, request = value.session.calls[-1]
assert method == "PUT"
assert request["json"] == {"duration": None, "expected_revision": 2, "mutation_id": "a" * 32, "requested_at": "2026-09-07T00:00:00.000Z"}
with pytest.raises(WisdomValidationError):
value.set_recommendation_mute("1_day", expected_revision=2)
assert len(value.session.calls) == 1
def test_submit_body_has_no_local_candidate_or_activity_signals():
body = {
"draft": {
"id": "d1",
"orgId": "o1",
"ownerUserId": "u1",
"slug": "my-skill",
"draftCommit": "sha256:" + "a" * 64,
"contentHash": "sha256:" + "b" * 64,
"authorDescription": "Does a task.",
"authorDescriptionHash": "sha256:" + "c" * 64,
"state": "ready",
"packageManifestHash": "sha256:" + "d" * 64,
"packageManifestSchemaVersion": 1,
"systemSpec": None,
"scan": None,
"scanVerdict": "pass",
"explanation": None,
"updatedAt": "now",
}
}
value = client(Response(201, body))
value.submit_draft(
slug="my-skill",
commit="sha256:" + "a" * 64,
content_hash="sha256:" + "b" * 64,
description="Does a task.",
)
payload = value.session.calls[0][2]["json"]
assert payload == {
"slug": "my-skill",
"draft_commit": "sha256:" + "a" * 64,
"content_hash": "sha256:" + "b" * 64,
"author_description": "Does a task.",
}
assert not (
{"usage", "refinement", "candidate", "ranking", "stability", "dismissal"}
& payload.keys()
)
def test_not_found_is_opaque():
value = client(Response(404, {"error": "not_found"}))
with pytest.raises(WisdomNotFound, match="item not found"):
value._request("GET", "skills/secret")
def test_approve_exact_three_hash_body():
value = client(Response(200, {"draft": {"id": "invalid"}}))
with pytest.raises(Exception):
value.approve("d1", content_hash="c", description_hash="d", manifest_hash="m")
payload = value.session.calls[0][2]["json"]
assert payload == {
"content_hash": "c",
"author_description_hash": "d",
"package_manifest_hash": "m",
}
def test_revise_binds_predecessor_hashes_and_new_private_commit():
value = client(Response(201, {"draft": _draft(id="d2")}))
professionalism_review = {
"schema_version": 1,
"content_hash": "sha256:" + "f" * 64,
"author_description_hash": "sha256:" + "9" * 64,
"status": "pass",
"summary": "No language or conduct concerns detected.",
"checks": [],
"provenance": {
"kind": "agent_assessed",
"provider": "codex",
"model": "gpt-5.6-sol",
},
"assessed_at": "2026-09-02T00:00:00Z",
}
revised = value.revise_draft(
"d1",
commit="sha256:" + "e" * 64,
content_hash="sha256:" + "f" * 64,
description="Updated owner copy.",
expected_content_hash="sha256:" + "b" * 64,
expected_description_hash="sha256:" + "c" * 64,
expected_manifest_hash="sha256:" + "d" * 64,
professionalism_review=professionalism_review,
)
assert revised.id == "d2"
method, url, request = value.session.calls[0]
assert (method, url) == (
"POST",
"https://gateway.example/v1/sync/wisdom/drafts/d1/revise",
)
assert request["json"] == {
"draft_commit": "sha256:" + "e" * 64,
"content_hash": "sha256:" + "f" * 64,
"author_description": "Updated owner copy.",
"expected_content_hash": "sha256:" + "b" * 64,
"expected_author_description_hash": "sha256:" + "c" * 64,
"expected_package_manifest_hash": "sha256:" + "d" * 64,
"professionalism_review": professionalism_review,
}
def test_content_fetch_is_bound_to_installation_identity_and_takedown_generation():
skill = b"# Skill\n"
manifest = b'{"schema_version":1,"name":"skill","requirements":{"hermes":{"minimum_version":"0.1.0"}}}'
files = [
("SKILL.md", "file", skill),
("skill.manifest.json", "file", manifest),
]
_records, content_hash = verify_content_files(files)
value = client(
Response(
200,
{
"commit": "sha256:" + "a" * 64,
"content_hash": content_hash,
"files": [
{
"path": path,
"mode": mode,
"hash": "sha256:" + hashlib.sha256(body).hexdigest(),
"content_base64": base64.b64encode(body).decode("ascii"),
}
for path, mode, body in files
],
},
)
)
value.content(
"skill-1",
2,
installation_id="hwi_1234567890123456",
takedown_generation=7,
)
method, url, request = value.session.calls[0]
assert (method, url) == (
"GET",
"https://gateway.example/v1/sync/wisdom/skills/skill-1/versions/2/content",
)
assert request["params"] == {
"installation_id": "hwi_1234567890123456",
"takedown_generation": 7,
}
def test_raw_copy_fetches_hash_verified_published_bytes_without_install_state():
skill = b"# Skill\n"
manifest = b'{"schema_version":1,"name":"skill","requirements":{"hermes":{"minimum_version":"0.1.0"}}}'
files = [
("SKILL.md", "file", skill),
("skill.manifest.json", "file", manifest),
]
_records, content_hash = verify_content_files(files)
value = client(
Response(
200,
{
"commit": "sha256:" + "a" * 64,
"content_hash": content_hash,
"copy_semantics": "unmanaged_fork",
"files": [
{
"path": path,
"mode": mode,
"hash": "sha256:" + hashlib.sha256(body).hexdigest(),
"content_base64": base64.b64encode(body).decode("ascii"),
}
for path, mode, body in files
],
},
)
)
_response, decoded = value.raw_copy("skill-1", 2)
assert decoded == files
method, url, request = value.session.calls[0]
assert (method, url) == (
"GET",
"https://gateway.example/v1/sync/wisdom/skills/skill-1/versions/2/raw",
)
assert request["params"] is None
def test_installation_reconciliation_uses_identity_path_and_owned_delete():
value = client(Response(200, {"installations": []}))
assert value.installations("hwi_1234567890123456") == []
method, url, request = value.session.calls[0]
assert (method, url) == (
"GET",
"https://gateway.example/v1/sync/wisdom/installations/hwi_1234567890123456",
)
assert request["params"] is None
value.session.response = Response(
200,
{
"skill_id": "skill-1",
"installation_id": "hwi_1234567890123456",
"state": "inactive",
},
)
result = value.deactivate_install("hwi_1234567890123456", "skill-1")
assert result.state == "inactive"
assert value.session.calls[1][0:2] == (
"DELETE",
"https://gateway.example/v1/sync/wisdom/installations/hwi_1234567890123456/skills/skill-1",
)
def test_installation_and_feed_responses_are_typed_fail_closed():
value = client(
Response(
200,
{
"installations": [
{
"skill_id": "skill-1",
"installed_version": 1,
"latest_version": 2,
"update_mode": "UNKNOWN",
"skill_state": "active",
"takedown_generation": 0,
}
]
},
)
)
with pytest.raises(WisdomError, match="schema validation"):
value.installations("hwi_1234567890123456")
value.session.response = Response(
200,
{
"events": [
{
"event_id": "event-1",
"kind": "invented",
"skill_id": "skill-1",
"version": 2,
"takedown_generation": 0,
"installation_id": "hwi_1234567890123456",
"update_mode": "MANUAL",
"occurred_at": "2026-08-24T00:00:00Z",
}
],
"next_cursor": "cursor-1",
"has_more": False,
},
)
with pytest.raises(WisdomError, match="schema validation"):
value.feed(installation_id="hwi_1234567890123456")