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

234 lines
12 KiB
Python

import argparse
import json
import os
import sys
from pathlib import Path
import pytest
from gateway.session_context import clear_session_vars, set_session_vars
from hermes_cli.subcommands.wisdom import build_wisdom_parser, cmd_wisdom
from hermes_wisdom.agent_led.schemas import SharePackage
from hermes_wisdom.agent_led.setup_document import SETUP_PATH, parse_setup_document
from hermes_wisdom.agent_led.share_flow import normalize_generated_package
from hermes_wisdom.installed_setup import inspect_installed_setup
from hermes_wisdom.mediation import WisdomMediation
from hermes_wisdom.package import PackagePolicyError
from hermes_wisdom.service import WisdomService
from hermes_wisdom.store import WisdomStore
from tests.wisdom.test_service import InstallClient, _install_service
from tests.wisdom.entitlement_fixtures import authorized_wisdom_token_fixture
from tools import wisdom_tool
from tools.registry import registry
@pytest.fixture
def installed(tmp_path, monkeypatch):
authorized_wisdom_token_fixture(monkeypatch)
client = InstallClient()
service = _install_service(monkeypatch, tmp_path, client=client)
monkeypatch.setattr("hermes_wisdom.consumption.get_skills_dir", lambda: tmp_path / "skills")
sentinel = tmp_path / "must-not-execute"
package = SharePackage.model_validate({
"skill_name": "managed-skill",
"source_content_hash": "sha256:source",
"editorial_name": "Managed skill",
"plain_description": "A setup inspection fixture.",
"files": [{"path": "SKILL.md", "content": "# Managed\n"}],
"requirements": [
{"kind": "env_var", "name": "WISDOM_FIXTURE_CREDENTIAL", "purpose": "Authenticate the example service"},
{"kind": "command", "name": sys.executable, "purpose": "Run the example"},
{"kind": "account", "name": "example-account", "purpose": "User-managed example account"},
],
"setup_instructions": ["Connect your example account."],
"credential_handoff": ["Configure WISDOM_FIXTURE_CREDENTIAL privately."],
"verification_step": f"touch {sentinel}",
})
normalized = normalize_generated_package(package)
setup = next(file.content for file in normalized.files if file.path == SETUP_PATH)
client.files.append((SETUP_PATH, "file", setup.encode()))
plan = service.install_plan("skill-1")
outcome = service.install_apply(plan["receipt"])
assert outcome["installed"] is True
monkeypatch.setattr("hermes_wisdom.service._config", lambda: {
"enabled": True, "disclosure_acknowledged_at": "test", "delivery_mode": "agent",
})
monkeypatch.setattr("hermes_wisdom.mediation.delivery_mode", lambda *args: "agent")
monkeypatch.setattr("hermes_cli.config.get_env_value", lambda name: None)
monkeypatch.setattr("subprocess.run", lambda *args, **kwargs: pytest.fail("inspection must not execute commands"))
for method in ("skill", "version", "content", "record_install"):
monkeypatch.setattr(client, method, lambda *args, **kwargs: pytest.fail("inspection must not contact Gateway"))
return service, tmp_path, sentinel, package
def test_installed_guidance_survives_restart_without_executing_or_claiming_ready(installed, monkeypatch, capsys):
service, root, sentinel, package = installed
tokens = set_session_vars(platform="telegram", chat_type="dm", chat_id="chat", user_id="owner", session_key="private")
try:
monkeypatch.setattr("hermes_wisdom.service.WisdomService", lambda: service)
result = json.loads(registry.dispatch("wisdom_inspect", {"kind": "installed", "identity": "skill-1", "version": 1}))
assert result["files_installed"] is True
assert result["ready_to_use"] is None and result["execution_authorized"] is False
assert result["state"] == "setup_required"
assert [item["status"] for item in result["prerequisites"]] == ["missing", "present", "manual"]
assert result["guidance"]["verification_step"] == package.verification_step
assert result["guidance"]["setup_instructions"] == package.setup_instructions
inbox = WisdomMediation(service).activity()
assert inbox["installed_setup"][0]["version"] == 1
assert "WISDOM_FIXTURE_CREDENTIAL" not in json.dumps(inbox)
restarted = WisdomService(store=WisdomStore(root / "state"), client=service.client)
monkeypatch.setattr("hermes_wisdom.service.WisdomService", lambda: restarted)
secret = "a-private-value-that-must-not-appear"
monkeypatch.setattr("hermes_cli.config.get_env_value", lambda name: secret if name == "WISDOM_FIXTURE_CREDENTIAL" else None)
parser = argparse.ArgumentParser()
build_wisdom_parser(parser.add_subparsers())
args = parser.parse_args(["wisdom", "installed-setup", "skill-1", "--version", "1", "--json"])
assert cmd_wisdom(args) == 0
stdout = capsys.readouterr().out
resumed = json.loads(stdout)
assert resumed["content_hash"] == result["content_hash"]
assert resumed["prerequisites"][0]["status"] == "present"
assert resumed["verification"] == {"state": "not_recorded"}
assert secret not in stdout and not sentinel.exists()
assert service.store.pending_operations() == []
finally:
clear_session_vars(tokens)
@pytest.mark.parametrize("change", ["bytes", "version", "org", "inactive", "pending", "symlink", "hardlink", "extra_directory", "group"])
def test_installed_setup_refuses_stale_or_unowned_context(installed, monkeypatch, change):
service, root, sentinel, _package = installed
row = service.store.installation("skill-1")
target = Path(row["target_path"])
if change == "bytes":
(target / "SKILL.md").write_text("# Edited\n")
elif change == "version":
service.store.record_install({**row, "version": 2})
elif change == "org":
service.store.verify_installation_identity("another-org")
elif change == "inactive":
service.store.deactivate_install("skill-1")
elif change == "pending":
service.store.journal("install", "skill-1", "local_ledger_committed", {})
elif change == "symlink":
file = target / SETUP_PATH
outside = root / "outside.md"
file.rename(outside)
file.symlink_to(outside)
elif change == "extra_directory":
(target / "refs" / "not-in-the-installed-package").mkdir()
elif change == "hardlink":
os.link(target / SETUP_PATH, root / "linked-setup.md")
if change == "group":
tokens = set_session_vars(platform="slack", chat_type="group", chat_id="group", user_id="member", session_key="shared")
try:
monkeypatch.setattr("hermes_wisdom.service.WisdomService", lambda: service)
result = registry.dispatch("wisdom_inspect", {"kind": "installed", "identity": "skill-1", "version": 1})
assert "private conversation" in result and "WISDOM_FIXTURE_CREDENTIAL" not in result
inbox = registry.dispatch("wisdom_inbox", {})
assert "private conversation" in inbox and "installed_setup" not in inbox
finally:
clear_session_vars(tokens)
else:
with pytest.raises(PackagePolicyError):
inspect_installed_setup(service.store, "skill-1", version=1)
assert not sentinel.exists()
@pytest.mark.macos_only
def test_setup_inspection_rejects_executable_mode_on_macos(installed):
_assert_executable_setup_rejected(installed)
@pytest.mark.linux_only
def test_setup_inspection_rejects_executable_mode_on_linux(installed):
_assert_executable_setup_rejected(installed)
def _assert_executable_setup_rejected(installed):
service, _root, sentinel, _package = installed
setup = Path(service.store.installation("skill-1")["target_path"]) / SETUP_PATH
setup.chmod(setup.stat().st_mode | 0o100)
with pytest.raises(PackagePolicyError, match="executable"):
inspect_installed_setup(service.store, "skill-1", version=1)
assert not sentinel.exists()
def test_setup_inspection_rejects_file_replaced_before_open(installed, monkeypatch):
service, root, sentinel, _package = installed
setup = Path(service.store.installation("skill-1")["target_path"]) / SETUP_PATH
replacement = root / "replacement.md"
replacement.write_bytes(setup.read_bytes())
original_open = os.open
def swapped_open(path, flags, *args, **kwargs):
return original_open(replacement if path == setup else path, flags, *args, **kwargs)
monkeypatch.setattr(os, "open", swapped_open)
with pytest.raises(PackagePolicyError, match="changed during inspection"):
inspect_installed_setup(service.store, "skill-1", version=1)
assert not sentinel.exists()
def test_setup_document_preserves_existing_wire_bytes_and_rejects_repair(installed):
_service, _root, _sentinel, package = installed
from hermes_wisdom.contract import canonical_json_bytes
keys = {"requirements", "setup_instructions", "credential_handoff", "compatibility_limits", "verification_step", "removed_or_generalized", "related_skills"}
original = (
"# Setup and portability\n\nInstalling files does not authorize executing these instructions.\n\n```json\n"
+ canonical_json_bytes({"schema_version": 1, "execution_requires_user_approval": True, **package.model_dump(mode="json", include=keys)}).decode()
+ "\n```\n"
).encode()
normalized = normalize_generated_package(package)
encoded = next(file.content.encode() for file in normalized.files if file.path == SETUP_PATH)
assert encoded == original
assert parse_setup_document(original).verification_step == package.verification_step
for bad in (original + b"execute extra", original.replace(b'"schema_version":1', b'"schema_version":2'), original.replace(b'"execution_requires_user_approval":true', b'"execution_requires_user_approval":false')):
with pytest.raises(ValueError):
parse_setup_document(bad)
with pytest.raises(ValueError):
wisdom_tool.Presentation.model_validate({"kind": "installed", "identity": "skill-1", "title": "Run", "explanation": "Not an installation consent"})
@pytest.mark.parametrize("guidance", ["valid", "missing", "invalid"])
def test_real_update_replaces_setup_reference_without_inventing_verification(installed, guidance):
from hermes_wisdom.consumption import WisdomConsumption
from tests.wisdom.test_consumption import Client
service, _root, sentinel, package = installed
before = inspect_installed_setup(service.store, "skill-1", version=1)
target = Path(service.store.installation("skill-1")["target_path"])
revised = package.model_copy(update={
"requirements": [], "setup_instructions": [], "credential_handoff": [],
"verification_step": "Review the second version with the user.",
})
setup = next(file.content.encode() for file in normalize_generated_package(revised).files if file.path == SETUP_PATH)
if guidance == "invalid":
setup = setup.replace(b'"execution_requires_user_approval":true', b'"execution_requires_user_approval":false')
files = [
("SKILL.md", "file", b"# Second version\n"),
("skill.manifest.json", "file", (target / "skill.manifest.json").read_bytes()),
]
if guidance != "missing":
files.append((SETUP_PATH, "file", setup))
manager = WisdomConsumption(store=service.store, client=Client(files, mode="MANUAL"), scan=lambda path: {
"guard": {"allowed": True, "findings": [], "reason": None},
"skill_evaluator": {"status": "disabled", "findings": []},
}, config={})
plan = manager.update_plan("skill-1")
manager.update_apply(plan["receipt"])
with pytest.raises(PackagePolicyError, match="version changed"):
inspect_installed_setup(service.store, "skill-1", version=1)
after = inspect_installed_setup(service.store, "skill-1", version=2)
assert after["content_hash"] != before["content_hash"]
assert after["ready_to_use"] is None and after["execution_authorized"] is False
assert after["verification"] == {"state": "not_recorded"}
if guidance == "valid":
assert after["state"] == "verification_required"
assert after["guidance"]["verification_step"] == revised.verification_step
else:
assert after["state"] == "guidance_unavailable" and after["guidance"] is None
assert not sentinel.exists()