Files
hermes-agent/tests/wisdom/test_share_queue.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

756 lines
33 KiB
Python

import json
from types import SimpleNamespace
from unittest.mock import Mock
import pytest
from hermes_wisdom.client import WisdomConflict, WisdomNotFound
from hermes_wisdom.consent import ConsentActor
from hermes_wisdom.delivery import DeliveryReceipt
from hermes_wisdom.mediation import WisdomMediation
from hermes_wisdom.mediation_view import advice_view, interaction_view
from tests.wisdom.test_share_staging import staged # noqa: F401
from tests.wisdom.test_service import FakeClient
RECEIPT = DeliveryReceipt(
platform="telegram",
destination="chat",
thread_id="thread",
message_id="1",
acknowledgement="provider_accepted",
)
@pytest.mark.parametrize("version,expected", [("0.2.0", "0.2.0"), ("v1.2.3-beta.1", "1.2.3-beta.1"), ("true", None), ("'[install](https://example.org)'", None)])
def test_candidate_version_comes_from_exact_source(staged, version, expected):
from hermes_wisdom.service import _source_fingerprint
service, _, source, _ = staged
(source / "SKILL.md").write_text(f"---\nname: notes\nversion: {version}\n---\nSkill body\n")
content_hash = _source_fingerprint(source)
skill = service.store.register_skill(source, content_hash=content_hash, source_kind="local")
assert service.candidate_local_version(skill, content_hash) == expected
with pytest.raises(WisdomConflict):
service.candidate_local_version(skill, "sha256:outdated")
def test_local_version_is_visible_without_claiming_a_published_version(sharing, monkeypatch):
from hermes_wisdom.consent import public_plan
service, mediation, _, shown, _, _, _ = sharing
monkeypatch.setattr(service, "candidate_local_version", lambda *_: "0.2.0")
with service.store.transaction() as db:
reference = json.loads(db.execute("SELECT reference_json FROM wisdom_assessment WHERE id=?", (shown["assessment_id"],)).fetchone()[0])
operation, plan = mediation.consent._plan(reference)
facts = public_plan(plan)
assert facts["local_version"] == "0.2.0"
assert "version" not in facts
interaction = {**shown, "operation": operation, "facts": facts}
assert "local v0.2.0" in interaction_view(interaction).items[0].title
view = advice_view([{"advice": {"title": "Notes", "explanation": "Refined skill", "relevance": "recommend", "assessment_kind": "qualification"}, "interaction": interaction}])
assert view.items[0].title == "Notes · local v0.2.0"
completed = {**interaction, "state": "completed", "result": {"packaging_state": "ready"}}
assert "local v0.2.0" in interaction_view(completed).items[0].title
class PublishingClient(FakeClient):
"""In-memory remote using the production CAS reconstruction path."""
def __init__(self):
super().__init__()
self.objects = {}
self.sync = SimpleNamespace(get_object=self.objects.__getitem__)
self.publications = 0
def upload_private_objects(self, objects):
self.objects.update(objects.objects)
self.uploaded += 1
def submit_draft(self, **payload):
from hermes_wisdom.client import _walk_private_commit
from hermes_wisdom.contract import author_description_hash, sha256_address
draft = super().submit_draft(**payload)
files = _walk_private_commit(self.sync, draft.draftCommit)
manifest = next(
body for path, _, body in files if path == "skill.manifest.json"
)
self.drafts[draft.id] = draft.model_copy(
update={
"orgId": "org",
"ownerUserId": self.identity["owner"],
"authorDescriptionHash": author_description_hash(
payload["description"]
),
"packageManifestHash": sha256_address(manifest),
}
)
return self.drafts[draft.id]
def reconstruct_draft(self, identity):
from hermes_wisdom.client import WisdomClient
return WisdomClient.reconstruct_draft(self, identity)
def approve(self, identity, **hashes):
draft = self.drafts[identity]
assert hashes == {
"content_hash": draft.contentHash,
"description_hash": draft.authorDescriptionHash,
"manifest_hash": draft.packageManifestHash,
}
self.drafts[identity] = draft.model_copy(update={"state": "owner_approved"})
return self.drafts[identity]
def publish(self, identity, *, content_hash):
assert self.drafts[identity].contentHash == content_hash
self.publications += 1
self.drafts[identity] = self.drafts[identity].model_copy(
update={"state": "published"}
)
return {"state": "published"}
@pytest.fixture
def sharing(staged, monkeypatch, request):
service, package, source, _ = staged
if getattr(request, "param", None) == "portal":
from hermes_wisdom.service import _source_fingerprint
(source / "references").rename(source / "refs")
package = package.model_copy(update={"source_content_hash": _source_fingerprint(source)})
service._client = PublishingClient()
monkeypatch.setattr("hermes_wisdom.mediation.delivery_mode", lambda: "agent")
service.store.activate_installation_identity("installation", "org")
monkeypatch.setattr(service, "require_setup", Mock())
skill = service.store.register_skill(
source, content_hash=package.source_content_hash, source_kind="local"
)
event = service.store.emit_local_event(
kind="wisdom.candidate",
skill_id=skill,
content_hash=package.source_content_hash,
payload={"skill_name": "notes"},
session_id="session",
task_id=None,
qualification="weekly_usage",
)
now = [1000.0]
mediation = WisdomMediation(service, clock=lambda: now[0])
actor = ConsentActor("session", "telegram", "owner", "chat", "thread")
register(mediation, actor)
identity = mediation.queue.enqueue(
"org",
f"candidate:{event}",
{
"kind": "candidate",
"event_id": event,
"content_hash": package.source_content_hash,
},
origin_session=actor.session_key,
)
job = mediation.queue.claim("org", actor.session_key)[0]
mediation.queue.save_advice(
"org",
identity,
job["lease_token"],
{
"title": "Useful team skill",
"explanation": "This may help your team.",
"relevance": "recommend",
},
)
shown = mediation.consent.present("org", identity, actor)
assert mediation.queue.begin_delivery("org", identity, job["lease_token"])
assert mediation.queue.complete_delivery(
"org", identity, job["lease_token"], receipt=RECEIPT
)
model = Mock(return_value=package)
monkeypatch.setattr("hermes_wisdom.share_queue.package_for_share", model)
return service, mediation, actor, shown, model, source, now
def register(mediation, actor, *, available=True):
mediation.queue.register_session(
"org",
session_key=actor.session_key,
session_id=actor.session_key,
actor_id=actor.actor_id,
platform=actor.platform,
private=True,
available=available,
user_activity=True,
address=actor.address,
)
@pytest.mark.parametrize("sharing", ["portal"], indirect=True)
def test_native_review_uploads_private_draft_and_preserves_link(sharing, monkeypatch):
from hermes_wisdom.mediation_view import resolve_surface_action
service, mediation, actor, shown, model, source, _ = sharing
monkeypatch.setattr("hermes_wisdom.mediation_view.WisdomConsent", lambda _: mediation.consent)
def click(action):
return resolve_surface_action(
service, f"wi:agent:{action}:{shown['id']}", platform=actor.platform,
actor_id=actor.actor_id, **actor.address,
)
# Existing cards still carry inspect; only the native handler treats it as review.
view = click("inspect")
assert service.client.uploaded == 1
assert service.client.publications == 0
assert any(a.label == "View Skill" and "/wisdom/review/draft-1" in a.url for a in view.actions)
assert view.actions[-1].label == "Yes, share"
assert "private draft is ready" in view.to_text()
current = mediation.consent.resolve("org", shown["id"], actor, "inspect")
assert current["operation"] == "publish" and current["state"] == "pending"
assert current["facts"]["hashes"]
for action in ("review", "checks.show", "checks.hide"):
toggled = click(action)
actions = toggled.actions + [a for item in toggled.items for a in item.actions]
assert any(a.label == "View Skill" and a.url for a in actions)
assert service.client.uploaded == 1
assert service.client.publications == 0
assert "ORIGINAL_PRIVATE_SETUP" in (source / "SKILL.md").read_text()
confirmed = mediation.consent.resolve("org", shown["id"], actor, "confirm")
assert confirmed["state"] == "completed"
assert service.client.publications == 1
@pytest.mark.parametrize("failure", ["actor", "expired", "source", "org"])
def test_portal_review_rejects_invalid_control_before_upload(sharing, failure):
service, mediation, actor, shown, _, source, now = sharing
if failure == "actor":
actor = ConsentActor(**{**actor.__dict__, "actor_id": "stranger"})
elif failure == "expired":
now[0] = shown["expires_at"] + 1
elif failure == "source":
(source / "SKILL.md").write_text("Changed since qualification")
else:
service.store.activate_installation_identity("installation", "other-org")
if failure == "expired":
result = mediation.consent.resolve("org", shown["id"], actor, "review")
assert result["state"] == "expired"
assert any(a.label == "Recheck" for a in interaction_view(result).actions)
else:
with pytest.raises((WisdomConflict, WisdomNotFound, ValueError)):
mediation.consent.resolve("org", shown["id"], actor, "review")
assert service.client.uploaded == service.client.publications == 0
@pytest.mark.parametrize("sharing", ["portal"], indirect=True)
def test_private_review_failure_keeps_card_retryable(sharing, monkeypatch):
service, mediation, actor, shown, _, _, _ = sharing
submit = service.client.submit_draft
monkeypatch.setattr(service.client, "submit_draft", Mock(side_effect=RuntimeError("offline")))
with pytest.raises(RuntimeError, match="offline"):
mediation.consent.resolve("org", shown["id"], actor, "review")
current = mediation.consent._resolve("org", shown["id"], actor, "inspect")
assert current["state"] == "pending" and current["result"] is None
monkeypatch.setattr(service.client, "submit_draft", submit)
current = mediation.consent.resolve("org", shown["id"], actor, "review")
assert current["result"]["portal_url"]
assert service.client.publications == 0
def test_share_is_native_local_preparation_then_separate_exact_publication(sharing):
service, mediation, actor, shown, model, source, _ = sharing
assert shown["operation"] == "share"
assert (
mediation.consent.resolve("org", shown["id"], actor, "inspect")["operation"]
== "share"
)
model.assert_not_called()
assert (
service.store.latest_draft_for_source(
shown["facts"]["skill_id"],
service._candidate_event_context(
mediation.queue.assessments("org")[0]["reference"]["event_id"]
)[2],
)
is None
)
first = mediation.consent.resolve("org", shown["id"], actor, "confirm")
repeat = mediation.consent.resolve("org", shown["id"], actor, "confirm")
assert first["result"] == repeat["result"]
assert first["result"]["packaging_state"] == "queued"
receipt = interaction_view(first)
assert receipt.summary == "Preparing to share"
assert "Security check" not in receipt.to_text()
assert "Professionalism" not in receipt.to_text()
assert receipt.actions[0].label == "View"
assert receipt.actions[0].callback_data == f"wi:agent:inspect:{shown['id']}"
assert mediation.consent.resolve("org", shown["id"], actor, "inspect")["result"]["packaging_state"] == "queued"
assert len(mediation.queue.assessments("org")) == 2
model.assert_not_called()
assert service.client.uploaded == 0
no_assessment = Mock(side_effect=AssertionError("must reuse packaging result"))
items = mediation.prepare(
"org",
actor,
runtime={"model": "selected", "provider": "chosen"},
history=[],
assessor=no_assessment,
)
assert len(items) == 1
final = items[0]["interaction"]
assert final["operation"] == "publish" and final["id"] != shown["id"]
assert "refs/wisdom-setup.md" in final["facts"]["file_names"]
assert service.client.uploaded == 0 and model.call_count == 1
reopened = mediation.consent.resolve("org", shown["id"], actor, "inspect")
assert reopened["id"] == final["id"] and "inspection" in reopened
assert service.client.uploaded == service.client.publications == 0
wrong = ConsentActor(**{**actor.__dict__, "actor_id": "stranger"})
with pytest.raises(WisdomNotFound):
mediation.consent.resolve("org", shown["id"], wrong, "inspect")
assert "ORIGINAL_PRIVATE_SETUP" in (source / "SKILL.md").read_text()
assert "package" not in mediation.activity().get("assessments", [{}])[-1].get(
"reference", {}
)
result = mediation.consent.resolve("org", final["id"], actor, "confirm")
assert result["state"] == "completed", result
assert service.client.uploaded == 1
assert service.client.publications == 1
receipt = interaction_view(result)
assert receipt.summary == "Published"
reopened = mediation.consent.resolve("org", shown["id"], actor, "inspect")
assert reopened["id"] == final["id"] and reopened["state"] == "completed"
assert interaction_view(reopened).actions[0].url
assert result["result"]["draft_id"] == "draft-1"
assert result["result"]["owner_user_id"] == service.client.identity["owner"]
assert "confirmation control" not in receipt.to_text()
assert "check" not in receipt.to_text().lower()
assert (
mediation.consent.resolve("org", final["id"], actor, "confirm")["state"]
== "completed"
)
assert service.client.publications == 1
assert "ORIGINAL_PRIVATE_SETUP" not in json.dumps(service.client.submissions)
@pytest.mark.parametrize("field", ["actor_id", "session_key", "chat_id", "platform"])
def test_wrong_actor_cannot_queue_packaging(sharing, field):
_, mediation, actor, shown, model, _, _ = sharing
wrong = ConsentActor(**{**actor.__dict__, field: "other"})
with pytest.raises(WisdomNotFound):
mediation.consent.resolve("org", shown["id"], wrong, "confirm")
assert len(mediation.queue.assessments("org")) == 1
model.assert_not_called()
def test_packaging_waits_for_owning_session_safe_boundary(sharing):
service, mediation, actor, shown, model, _, _ = sharing
mediation.consent.resolve("org", shown["id"], actor, "confirm")
register(mediation, actor, available=False)
assert mediation.prepare("org", actor, runtime={"model": "test-model", "provider": "test-provider"}, history=[]) == []
other = ConsentActor("other", "slack", "other-user", "different")
register(mediation, other)
assert mediation.prepare("org", other, runtime={"model": "test-model", "provider": "test-provider"}, history=[]) == []
assert service.client.uploaded == 0
model.assert_not_called()
def test_packaging_retries_resume_persisted_model_output(sharing, monkeypatch):
service, mediation, actor, shown, model, _, now = sharing
mediation.consent.resolve("org", shown["id"], actor, "confirm")
prepare = service.prepare_share_package
monkeypatch.setattr(
service, "prepare_share_package", Mock(side_effect=OSError("disk busy"))
)
assert mediation.prepare("org", actor, runtime={"model": "test-model", "provider": "test-provider"}, history=[]) == []
assert model.call_count == 1
monkeypatch.setattr(service, "prepare_share_package", prepare)
now[0] += 61
register(mediation, actor)
items = mediation.prepare("org", actor, runtime={"model": "test-model", "provider": "test-provider"}, history=[])
assert items[0]["interaction"]["operation"] == "publish"
assert model.call_count == 1 and service.client.uploaded == 0
def test_source_change_prevents_packaging_and_upload(sharing):
service, mediation, actor, shown, model, source, _ = sharing
mediation.consent.resolve("org", shown["id"], actor, "confirm")
(source / "SKILL.md").write_text("different")
assert mediation.prepare("org", actor, runtime={"model": "test-model", "provider": "test-provider"}, history=[]) == []
model.assert_not_called()
assert service.client.uploaded == 0
def test_superseded_model_owner_cannot_write_a_proposal(sharing):
service, mediation, actor, shown, model, _, now = sharing
mediation.consent.resolve("org", shown["id"], actor, "confirm")
package = model.return_value
def expire(*args, **kwargs):
now[0] += 181
return package
model.side_effect = expire
assert mediation.prepare("org", actor, runtime={"model": "test-model", "provider": "test-provider"}, history=[]) == []
row = mediation.queue.assessments("org")[-1]
assert "package" not in row["reference"]
assert not (service.store.root / "share-staging").exists()
assert service.client.uploaded == 0
def test_changed_prepared_bytes_are_not_uploaded_from_old_consent(sharing):
service, mediation, actor, shown, _, _, _ = sharing
mediation.consent.resolve("org", shown["id"], actor, "confirm")
item = mediation.prepare("org", actor, runtime={"model": "test-model", "provider": "test-provider"}, history=[])[0]
draft = service.store.draft(item["assessment"]["reference"]["prepared_draft_id"])
from pathlib import Path
(Path(draft["overlay_path"]) / "SKILL.md").write_text("different")
result = mediation.consent.resolve(
"org", item["interaction"]["id"], actor, "confirm"
)
assert result["state"] in {"stale", "needs_review"}
assert service.client.uploaded == 0
def test_share_copy_and_controls_keep_publication_separate(sharing):
_, _, _, shown, _, _, _ = sharing
view = interaction_view(shown)
assert [action.label for action in view.actions] == [
"Show checks",
"Not Now",
"Review first",
"Share",
]
assert "Nothing is shared without your approval" not in view.to_text()
assert view.items[0].detail.rstrip().endswith("Would you like to share it?")
view = advice_view([
{
"advice": {
"title": "Skill",
"explanation": "Useful",
"relevance": "recommend",
},
"interaction": shown,
}
])
assert "You can review the skill before publishing" not in view.to_text()
assert view.items[0].detail.rstrip().endswith("Would you like to share it?")
assert "handoff package" not in view.to_text()
assert "✅ Security check (local preflight)" in view.to_text()
assert "will be scanned" not in view.to_text()
expanded = advice_view([
{"advice": {"title": "Skill", "explanation": "Useful", "relevance": "recommend"},
"interaction": shown}
], checks_expanded=True)
assert "✅ Private keys" in expanded.to_text()
assert "✅ Harmful instruction patterns" in expanded.to_text()
assert "Pending" not in expanded.to_text()
def test_checks_toggle_is_read_only_and_preserves_consent(sharing, monkeypatch):
from hermes_wisdom.mediation_view import resolve_surface_action
from hermes_wisdom.client import WisdomNotFound
service, mediation, actor, shown, model, _, _ = sharing
monkeypatch.setattr("hermes_wisdom.mediation_view.WisdomConsent", lambda service: mediation.consent)
with service.store.transaction() as db:
row = db.execute(
"SELECT plan_json FROM wisdom_consent WHERE id=?", (shown["id"],)
).fetchone()
plan = json.loads(row[0])
plan["professionalism_check"] = {
"status": "advisory",
"summary": "Check the wording.",
"checks": [
{
"key": "profanity_or_abuse",
"status": "advisory",
"finding_count": 1,
"details": ["Check the wording."],
}
],
}
db.execute(
"UPDATE wisdom_consent SET plan_json=? WHERE id=?",
(json.dumps(plan), shown["id"]),
)
def toggle(action, user=actor.actor_id):
return resolve_surface_action(
service,
f"wi:agent:checks.{action}:{shown['id']}",
platform=actor.platform,
actor_id=user,
chat_id=actor.chat_id,
thread_id=actor.thread_id,
)
expanded = toggle("show")
assert "Profanity or abusive language" in expanded.to_text()
assert "Check the wording." in expanded.to_text()
assert expanded.items[0].actions[0].label == "Hide checks"
collapsed = toggle("hide")
assert "Profanity or abusive language" not in collapsed.to_text()
assert "Needs a look before sharing at work" in collapsed.to_text()
assert "Check the wording." not in collapsed.to_text()
assert [a.label for a in collapsed.items[0].actions] == [
"Show checks",
"Not Now",
"Review first",
"Share",
]
with pytest.raises(WisdomNotFound):
toggle("show", "different-user")
model.assert_not_called()
assert (
mediation.consent.resolve("org", shown["id"], actor, "inspect")["state"]
== "pending"
)
def test_stale_checks_toggle_does_not_restore_actionable_advice(sharing):
from hermes_wisdom.mediation_view import resolve_surface_action
service, _, actor, shown, model, _, _ = sharing
with service.store.transaction() as db:
db.execute("UPDATE wisdom_consent SET state='stale' WHERE id=?", (shown["id"],))
for mode in ("show", "hide"):
view = resolve_surface_action(
service, f"wi:agent:checks.{mode}:{shown['id']}",
platform=actor.platform, actor_id=actor.actor_id,
chat_id=actor.chat_id, thread_id=actor.thread_id,
)
assert view.summary == "Stale"
assert len(view.actions) == 2
assert view.actions[-1].label == "Recheck"
assert view.actions[0].label == ("Hide checks" if mode == "show" else "Show checks")
assert ("Private keys" in view.to_text()) == (mode == "show")
assert "Pass" not in view.to_text()
assert not any(action.primary for action in view.actions)
model.assert_not_called()
@pytest.mark.parametrize("operation", ["install", "update"])
def test_install_update_review_collapses_rows_without_hiding_warnings(sharing, operation):
_, _, _, shown, _, _, _ = sharing
shown = {**shown, "operation": operation, "facts": {**shown["facts"],
"security_check": {"status": "advisory", "summary": "Review the policy finding.",
"checks": [{"label": "Organization policy", "status": "advisory"}]}}}
collapsed = interaction_view(shown)
assert "⚠️ Security check: Advisory" in collapsed.to_text()
assert "Review the policy finding." in collapsed.to_text()
assert "Organization policy" not in collapsed.to_text()
assert collapsed.actions[0].label == "Show checks"
assert collapsed.actions[-1].primary
expanded = interaction_view(shown, checks_expanded=True)
assert "⚠️ Organization policy: Advisory" in expanded.to_text()
assert expanded.actions[0].label == "Hide checks"
def test_private_review_pages_cover_exact_files_without_consuming_consent(sharing):
service, mediation, actor, shown, _, _, _ = sharing
mediation.consent.resolve("org", shown["id"], actor, "confirm")
item = mediation.prepare("org", actor, runtime={"model": "test-model", "provider": "test-provider"}, history=[])[0]
identity = item["interaction"]["id"]
first = mediation.consent.resolve("org", identity, actor, "inspect")
assert first["facts"]["editorial_name"] == "Release Notes"
seen = {}
for page in range(first["inspection"]["page_count"]):
result = mediation.consent.resolve("org", identity, actor, f"inspect.{page}")
inspection = result["inspection"]
seen[inspection["path"]] = (
seen.get(inspection["path"], "") + inspection["content"]
)
assert result["state"] == "pending"
assert len(inspection["content"]) <= 1000
view = interaction_view(result)
assert view.actions[-1].primary
assert view.actions[-1].callback_data == f"wi:agent:confirm:{identity}"
assert f"/wisdom consent {identity} confirm" in view.to_local_text()
prepared = service.prepare_candidate(item["assessment"]["reference"]["event_id"])[
"prepared"
]
assert seen.pop("Author description") == prepared["drafted_description"]
assert seen == {file["path"]: file["content_utf8"] for file in prepared["files"]}
assert service.client.uploaded == service.client.publications == 0
assert all(
"inspection" not in interaction
for interaction in mediation.activity()["interactions"]
)
wrong = ConsentActor(**{**actor.__dict__, "actor_id": "stranger"})
with pytest.raises(WisdomNotFound):
mediation.consent.resolve("org", identity, wrong, "inspect.1")
with pytest.raises(WisdomNotFound):
mediation.consent.resolve("org", identity, actor, "inspect.999")
@pytest.mark.parametrize("control", ["Back to first page", "Not Now"])
def test_package_review_controls_never_upload_and_preserve_review(sharing, monkeypatch, control):
from hermes_wisdom.mediation_view import resolve_surface_action
service, mediation, actor, shown, model, _, _ = sharing
service.client.display_org_id = "org"
monkeypatch.setattr("hermes_wisdom.mediation_view.WisdomConsent", lambda _: mediation.consent)
mediation.consent.resolve("org", shown["id"], actor, "confirm")
item = mediation.prepare(
"org", actor, runtime={"model": "test-model", "provider": "test-provider"}, history=[]
)[0]
identity = item["interaction"]["id"]
reviewed = mediation.consent.resolve("org", identity, actor, "inspect.1")
view = interaction_view(reviewed)
selected = next(
action for action in view.actions + view.navigation_actions if action.label == control
)
with pytest.raises(WisdomNotFound):
resolve_surface_action(
service, selected.callback_data, platform=actor.platform,
actor_id="stranger", **actor.address,
)
returned = resolve_surface_action(
service, selected.callback_data, platform=actor.platform,
actor_id=actor.actor_id, **actor.address,
)
assert service.client.uploaded == service.client.publications == 0
if control == "Not Now":
assert returned.summary == "Deferred on this surface"
assert not any(action.primary for action in returned.actions)
with service.store.transaction() as db:
assert db.execute(
"SELECT interaction_id FROM wisdom_consent_defer WHERE interaction_id=?", (identity,)
).fetchone()[0] == identity
else:
assert returned.summary.endswith("1/" + str(reviewed["inspection"]["page_count"]))
reopened = mediation.consent.resolve("org", identity, actor, "inspect.0")
assert reopened["state"] == "pending"
assert reopened["facts"]["hashes"] == reviewed["facts"]["hashes"]
assert reopened["inspection"]["page"] == 0
model.assert_called_once()
assert service.client.uploaded == service.client.publications == 0
result = mediation.consent.resolve("org", identity, actor, "confirm")
assert result["state"] == "completed"
assert service.client.uploaded == service.client.publications == 1
@pytest.mark.parametrize(
"publication,title",
[("published", "Published"), ("pending_moderation", "Pending moderation")],
)
def test_publication_receipt_links_to_portal_without_expanding_checks(
publication, title
):
view = interaction_view({
"state": "completed",
"operation": "publish",
"facts": {"editorial_name": "Skill"},
"result": {
"publication_state": publication,
"portal_url": "https://portal.example/review/draft",
},
})
assert view.summary == title
assert len(view.actions) == 1
assert view.actions[0].label == "View in Portal"
assert view.actions[0].url == "https://portal.example/review/draft"
@pytest.mark.parametrize("operation,title", [("install", "Files installed"), ("update", "Files updated")])
def test_install_and_update_receipts_are_compact(operation, title):
view = interaction_view({
"id": "consent",
"state": "completed",
"operation": operation,
"facts": {"editorial_name": "Release Evidence Brief"},
"result": {},
})
assert view.summary == title
assert view.items[0].title == "Release Evidence Brief"
assert "Prerequisites and verification must pass" in view.items[0].detail
assert [a.label for a in view.actions] == ["Check setup", "View Assessment"]
def test_packaging_prompt_contains_full_schema(sharing):
from hermes_wisdom.agent_led.agent import package_for_share
service, _, _, shown, model, _, _ = sharing
package = model.return_value
def call(messages, schema):
assert (
json.loads(messages[0]["content"].split("this exact schema:\n", 1)[1])
== schema
)
assert "PackagedFile" in messages[0]["content"]
return package.model_dump_json()
assert package_for_share({}, model_call=call) == package
def test_packaging_failure_eventually_offers_manual_review_not_publication(sharing):
service, mediation, actor, shown, model, _, now = sharing
model.side_effect = TimeoutError
mediation.consent.resolve("org", shown["id"], actor, "confirm")
for _ in range(3):
register(mediation, actor)
assert mediation.prepare("org", actor, runtime={"model": "test-model", "provider": "test-provider"}, history=[]) == []
now[0] += 61
register(mediation, actor)
items = mediation.prepare("org", actor, runtime={"model": "test-model", "provider": "test-provider"}, history=[])
assert len(items) == 1 and items[0]["interaction"] is None
assert "Nothing was uploaded or published" in items[0]["advice"]["explanation"]
assert model.call_count == 3 and service.client.uploaded == 0
job = items[0]["assessment"]
assert mediation.queue.begin_delivery("org", job["id"], job["lease_token"])
assert mediation.queue.complete_delivery(
"org", job["id"], job["lease_token"], receipt=RECEIPT
)
assert mediation.prepare("org", actor, runtime={"model": "test-model", "provider": "test-provider"}, history=[]) == []
def test_private_review_escapes_terminal_controls_before_pagination(sharing):
service, mediation, actor, shown, model, _, _ = sharing
package = model.return_value
package.files[0].content += "\n" + "\x1b[2J" * 350
mediation.consent.resolve("org", shown["id"], actor, "confirm")
item = mediation.prepare("org", actor, runtime={"model": "test-model", "provider": "test-provider"}, history=[])[0]
identity = item["interaction"]["id"]
first = mediation.consent.resolve("org", identity, actor, "inspect")
contents = []
for page in range(first["inspection"]["page_count"]):
result = mediation.consent.resolve("org", identity, actor, f"inspect.{page}")
content = result["inspection"]["content"]
assert len(content) <= 1000
assert "\x1b" not in content
contents.append(content)
assert "\\u001b[2J" in "".join(contents)
assert service.client.uploaded == 0
def test_share_model_cannot_return_a_tool_call(monkeypatch):
from hermes_wisdom.agent_led.agent import session_model_call
call = Mock(
return_value=SimpleNamespace(
choices=[SimpleNamespace(message=SimpleNamespace(tool_calls=[{}]))]
)
)
monkeypatch.setattr("agent.auxiliary_client.call_llm", call)
runtime = {"provider": "chosen", "model": "session-model"}
with pytest.raises(ValueError, match="disallowed tools"):
session_model_call(runtime, name="wisdom_share_packaging")([], {})
assert call.call_args.kwargs["main_runtime"] is runtime
assert call.call_args.kwargs["tools"] == []
assert "task" not in call.call_args.kwargs
with pytest.raises(ValueError, match="active session model"):
session_model_call({}, name="wisdom_share_packaging")([], {})
def test_consent_expiring_during_review_cannot_upload(sharing, monkeypatch):
service, mediation, actor, shown, _, _, now = sharing
mediation.consent.resolve("org", shown["id"], actor, "confirm")
item = mediation.prepare("org", actor, runtime={"model": "test-model", "provider": "test-provider"}, history=[])[0]
final = item["interaction"]
def slow_review(**kwargs):
now[0] = final["expires_at"] + 1
return {"status": "unavailable"}
monkeypatch.setattr(service, "_require_professionalism_review", slow_review)
result = mediation.consent.resolve("org", final["id"], actor, "confirm")
assert result["state"] == "stale"
assert service.client.uploaded == 0