test_profiles.py
python
sha256:c4c154d26740ebed7e38471f96d2f3eadd64677fa3d8ad35a2a2e0593e0f9bfd
fix(profiles): sigil dots reflect activity — repositories p…
Opus 5.5
patch
1 day ago
| 1 | """DOC_PRF — /muse/profiles contract (musehub#256, QA contract v2). |
| 2 | |
| 3 | Every claim below was checked against musehub ``dev`` 2978eb11 and muse 0.2.1rc20, partly in-process against a |
| 4 | private disposable Postgres (the probes are not part of this suite). The page's figure and JSON examples are |
| 5 | computed by the server's own code (``docs_profiles_data``); these tests re-derive each one from the code the |
| 6 | page documents, so a change to either side fails here. Known product defects stay documented as contract plus |
| 7 | warning (#241 defect-preservation rule): each is pinned by a strict xfail that flips when the defect is fixed, |
| 8 | so the warning must be removed in the same change. |
| 9 | |
| 10 | DOC_PRF_01 (commands parse), _02 (anchors) and _03 (URL scheme) are the #242 checkers (test_doc_inf_cli.py, |
| 11 | test_doc_inf_registry.py, test_doc_inf_scheme.py). No database is used. |
| 12 | """ |
| 13 | |
| 14 | from __future__ import annotations |
| 15 | |
| 16 | import ast |
| 17 | import asyncio |
| 18 | import hashlib |
| 19 | import html as html_lib |
| 20 | import inspect |
| 21 | import json |
| 22 | import re |
| 23 | from datetime import datetime, timedelta, timezone |
| 24 | from pathlib import Path |
| 25 | |
| 26 | import pytest |
| 27 | |
| 28 | from musehub.api.routes.musehub import docs_profiles_data as data |
| 29 | from musehub.models.musehub import OrgManifest, ProfileManifest, TrustChainEntry |
| 30 | from musehub.services import musehub_mpay, spectral_sigil |
| 31 | from tests.docs_contract import registry_check as rc |
| 32 | |
| 33 | pytestmark = pytest.mark.no_db |
| 34 | |
| 35 | PAGE = rc.phase_path("profiles") |
| 36 | ROOT = Path(__file__).resolve().parents[2] |
| 37 | HUB_ISSUES = "https://staging.musehub.ai/gabriel/musehub/issues/" |
| 38 | MUSE_ISSUES = "https://staging.musehub.ai/gabriel/muse/issues/" |
| 39 | |
| 40 | _T_DESIGN = "5" # profile design target (open) |
| 41 | _T_MODEL_FIX = "132" # agent_model staleness (closed) |
| 42 | _T_MPAY_CLI = "165" # muse sign payment (gabriel/muse) |
| 43 | |
| 44 | _ARCHETYPES = ("human", "agent", "org") |
| 45 | |
| 46 | |
| 47 | @pytest.fixture(scope="module") |
| 48 | def html(rendered: dict[str, str]) -> str: |
| 49 | return html_lib.unescape(rendered[PAGE]) |
| 50 | |
| 51 | |
| 52 | @pytest.fixture(scope="module") |
| 53 | def text(html: str) -> str: |
| 54 | return " ".join(re.sub(r"<[^>]+>", "", html).split()) |
| 55 | |
| 56 | |
| 57 | def _after_id(html: str, anchor: str) -> str: |
| 58 | """The page source from the element carrying ``id="<anchor>"`` onwards.""" |
| 59 | return html.split(f'id="{anchor}"', 1)[1] |
| 60 | |
| 61 | |
| 62 | def _table_rows(fragment: str) -> list[list[str]]: |
| 63 | """Cell texts of the first table in ``fragment``.""" |
| 64 | table = fragment.split("<table", 1)[1].split("</table>", 1)[0] |
| 65 | rows = [] |
| 66 | for tr in re.findall(r"<tr[^>]*>(.*?)</tr>", table, flags=re.S): |
| 67 | cells = re.findall(r"<t[dh][^>]*>(.*?)</t[dh]>", tr, flags=re.S) |
| 68 | rows.append([" ".join(re.sub(r"<[^>]+>", "", c).split()) for c in cells]) |
| 69 | return rows |
| 70 | |
| 71 | |
| 72 | def _pre_after(html: str, label: str) -> str: |
| 73 | rest = html.split(label, 1)[1] |
| 74 | return re.sub(r"<[^>]+>", "", rest.split("<pre>", 1)[1].split("</pre>", 1)[0]) |
| 75 | |
| 76 | |
| 77 | def _first(pattern: str, text: str) -> str: |
| 78 | """Group 1 of the first match of ``pattern`` in ``text``; the match must exist.""" |
| 79 | match = re.search(pattern, text) |
| 80 | assert match is not None, pattern |
| 81 | return match.group(1) |
| 82 | |
| 83 | |
| 84 | def _route_pairs(router: object, only: str | None = None) -> set[tuple[str, str]]: |
| 85 | """(method, normalised path) of a router's routes, optionally only the route whose path is ``only``.""" |
| 86 | pairs: set[tuple[str, str]] = set() |
| 87 | for route in getattr(router, "routes", []): |
| 88 | path = str(getattr(route, "path", "")) |
| 89 | if only is None or path == only: |
| 90 | pairs |= {(m, _norm(path)) for m in getattr(route, "methods", None) or ()} |
| 91 | return pairs |
| 92 | |
| 93 | |
| 94 | def _aliases(model: type) -> set[str]: |
| 95 | return {f.alias or n for n, f in model.model_fields.items()} # type: ignore[attr-defined] |
| 96 | |
| 97 | |
| 98 | # ── DOC_PRF_04: the manifest examples are the model, serialised the way FastAPI does ──────────────────────────── |
| 99 | |
| 100 | |
| 101 | @pytest.mark.parametrize("archetype", _ARCHETYPES) |
| 102 | def test_manifest_example_is_the_model(html: str, archetype: str) -> None: |
| 103 | shown = json.loads(_pre_after(html, {"human": "human profile manifest", "agent": "agent manifest — trust chain", |
| 104 | "org": "<span class=\"devdocs-code-label\">org manifest"}[archetype])) |
| 105 | assert shown == json.loads(data.MANIFEST_EXAMPLES[archetype]) |
| 106 | assert set(shown) == _aliases(ProfileManifest), "an example must show every field the endpoint returns, camelCase" |
| 107 | again = ProfileManifest.model_validate(shown) |
| 108 | assert again.model_dump(mode="json", by_alias=True) == shown |
| 109 | assert again.identity_type == archetype |
| 110 | |
| 111 | |
| 112 | def test_manifest_field_table_names_every_field(html: str) -> None: |
| 113 | section = _after_id(html, "manifest").split('id="attestations"', 1)[0] |
| 114 | cells = " ".join(r[0] for r in _table_rows(section.split("</pre>", 1)[1])) |
| 115 | missing = sorted(a for a in _aliases(ProfileManifest) if a not in cells) |
| 116 | assert not missing, f"fields the manifest returns but the field table does not name: {missing}" |
| 117 | |
| 118 | |
| 119 | def test_agent_and_org_fields_match_the_models(html: str) -> None: |
| 120 | agent = json.loads(data.MANIFEST_EXAMPLES["agent"]) |
| 121 | org = json.loads(data.MANIFEST_EXAMPLES["org"]) |
| 122 | assert set(agent["trustChain"][0]) == _aliases(TrustChainEntry) == {"handle", "identityType", "spawnedBy"} |
| 123 | assert set(org["org"]) == _aliases(OrgManifest) == {"members", "quorum", "treasuryAddress"} |
| 124 | # leaf first: the agent itself, then each spawnedBy parent up to the human root |
| 125 | chain = agent["trustChain"] |
| 126 | assert chain[0]["handle"] == agent["handle"] and chain[-1]["identityType"] == "human" |
| 127 | assert chain[0]["spawnedBy"] == chain[1]["handle"] |
| 128 | assert "expiresAt" not in agent and "expiresAt" not in _aliases(ProfileManifest) |
| 129 | |
| 130 | |
| 131 | def test_trust_chain_walk_has_a_cycle_guard() -> None: |
| 132 | src = inspect.getsource(__import__("musehub.services.musehub_profile", fromlist=["x"])._build_trust_chain) |
| 133 | assert "seen" in src and "not in seen" in src and src.index("chain: list") < src.index("while") |
| 134 | |
| 135 | |
| 136 | # ── DOC_PRF_05: the Spectral Sigil facts ─────────────────────────────────────────────────────────────────────── |
| 137 | |
| 138 | |
| 139 | def test_derive_hue_snippet_is_the_source(html: str) -> None: |
| 140 | shown = _pre_after(html, "musehub/services/spectral_sigil.py") |
| 141 | real = inspect.getsource(spectral_sigil.derive_hue).strip() |
| 142 | assert shown.strip() == real |
| 143 | ids = [hashlib.sha256(str(i).encode()).hexdigest() for i in range(50)] |
| 144 | assert all(spectral_sigil.derive_hue(i) == int(i[:8], 16) % 360 for i in ids) |
| 145 | with pytest.raises(ValueError): |
| 146 | spectral_sigil.derive_hue("sha256:" + ids[0]) # the page says: bare digest, no prefix |
| 147 | |
| 148 | |
| 149 | def test_palette_table_is_the_palette(html: str) -> None: |
| 150 | rows = {r[0]: r for r in _table_rows(_after_id(html, "sigil-palette"))[1:]} |
| 151 | for archetype in _ARCHETYPES: |
| 152 | sat, lit = spectral_sigil._palette(archetype, 0) |
| 153 | assert rows[archetype][1] == f"{sat}%" and rows[archetype][2] == f"{lit}%" |
| 154 | assert spectral_sigil._palette("anything-else", 0) == spectral_sigil._palette("human", 0) |
| 155 | |
| 156 | |
| 157 | def test_hue_is_independent_of_the_archetype() -> None: |
| 158 | """The page says the archetype changes saturation, lightness and core, never the hue.""" |
| 159 | for i in range(40): |
| 160 | hex_id = hashlib.sha256(f"id{i}".encode()).hexdigest() |
| 161 | hues = {t: _first(r"hsl\((\d+),", spectral_sigil.generate_sigil(hex_id, "x", t, {}).decode()) for t in _ARCHETYPES} |
| 162 | assert len(set(hues.values())) == 1 and int(hues["human"]) == spectral_sigil.derive_hue(hex_id) |
| 163 | hues_seen = {spectral_sigil.derive_hue(hashlib.sha256(f"o{i}".encode()).hexdigest()) for i in range(400)} |
| 164 | assert min(hues_seen) < 20 and max(hues_seen) > 340, "every archetype spans the whole hue wheel" |
| 165 | |
| 166 | |
| 167 | def test_domain_colour_table_is_the_generator_map(html: str) -> None: |
| 168 | rows = {r[0]: r[1] for r in _table_rows(_after_id(html, "sigil-domains"))[1:]} |
| 169 | assert rows == dict(spectral_sigil.DOMAIN_COLORS) |
| 170 | svg = spectral_sigil.generate_sigil("ab" * 32, "x", "human", {"quartz": 3}).decode() |
| 171 | assert 'fill="#888888"' in svg, "an unlisted domain gets #888888" |
| 172 | |
| 173 | |
| 174 | def test_layer_facts() -> None: |
| 175 | ids = [hashlib.sha256(f"id{i}".encode()).hexdigest() for i in range(120)] |
| 176 | for hex_id in ids: |
| 177 | for archetype in _ARCHETYPES: |
| 178 | svg = spectral_sigil.generate_sigil(hex_id, "gabriel", archetype, {}).decode() |
| 179 | assert svg.count("<ellipse") == 2, "two orbital rings" |
| 180 | assert svg.count("<circle") == 3 and 'fill="#666666"' in svg and 'opacity="0.4"' in svg, "dormant dots" |
| 181 | assert 'fill="hsl(' in svg.split("<rect", 1)[1].split("/>", 1)[0] and "20%,8%" in svg, "fixed background" |
| 182 | sides = len(_first(r'<polygon points="([^"]+)"', spectral_sigil.generate_sigil(hex_id, "o", "org", {}).decode()).split()) |
| 183 | assert 5 <= sides <= 8 |
| 184 | assert sides == 5 + ((bytes.fromhex(hex_id)[4] >> 6) & 3), "N comes from the high bits of byte 4" |
| 185 | org = spectral_sigil.generate_sigil(ids[0], "o", "org", {}).decode() |
| 186 | assert org.count("<line") == 3, "three diagonals" |
| 187 | assert spectral_sigil.generate_sigil(ids[0], "gabriel", "human", {}) == spectral_sigil.generate_sigil(ids[0], "gabriel", "human", {}) |
| 188 | initials = [_first(r">([^<]*)</text>", spectral_sigil.generate_sigil(ids[1], h, "human", {}).decode()) for h in ("gabriel", "")] |
| 189 | assert initials == ["G", "?"], "upper-cased first letter, '?' for an empty handle" |
| 190 | |
| 191 | |
| 192 | def test_avatar_route_facts() -> None: |
| 193 | from musehub.api.routes.musehub import ui_avatars |
| 194 | |
| 195 | assert ui_avatars._SUPPORTED_ALGOS == frozenset({"sha256"}) |
| 196 | pattern = ui_avatars._HEX_RE["sha256"] |
| 197 | assert pattern.match("a" * 64) and not pattern.match("A" * 64) and not pattern.match("a" * 63) |
| 198 | assert ui_avatars._CACHE_HEADERS["Cache-Control"] == "public, max-age=31536000, immutable" |
| 199 | src = inspect.getsource(ui_avatars.get_sigil_by_handle) |
| 200 | assert 'max-age=86400' in src and "len(handle) > 128" in src and '"agent"' in src and "sha256(handle.encode())" in src |
| 201 | |
| 202 | |
| 203 | def test_sigil_curl_example_uses_no_unregistered_digest(rendered: dict[str, str]) -> None: |
| 204 | """The page's first example used a digest that no host has registered (404 on staging and production).""" |
| 205 | raw = rendered[PAGE] # still HTML-escaped: the <hex> placeholder is <hex> |
| 206 | block = raw.split("fetch a sigil", 1)[1].split("<pre><code>", 1)[1].split("</code></pre>", 1)[0] |
| 207 | assert "41dfaf048e4979cb" not in raw and not re.search(r"avatars/sha256/[0-9a-f]{64}", block) |
| 208 | assert "/api/profiles/gabriel" in block and "/avatars/sha256/<hex>.svg" in block and "/avatars/handle/gabriel.svg" in block |
| 209 | |
| 210 | |
| 211 | def test_page_states_the_route_facts(text: str) -> None: |
| 212 | for fragment in ( |
| 213 | "Cache-Control: public, max-age=31536000, immutable", |
| 214 | "exactly 64 lowercase hex characters", |
| 215 | "Cache-Control: public, max-age=86400", |
| 216 | "longer than 128 characters is a 400", |
| 217 | "upper-cased", |
| 218 | "without the sha256: prefix", |
| 219 | "fixed saturation 20 % and lightness 8 %", |
| 220 | "The manifest has no expiresAt", |
| 221 | ): |
| 222 | assert fragment in text, fragment |
| 223 | |
| 224 | |
| 225 | # ── DOC_PRF_06: the V1 figure is measured, and complete without script ────────────────────────────────────────── |
| 226 | |
| 227 | |
| 228 | def test_figure_cells_are_the_measured_byte_maps(html: str) -> None: |
| 229 | fig = html.split('id="sigil-anatomy-figure"', 1)[1].split("</figure>", 1)[0] |
| 230 | cards = fig.split('class="pfig__card"')[1:] |
| 231 | assert len(cards) == len(data.FIXTURES) == 3 |
| 232 | for card, (archetype, handle) in zip(cards, data.FIXTURES, strict=True): |
| 233 | hex_id = data.fixture_digest(archetype) |
| 234 | served = data.bytes_read(hex_id, handle, archetype, {}) |
| 235 | active = data.bytes_read(hex_id, handle, archetype, data.ACTIVE_COUNTS) |
| 236 | cells = re.findall(r'<li class="pfig__byte pfig__byte--(\w+)( pfig__byte--unread)?"\s*><span class="pfig__idx">(\d+)</span>', card) |
| 237 | assert [int(c[2]) for c in cells] == list(range(32)) |
| 238 | assert [c[0] for c in cells] == list(data.LAYER_OF_BYTE) |
| 239 | assert {int(c[2]) for c in cells if not c[1]} == set(served) |
| 240 | unread = ", ".join(str(i) for i in sorted(set(range(32)) - active)) |
| 241 | only_active = ", ".join(str(i) for i in sorted(active - served)) |
| 242 | assert f"Not read at all: {unread}." in " ".join(card.split()) |
| 243 | assert f"supplied (no route supplies them): {only_active}." in " ".join(card.split()) |
| 244 | assert generate_matches(card, hex_id, handle, archetype) |
| 245 | # facts the legend states about the measured maps |
| 246 | human, agent, org = data.SIGIL_CARDS |
| 247 | assert agent.served & {5, 6, 7} == set(), "an agent reads only byte 4 of the core" |
| 248 | assert {11, 15} & human.active == set() and {24, 25, 26, 27, 28, 29, 30, 31} & human.active == set() |
| 249 | assert human.served & {16, 17, 18} == {16, 17, 18} and not human.served & {19, 20, 21, 22, 23} |
| 250 | assert set(range(19, 24)) <= human.active - human.served |
| 251 | |
| 252 | |
| 253 | def generate_matches(card: str, hex_id: str, handle: str, archetype: str) -> bool: |
| 254 | svg = spectral_sigil.generate_sigil(hex_id, handle, archetype, {}).decode() |
| 255 | return html_lib.unescape(svg) in html_lib.unescape(card) |
| 256 | |
| 257 | |
| 258 | def test_figure_is_accessible_and_script_free(html: str) -> None: |
| 259 | fig = html.split('id="sigil-anatomy-figure"', 1)[1].split("</figure>", 1)[0] |
| 260 | assert 'aria-labelledby="sigil-anatomy-figure-title"' in html |
| 261 | assert fig.count('role="img"') == 3 and fig.count('aria-label="Spectral Sigil for the') == 3 |
| 262 | assert "<script" not in fig and ' style="' not in fig and "onclick" not in fig |
| 263 | assert fig.count("<caption>") == 1 and 'scope="col"' in fig and 'scope="row"' in fig |
| 264 | assert "read</span>" in fig and "not read</span>" in fig, "the read state is text, not only colour" |
| 265 | |
| 266 | |
| 267 | # ── DOC_PRF_07: the API table is the router ──────────────────────────────────────────────────────────────────── |
| 268 | |
| 269 | |
| 270 | def _norm(path: str) -> str: |
| 271 | return re.sub(r"\{[^}]+\}", "{}", path.split("?", 1)[0]) |
| 272 | |
| 273 | |
| 274 | def test_api_table_is_the_route_table(html: str) -> None: |
| 275 | from musehub.api.routes.api.profiles import router as profiles_router |
| 276 | from musehub.api.routes.musehub import ui_avatars, ui_user_profile |
| 277 | |
| 278 | rows = _table_rows(_after_id(html, "api"))[1:] |
| 279 | documented = {(r[0], _norm(r[1])) for r in rows} |
| 280 | assert len(documented) == len(rows) == 10 |
| 281 | |
| 282 | real = _route_pairs(profiles_router) | _route_pairs(ui_avatars.router) | _route_pairs(ui_user_profile.router, only="/{handle}") |
| 283 | assert documented == real, f"documented only: {documented - real}; routed only: {real - documented}" |
| 284 | |
| 285 | |
| 286 | def test_api_table_query_parameters_exist() -> None: |
| 287 | from musehub.api.routes.api import profiles |
| 288 | |
| 289 | revoke = inspect.signature(profiles.revoke_attestation).parameters["revoker"] |
| 290 | assert revoke.default.is_required(), "revoker is required" |
| 291 | ledger = inspect.signature(profiles.get_mpay_ledger).parameters["limit"].default |
| 292 | assert (ledger.default, ledger.metadata[0].ge, ledger.metadata[1].le) == (100, 1, 500) |
| 293 | for fn, name in ((profiles.list_attestations, "include_revoked"), (profiles.list_attestation_types, "include_deprecated")): |
| 294 | assert name in inspect.signature(fn).parameters |
| 295 | |
| 296 | |
| 297 | def test_manifest_404_text(html: str) -> None: |
| 298 | src = inspect.getsource(__import__("musehub.api.routes.api.profiles", fromlist=["x"]).get_profile_manifest) |
| 299 | assert "Profile '{handle}' not found" in src and "status_code=404" in src |
| 300 | assert "Profile '{handle}' not found" in html |
| 301 | |
| 302 | |
| 303 | # ── DOC_PRF_08: the MCP table is the registry ────────────────────────────────────────────────────────────────── |
| 304 | |
| 305 | |
| 306 | def test_mcp_table_is_the_registry(html: str) -> None: |
| 307 | from musehub.mcp.tools import musehub as tools |
| 308 | |
| 309 | registry = {t["name"]: t for v in vars(tools).values() if isinstance(v, (list, tuple)) for t in v |
| 310 | if isinstance(t, dict) and "name" in t and "inputSchema" in t} |
| 311 | rows = _table_rows(_after_id(html, "mcp-tools"))[1:] |
| 312 | assert len(rows) == 6 |
| 313 | for name, args, _desc in rows: |
| 314 | schema = registry[name]["inputSchema"] |
| 315 | assert set(re.split(r",\s*", args)) == set(schema["properties"]), name |
| 316 | assert set(schema["required"]) <= set(schema["properties"]) |
| 317 | |
| 318 | |
| 319 | # ── DOC_PRF_09: what the profile page renders today (pinned against the template) ───────────────────────────── |
| 320 | |
| 321 | |
| 322 | def test_rendered_today_matches_the_profile_template(html: str) -> None: |
| 323 | tpl = (ROOT / "musehub/templates/musehub/pages/profile.html").read_text() |
| 324 | panels = re.findall(r"<h2>(.*?)</h2>", tpl) |
| 325 | for name in ("Capabilities & Scope", "Member Roster", "Activity Canvas", "Attestations", "Provenance Chain", |
| 326 | "Spawned Agents", "Recent Activity"): |
| 327 | assert name in panels, name |
| 328 | assert any("Repositor" in p for p in panels) |
| 329 | # conditions per archetype, as the page's table says |
| 330 | assert re.search(r"is_agent and identity\.agent_capabilities %\}\s*<section[^>]*>\s*<div[^>]*>\s*<h2>Capabilities", tpl) |
| 331 | assert re.search(r"is_org and org_manifest %\}\s*<section[^>]*>\s*<div[^>]*>\s*<h2>Member Roster", tpl) |
| 332 | assert re.search(r"if is_agent %\}\s*<section[^>]*>\s*<div[^>]*>\s*<h2>Provenance Chain", tpl) |
| 333 | assert re.search(r"not is_agent and agent_fleet %\}\s*<section[^>]*>\s*<div[^>]*>\s*<h2>Spawned Agents", tpl) |
| 334 | assert "attestation_badges or attestations_given" in tpl |
| 335 | # "API only" / "not implemented" rows: none of these is rendered by the HTML page |
| 336 | for absent in ("mpay", "nano", "avax", "pinned", "expired", "work ledger", "max_spend"): |
| 337 | assert absent not in tpl.lower(), f"profile.html now renders '{absent}': update the 'Rendered today' table and #{_T_DESIGN}" |
| 338 | assert "expires:" in tpl and "scope:" in tpl |
| 339 | |
| 340 | |
| 341 | def test_activity_canvas_semantics(html: str) -> None: |
| 342 | from musehub.services import musehub_profile as svc |
| 343 | |
| 344 | assert svc._GRID_DAYS == 364 and svc._CONTRIBUTION_WEEKS == 52 |
| 345 | assert svc._CANVAS_EXCLUDED_DOMAINS == frozenset({"identity", "social"}) |
| 346 | assert svc._normalise_domain_slug(None) == "code" and svc._normalise_domain_slug("sha256:abc") == "code" |
| 347 | assert svc._date_to_grid_index(datetime(2026, 1, 10, tzinfo=timezone.utc), datetime(2026, 1, 10, tzinfo=timezone.utc)) == 363 |
| 348 | today = datetime(2026, 1, 10, tzinfo=timezone.utc) |
| 349 | assert svc._date_to_grid_index(today, today - timedelta(days=363)) == 0, "index 0 is the oldest of the 364 days" |
| 350 | assert svc._date_to_grid_index(today, today - timedelta(days=364)) is None |
| 351 | tpl = (ROOT / "musehub/templates/musehub/pages/profile.html").read_text() |
| 352 | assert "(val / dom.peak * 4) | round | int), 4] | min" in tpl, "intensity = round(count / peak * 4), capped at 4" |
| 353 | assert svc._MAX_PINNED == 6 |
| 354 | |
| 355 | |
| 356 | def test_expiry_rejection_is_in_request_signing() -> None: |
| 357 | src = (ROOT / "musehub/auth/request_signing.py").read_text() |
| 358 | head = src.split("if identity.expires_at is not None:", 1)[1] |
| 359 | assert head.index("Identity has expired.") < head.index("key_rows") |
| 360 | assert "HTTP_401_UNAUTHORIZED" in head[:400] |
| 361 | |
| 362 | |
| 363 | # ── Links the warnings carry ─────────────────────────────────────────────────────────────────────────────────── |
| 364 | |
| 365 | |
| 366 | def test_warning_links(html: str) -> None: |
| 367 | for url in (f"{HUB_ISSUES}{_T_DESIGN}", f"{HUB_ISSUES}{_T_MODEL_FIX}", f"{MUSE_ISSUES}{_T_MPAY_CLI}"): |
| 368 | assert f'href="{url}"' in html, url |
| 369 | for anchor in ("/muse/identity#mpay", "/muse/identity#attestations"): |
| 370 | assert f'href="{anchor}"' in html |
| 371 | |
| 372 | |
| 373 | def test_cross_page_anchors_exist(rendered: dict[str, str]) -> None: |
| 374 | identity = rendered[rc.phase_path("identity")] |
| 375 | assert 'id="mpay"' in identity and 'id="attestations"' in identity |
| 376 | |
| 377 | |
| 378 | # ── Known defects: strict xfails that flip when fixed (remove the warning in the same change) ────────────────── |
| 379 | |
| 380 | |
| 381 | class _Result: |
| 382 | def __init__(self, rows: list[dict[str, object]]) -> None: |
| 383 | self._rows = rows |
| 384 | |
| 385 | def mappings(self) -> "_Result": |
| 386 | return self |
| 387 | |
| 388 | def all(self) -> list[dict[str, object]]: |
| 389 | return self._rows |
| 390 | |
| 391 | def one(self) -> dict[str, object]: |
| 392 | (row,) = self._rows |
| 393 | return row |
| 394 | |
| 395 | |
| 396 | class _LedgerSession: |
| 397 | """A database stand-in for the ledger's queries over a fixed claim set: the claim lists apply |
| 398 | ``ORDER BY created_at DESC LIMIT :limit``; the totals query sums every non-voided claim.""" |
| 399 | |
| 400 | def __init__(self, claims: list[dict[str, object]]) -> None: |
| 401 | self.claims = claims |
| 402 | |
| 403 | async def execute(self, clause: object, params: dict[str, object]) -> _Result: |
| 404 | sql = str(clause) |
| 405 | live = [c for c in self.claims if c["voided_at"] is None] |
| 406 | if "SUM(amount_nano)" in sql: |
| 407 | return _Result([{ |
| 408 | "total_sent_nano": sum(int(c["amount_nano"]) for c in live if c["sender"] == params["handle"]), # type: ignore[call-overload] |
| 409 | "total_received_nano": sum(int(c["amount_nano"]) for c in live if c["recipient"] == params["handle"]), # type: ignore[call-overload] |
| 410 | }]) |
| 411 | column = "sender" if "sender = :handle" in sql else "recipient" |
| 412 | rows = [c for c in self.claims if c[column] == params["handle"] and c["voided_at"] is None] |
| 413 | rows.sort(key=lambda c: c["created_at"], reverse=True) # type: ignore[arg-type, return-value] |
| 414 | return _Result(rows[: int(params["limit"])]) # type: ignore[call-overload] |
| 415 | |
| 416 | |
| 417 | def _claims(n: int) -> list[dict[str, object]]: |
| 418 | now = datetime(2026, 11, 1, tzinfo=timezone.utc) |
| 419 | return [ |
| 420 | {"claim_id": f"sha256:{i:064x}", "sender": "a", "recipient": "b", "amount_nano": 1, "nonce_hex": f"{i:064x}", |
| 421 | "signature": "ed25519:x", "sender_public_key": "ed25519:y", "memo": None, |
| 422 | "created_at": now.replace(second=i % 60, minute=i // 60), "confirmed_at": None, "voided_at": None} |
| 423 | for i in range(n) |
| 424 | ] |
| 425 | |
| 426 | |
| 427 | def test_ledger_claim_lists_are_limited() -> None: |
| 428 | """The documented behaviour: newest ``limit`` claims per direction.""" |
| 429 | ledger = asyncio.run(musehub_mpay.get_mpay_ledger(_LedgerSession(_claims(150)), "b", limit=100)) # type: ignore[arg-type] |
| 430 | assert len(ledger.received) == 100 and ledger.sent == [] |
| 431 | one = asyncio.run(musehub_mpay.get_mpay_ledger(_LedgerSession(_claims(150)), "b", limit=1)) # type: ignore[arg-type] |
| 432 | assert len(one.received) == 1 |
| 433 | |
| 434 | |
| 435 | def test_ledger_totals_cover_every_claim() -> None: |
| 436 | """musehub#301: the totals sum every non-voided claim; ``limit`` bounds only the claim lists.""" |
| 437 | ledger = asyncio.run(musehub_mpay.get_mpay_ledger(_LedgerSession(_claims(150)), "b", limit=100)) # type: ignore[arg-type] |
| 438 | assert ledger.total_received_nano == 150 |
| 439 | |
| 440 | |
| 441 | def test_page_says_the_totals_cover_every_claim(text: str) -> None: |
| 442 | assert "the sum of every non-voided claim in each direction, however many there are" in text |
| 443 | assert "with the totals of every non-voided claim (limit bounds only the lists)" in text |
| 444 | |
| 445 | |
| 446 | def test_sigil_routes_supply_activity_counts() -> None: |
| 447 | """musehub#302 (fixed): no served route passes an empty domain_counts.""" |
| 448 | for rel in ("musehub/api/routes/musehub/ui_avatars.py", "musehub/services/opengraph_cards.py"): |
| 449 | tree = ast.parse((ROOT / rel).read_text()) |
| 450 | calls = [n for n in ast.walk(tree) if isinstance(n, ast.Call) and getattr(n.func, "id", getattr(n.func, "attr", "")) == "generate_sigil"] |
| 451 | assert calls, rel |
| 452 | for call in calls: |
| 453 | counts = next(k.value for k in call.keywords if k.arg == "domain_counts") |
| 454 | assert not (isinstance(counts, ast.Dict) and not counts.keys), f"{rel}:{call.lineno} passes an empty domain_counts" |
| 455 | |
| 456 | |
| 457 | def test_org_roster_has_no_hardcoded_values() -> None: |
| 458 | """musehub#303: the roster renders only stored data (handles, quorum, treasury address).""" |
| 459 | tpl = (ROOT / "musehub/templates/musehub/pages/profile.html").read_text() |
| 460 | roster = tpl.split("<h2>Member Roster</h2>", 1)[1].split("</section>", 1)[0] |
| 461 | assert "roster-role" not in roster and "roster-weight" not in roster and "Voting weight" not in roster |
| 462 | assert "org_manifest.quorum" in roster and "org_manifest.treasury_address" in roster |
| 463 | |
| 464 | |
| 465 | def test_known_defect_warnings_are_present_until_fixed(text: str) -> None: |
| 466 | """These warnings are removed in the commit that fixes the defect (the strict xfails above flip then).""" |
| 467 | assert "no served route supplies activity counts" not in text # musehub#302 fixed |
File History
5 commits
sha256:c4c154d26740ebed7e38471f96d2f3eadd64677fa3d8ad35a2a2e0593e0f9bfd
fix(profiles): sigil dots reflect activity — repositories p…
Opus 5.5
patch
1 day ago
sha256:f19d5e4a89766fc91b926cdf801255e12dcd968041c0ece8adf6627760788d22
merge: next build — MCP (#291 #292 #295 #324), profiles/sit…
Opus 5.5
minor
⚠
1 day ago
sha256:7a1f4dfd571e937cb1032574d5c0965ba04ad520adcf523dec123d7a34746236
merge: rc26 — profiles/site wave (#119 #301 #303 #307 #314;…
Opus 5.5
minor
⚠
1 day ago
sha256:d5a444bc3d2142a9e90f5dd56f4f51fdfccdd0e4c87d3b90702914c5d99470a3
fix(profiles): MPay totals cover every claim; org roster sh…
Opus 5.5
minor
⚠
2 days ago
sha256:4294c765f86bae7ca565b02af974c56bcd0e4288a71fcf1e3038231106f56ec1
docs(profiles): #256 Identity Profiles QA contract v2 (repl…
Opus 5.5
minor
⚠
9 days ago